Programs & Examples On #Setparent

How to get screen width without (minus) scrollbar?

.prop("clientWidth") and .prop("scrollWidth")

var actualInnerWidth = $("body").prop("clientWidth"); // El. width minus scrollbar width
var actualInnerWidth = $("body").prop("scrollWidth"); // El. width minus scrollbar width

in JavaScript:

var actualInnerWidth = document.body.clientWidth;     // El. width minus scrollbar width
var actualInnerWidth = document.body.scrollWidth;     // El. width minus scrollbar width

P.S: Note that to use scrollWidth reliably your element should not overflow horizontally

jsBin demo


You could also use .innerWidth() but this will work only on the body element

var innerWidth = $('body').innerWidth(); // Width PX minus scrollbar 

Check if element is visible on screen

--- Shameless plug ---
I have added this function to a library I created vanillajs-browser-helpers: https://github.com/Tokimon/vanillajs-browser-helpers/blob/master/inView.js
-------------------------------

Well BenM stated, you need to detect the height of the viewport + the scroll position to match up with your top position. The function you are using is ok and does the job, though its a bit more complex than it needs to be.

If you don't use jQuery then the script would be something like this:

function posY(elm) {
    var test = elm, top = 0;

    while(!!test && test.tagName.toLowerCase() !== "body") {
        top += test.offsetTop;
        test = test.offsetParent;
    }

    return top;
}

function viewPortHeight() {
    var de = document.documentElement;

    if(!!window.innerWidth)
    { return window.innerHeight; }
    else if( de && !isNaN(de.clientHeight) )
    { return de.clientHeight; }
    
    return 0;
}

function scrollY() {
    if( window.pageYOffset ) { return window.pageYOffset; }
    return Math.max(document.documentElement.scrollTop, document.body.scrollTop);
}

function checkvisible( elm ) {
    var vpH = viewPortHeight(), // Viewport Height
        st = scrollY(), // Scroll Top
        y = posY(elm);
    
    return (y > (vpH + st));
}

Using jQuery is a lot easier:

function checkVisible( elm, evalType ) {
    evalType = evalType || "visible";

    var vpH = $(window).height(), // Viewport Height
        st = $(window).scrollTop(), // Scroll Top
        y = $(elm).offset().top,
        elementHeight = $(elm).height();

    if (evalType === "visible") return ((y < (vpH + st)) && (y > (st - elementHeight)));
    if (evalType === "above") return ((y < (vpH + st)));
}

This even offers a second parameter. With "visible" (or no second parameter) it strictly checks whether an element is on screen. If it is set to "above" it will return true when the element in question is on or above the screen.

See in action: http://jsfiddle.net/RJX5N/2/

I hope this answers your question.

-- IMPROVED VERSION--

This is a lot shorter and should do it as well:

function checkVisible(elm) {
  var rect = elm.getBoundingClientRect();
  var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
  return !(rect.bottom < 0 || rect.top - viewHeight >= 0);
}

with a fiddle to prove it: http://jsfiddle.net/t2L274ty/1/

And a version with threshold and mode included:

function checkVisible(elm, threshold, mode) {
  threshold = threshold || 0;
  mode = mode || 'visible';

  var rect = elm.getBoundingClientRect();
  var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
  var above = rect.bottom - threshold < 0;
  var below = rect.top - viewHeight + threshold >= 0;

  return mode === 'above' ? above : (mode === 'below' ? below : !above && !below);
}

and with a fiddle to prove it: http://jsfiddle.net/t2L274ty/2/

jQuery scrollTop() doesn't seem to work in Safari or Chrome (Windows)

I was facing this problem, I created this link at the bottom and implemented the jQuery scrollTop code and it worked perfectly in Firefox, IE, Opera but didn't work in Chrome and Safari. I'm learning jQuery so I don't know if this solution is technically perfect but this worked for me. I just implemented 2 ScrollTop codes the first one uses $('html') which works for Firefox, etc. The second one uses $('html body') this works for Chrome and Safari.

$('a#top').click(function() {

    $('html').animate({scrollTop: 0}, 'slow');
    return false;

    $('html body').animate({scrollTop: 0}, 'slow');
    return false;
});

Pure CSS scroll animation

You can use my script from CodePen by just wrapping all the content within a .levit-container DIV.

~function  () {
    function Smooth () {
        this.$container = document.querySelector('.levit-container');
        this.$placeholder = document.createElement('div');
    }

    Smooth.prototype.init = function () {
        var instance = this;

        setContainer.call(instance);
        setPlaceholder.call(instance);
        bindEvents.call(instance);
    }

    function bindEvents () {
        window.addEventListener('scroll', handleScroll.bind(this), false);
    }

    function setContainer () {
        var style = this.$container.style;

        style.position = 'fixed';
        style.width = '100%';
        style.top = '0';
        style.left = '0';
        style.transition = '0.5s ease-out';
    }

    function setPlaceholder () {
        var instance = this,
                $container = instance.$container,
                $placeholder = instance.$placeholder;

        $placeholder.setAttribute('class', 'levit-placeholder');
        $placeholder.style.height = $container.offsetHeight + 'px';
        document.body.insertBefore($placeholder, $container);
    }

    function handleScroll () {
        this.$container.style.transform = 'translateZ(0) translateY(' + (window.scrollY * (- 1)) + 'px)';
    }

    var smooth = new Smooth();
    smooth.init();
}();

https://codepen.io/acauamontiel/pen/zxxebb?editors=0010

Programmatically switching between tabs within Swift

If you want to do this from code that you are writing as part of a particular view controller, like in response to a button press or something, you can do this:

@IBAction func pushSearchButton(_ sender: UIButton?) {
    if let tabBarController = self.navigationController?.tabBarController  {
        tabBarController.selectedIndex = 1
    }
}

And you can also add code to handle tab switching using the UITabBarControllerDelegate methods. Using tags on the base view controllers of each tab, you can see where you are and act accordingly: For example

func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
    
    // if we didn't change tabs, don't do anything
    if tabBarController.selectedViewController?.tabBarItem.tag ==  viewController.tabBarItem.tag {
        return false
    }
    
    if viewController.tabBarItem.tag == 4096 { // some particular tab
        // do stuff appropriate for a transition to this particular tab
    }
    else if viewController.tabBarItem.tag == 2048 { // some other tab
        // do stuff appropriate for a transition to this other tab
    }
}

Select a row from html table and send values onclick of a button

You can access the first element adding the following code to the highlight function

$(this).find(".selected td:first").html()

Working Code:JSFIDDLE

Running multiple commands with xargs

Another possible solution that works for me is something like -

cat a.txt | xargs bash -c 'command1 $@; command2 $@' bash

Note the 'bash' at the end - I assume it is passed as argv[0] to bash. Without it in this syntax the first parameter to each command is lost. It may be any word.

Example:

cat a.txt | xargs -n 5 bash -c 'echo -n `date +%Y%m%d-%H%M%S:` ; echo " data: " $@; echo "data again: " $@' bash

Looping from 1 to infinity in Python

Reiterating thg435's comment:

from itertools import takewhile, count

def thereIsAReasonToContinue(i):
    return not thereIsAReasonToBreak(i)

for i in takewhile(thereIsAReasonToContinue, count()):
    pass # or something else

Or perhaps more concisely:

from itertools import takewhile, count

for i in takewhile(lambda x : not thereIsAReasonToBreak(x), count()):
    pass # or something else

takewhile imitates a "well-behaved" C for loop: you have a continuation condition, but you have a generator instead of an arbitrary expression. There are things you can do in a C for loop that are "badly behaved", such as modifying i in the loop body. It's possible to imitate those too using takewhile, if the generator is a closure over some local variable i that you then mess with. In a way, defining that closure makes it especially obvious that you're doing something potentially confusing with your control structure.

Converting String to Int with Swift

Useful for String to Int and other type

extension String {
        //Converts String to Int
        public func toInt() -> Int? {
            if let num = NumberFormatter().number(from: self) {
                return num.intValue
            } else {
                return nil
            }
        }

        //Converts String to Double
        public func toDouble() -> Double? {
            if let num = NumberFormatter().number(from: self) {
                return num.doubleValue
            } else {
                return nil
            }
        }

        /// EZSE: Converts String to Float
        public func toFloat() -> Float? {
            if let num = NumberFormatter().number(from: self) {
                return num.floatValue
            } else {
                return nil
            }
        }

        //Converts String to Bool
        public func toBool() -> Bool? {
            return (self as NSString).boolValue
        }
    }

Use it like :

"123".toInt() // 123

How to properly create composite primary keys - MYSQL

Aside from personal design preferences, there are cases where one wants to make use of composite primary keys. Tables may have two or more fields that provide a unique combination, and not necessarily by way of foreign keys.

As an example, each US state has a set of unique Congressional districts. While many states may individually have a CD-5, there will never be more than one CD-5 in any of the 50 states, and vice versa. Therefore, creating an autonumber field for Massachusetts CD-5 would be redundant.

If the database drives a dynamic web page, writing code to query on a two-field combination could be much simpler than extracting/resubmitting an autonumbered key.

So while I'm not answering the original question, I certainly appreciate Adam's direct answer.

Where can I find System.Web.Helpers, System.Web.WebPages, and System.Web.Razor?

I had the same problem , first I couldn't find those dlls in the list of .NET components . but later I figured it out that the solution is :

1- first I changed target framework from .NET framework 4 client profile to .NET framework 4.

2- then scroll down the list of .NET components , pass first list of system.web... , scroll down , and find the second list of system.web... at the bottom , they're there .

I hope this could help others

error, string or binary data would be truncated when trying to insert

Another situation in which you can get this error is the following:

I had the same error and the reason was that in an INSERT statement that received data from an UNION, the order of the columns was different from the original table. If you change the order in #table3 to a, b, c, you will fix the error.

select a, b, c into #table1
from #table0

insert into #table1
    select a, b, c from #table2
    union
    select a, c, b from #table3

Execute a batch file on a remote PC using a batch file on local PC

Use microsoft's tool for remote commands executions: PsExec

If there isn't your bat-file on remote host, copy it first. For example:

copy D:\apache-tomcat-6.0.20\apache-tomcat-7.0.30\bin\shutdown.bat \\RemoteServerNameOrIP\d$\apache-tomcat-6.0.20\apache-tomcat-7.0.30\bin\

And then execute:

psexec \\RemoteServerNameOrIP d:\apache-tomcat-6.0.20\apache-tomcat-7.0.30\bin\shutdown.bat

Note: filepath for psexec is path to file on remote server, not your local.

Changing the default title of confirm() in JavaScript?

This is not possible, as you say, from a security stand point. The only way you could simulate it, is by creating a modeless dialog window.

There are many third-party javascript-plugins that you could use to fake this effect so you do not have to write all that code.

How do I do word Stemming or Lemmatization?

Try this one here: http://www.twinword.com/lemmatizer.php

I entered your query in the demo "cats running ran cactus cactuses cacti community communities" and got ["cat", "running", "run", "cactus", "cactus", "cactus", "community", "community"] with the optional flag ALL_TOKENS.

Sample Code

This is an API so you can connect to it from any environment. Here is what the PHP REST call may look like.

// These code snippets use an open-source library. http://unirest.io/php
$response = Unirest\Request::post([ENDPOINT],
  array(
    "X-Mashape-Key" => [API KEY],
    "Content-Type" => "application/x-www-form-urlencoded",
    "Accept" => "application/json"
  ),
  array(
    "text" => "cats running ran cactus cactuses cacti community communities"
  )
);

Circle drawing with SVG's arc path

For those like me who were looking for an ellipse attributes to path conversion:

const ellipseAttrsToPath = (rx,cx,ry,cy) =>
`M${cx-rx},${cy}a${rx},${ry} 0 1,0 ${rx*2},0a${rx},${ry} 0 1,0 -${rx*2},0`

TypeError: 'bool' object is not callable

Actually you can fix it with following steps -

  1. Do cls.__dict__
  2. This will give you dictionary format output which will contain {'isFilled':True} or {'isFilled':False} depending upon what you have set.
  3. Delete this entry - del cls.__dict__['isFilled']
  4. You will be able to call the method now.

In this case, we delete the entry which overrides the method as mentioned by BrenBarn.

Check if Nullable Guid is empty in c#

Check Nullable<T>.HasValue

if(!SomeProperty.HasValue ||SomeProperty.Value == Guid.Empty)
{
 //not valid GUID
}
else
{
 //Valid GUID
}

How to set up java logging using a properties file? (java.util.logging)

Are you searching for the log file in the right path: %h/one%u.log

Here %h resolves to your home : In windows this defaults to : C:\Documents and Settings(user_name).

I have tried the sample code you have posted and it works fine after you specify the configuration file path (logging.properties either through code or java args) .

How to add image in a TextView text?

This is partly based on this earlier answer above by @A Boschman. In that solution, I found that the input size of the image greatly affected the ability of makeImageSpan() to properly center-align the image. Additionally, I found that the solution affected text spacing by creating unnecessary line spacing.

I found BaseImageSpan (from Facebook's Fresco library) to do the job particularly well:

 /**
 * Create an ImageSpan for the given icon drawable. This also sets the image size. Works best
 * with a square icon because of the sizing
 *
 * @param context       The Android Context.
 * @param drawableResId A drawable resource Id.
 * @param size          The desired size (i.e. width and height) of the image icon in pixels.
 *                      Use the lineHeight of the TextView to make the image inline with the
 *                      surrounding text.
 * @return An ImageSpan, aligned with the bottom of the text.
 */
private static BetterImageSpan makeImageSpan(Context context, int drawableResId, int size) {
    final Drawable drawable = context.getResources().getDrawable(drawableResId);
    drawable.mutate();
    drawable.setBounds(0, 0, size, size);
    return new BetterImageSpan(drawable, BetterImageSpan.ALIGN_CENTER);
}

Then supply your betterImageSpan instance to spannable.setSpan() as usual

HTML5 iFrame Seamless Attribute

Still at 2014 seamless iframe is not fully supported by all of the major browsers, so you should look for an alternative solution.

By January 2014 seamless iframe is still not supported for Firefox neither IE 11, and it's supported by Chrome, Safari and Opera (the webkit version)

If you wanna check this and more supported options in detail, the HTML5 test site would be a good option:

http://html5test.com/results/desktop.html

You can check different platforms, at the score section you can click every browser and see what's supported and what's not.

Remove folder and its contents from git/GitHub's history

In addition to the popular answer above I would like to add a few notes for Windows-systems. The command

git filter-branch --tree-filter 'rm -rf node_modules' --prune-empty HEAD
  • works perfectly without any modification! Therefore, you must not use Remove-Item, del or anything else instead of rm -rf.

  • If you need to specify a path to a file or directory use slashes like ./path/to/node_modules

How can I easily view the contents of a datatable or dataview in the immediate window

I've not tried it myself, but Visual Studio 2005 (and later) support the concept of Debugger Visualizers. This allows you to customize how an object is shown in the IDE. Check out this article for more details.

http://davidhayden.com/blog/dave/archive/2005/12/26/2645.aspx

When to use cla(), clf() or close() for clearing a plot in matplotlib?

They all do different things, since matplotlib uses a hierarchical order in which a figure window contains a figure which may consist of many axes. Additionally, there are functions from the pyplot interface and there are methods on the Figure class. I will discuss both cases below.

pyplot interface

pyplot is a module that collects a couple of functions that allow matplotlib to be used in a functional manner. I here assume that pyplot has been imported as import matplotlib.pyplot as plt. In this case, there are three different commands that remove stuff:

plt.cla() clears an axes, i.e. the currently active axes in the current figure. It leaves the other axes untouched.

plt.clf() clears the entire current figure with all its axes, but leaves the window opened, such that it may be reused for other plots.

plt.close() closes a window, which will be the current window, if not specified otherwise.

Which functions suits you best depends thus on your use-case.

The close() function furthermore allows one to specify which window should be closed. The argument can either be a number or name given to a window when it was created using figure(number_or_name) or it can be a figure instance fig obtained, i.e., usingfig = figure(). If no argument is given to close(), the currently active window will be closed. Furthermore, there is the syntax close('all'), which closes all figures.

methods of the Figure class

Additionally, the Figure class provides methods for clearing figures. I'll assume in the following that fig is an instance of a Figure:

fig.clf() clears the entire figure. This call is equivalent to plt.clf() only if fig is the current figure.

fig.clear() is a synonym for fig.clf()

Note that even del fig will not close the associated figure window. As far as I know the only way to close a figure window is using plt.close(fig) as described above.

What are functional interfaces used for in Java 8?

You can use lambda in Java 8

public static void main(String[] args) {
    tentimes(inputPrm - > System.out.println(inputPrm));
    //tentimes(System.out::println);  // You can also replace lambda with static method reference
}

public static void tentimes(Consumer myFunction) {
    for (int i = 0; i < 10; i++)
        myFunction.accept("hello");
}

For further info about Java Lambdas and FunctionalInterfaces

How do you determine what SQL Tables have an identity column programmatically

In SQL 2005:

select object_name(object_id), name
from sys.columns
where is_identity = 1

Changing navigation title programmatically

In Swift 4:

Swift 4

override func viewDidLoad() {
    super.viewDidLoad()

    self.title = "Your title"
}

I hope it helps, regards!

How to delete SQLite database from Android programmatically

I have used the following for "formatting" the database on device after I have changed the structure of the database in assets. I simply uncomment the line in MainActivity when I wanted that the database is read from the assets again. This will reset the device database values and structure to mach with the preoccupied database in assets folder.

    //database initialization. Uncomment to clear the database
    //deleteDatabase("questions.db");

Next, I will implement a button that will run the deleteDatabase so that the user can reset its progress in the game.

How to concatenate int values in java?

public class joining {

    public static void main(String[] args) {
        int a=1; 
        int b=0;
        int c=2;
        int d=2;
        int e=1;

        String j = Long.toString(a);
        String k = Long.toString(b);
        String l = Long.toString(c);
        String m = Long.toString(d);
        String n = Long.toString(e);

       /* String s1=Long.toString(a);    // converting long to String
        String s2=Long.toString(b);
        String s3=s2+s1;
        long c=Long.valueOf(s3).longValue();    // converting String to long
        */

        System.out.println(j+k+l+m+n);  
    }
}

How do I "select Android SDK" in Android Studio?

I had the similar problem. I tried sync with gradle files and removed .idea folder but nothing works.

Here is what worked for me :

1.) Close android studio

2.) Remove c:/Users/{User}/.AndroidStudio{version} folder

Caution: It will remove all your installed plugins and settings. Try this if nothing works

Move entire line up and down in Vim

I put the following at the end of my .vimrc file:

noremap H ddkkp
noremap N ddp

So now 'H' and 'N' move current line up and down respectively.

How to make layout with rounded corners..?

I have done this way:

Check Screenshot:

Relative layout Background

Create drawable file named with custom_rectangle.xml in drawable folder:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <solid android:color="@android:color/white" />

    <corners android:radius="10dip" />

    <stroke
        android:width="1dp"
        android:color="@android:color/white" />

</shape>

Now apply Rectangle background on View:

mView.setBackground(R.drawlable.custom_rectangle);

Done

regex.test V.S. string.match to know if a string matches a regular expression

Don't forget to take into consideration the global flag in your regexp :

var reg = /abc/g;
!!'abcdefghi'.match(reg); // => true
!!'abcdefghi'.match(reg); // => true
reg.test('abcdefghi');    // => true
reg.test('abcdefghi');    // => false <=

This is because Regexp keeps track of the lastIndex when a new match is found.

Changing the selected option of an HTML Select element

You can change the value of the select element, which changes the selected option to the one with that value, using JavaScript:

document.getElementById('sel').value = 'bike';??????????

DEMO

How can I get a random number in Kotlin?

Building off of @s1m0nw1 excellent answer I made the following changes.

  1. (0..n) implies inclusive in Kotlin
  2. (0 until n) implies exclusive in Kotlin
  3. Use a singleton object for the Random instance (optional)

Code:

private object RandomRangeSingleton : Random()

fun ClosedRange<Int>.random() = RandomRangeSingleton.nextInt((endInclusive + 1) - start) + start

Test Case:

fun testRandom() {
        Assert.assertTrue(
                (0..1000).all {
                    (0..5).contains((0..5).random())
                }
        )
        Assert.assertTrue(
                (0..1000).all {
                    (0..4).contains((0 until 5).random())
                }
        )
        Assert.assertFalse(
                (0..1000).all {
                    (0..4).contains((0..5).random())
                }
        )
    }

switch case statement error: case expressions must be constant expression

I would like to mention that, I came across the same situation when I tried adding a library into my project. All of a sudden all switch statements started to show errors!

Now I tried to remove the library which I added, even then it did not work. how ever "when I cleaned the project" all the errors just went off !

Long Press in JavaScript?

I created long-press-event (0.5k pure JavaScript) to solve this, it adds a long-press event to the DOM.

Listen for a long-press on any element:

// the event bubbles, so you can listen at the root level
document.addEventListener('long-press', function(e) {
  console.log(e.target);
});

Listen for a long-press on a specific element:

// get the element
var el = document.getElementById('idOfElement');

// add a long-press event listener
el.addEventListener('long-press', function(e) {

    // stop the event from bubbling up
    e.preventDefault()

    console.log(e.target);
});

Works in IE9+, Chrome, Firefox, Safari & hybrid mobile apps (Cordova & Ionic on iOS/Android)

Demo

Reading InputStream as UTF-8

I ran into the same problem every time it finds a special character marks it as ??. to solve this, I tried using the encoding: ISO-8859-1

BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("txtPath"),"ISO-8859-1"));

while ((line = br.readLine()) != null) {

}

I hope this can help anyone who sees this post.

Enabling refreshing for specific html elements only

Try this in your script:

$("#YourElement").html(htmlData);

I do this in my table refreshment.

Convert decimal to binary in python

n=int(input('please enter the no. in decimal format: '))
x=n
k=[]
while (n>0):
    a=int(float(n%2))
    k.append(a)
    n=(n-a)/2
k.append(0)
string=""
for j in k[::-1]:
    string=string+str(j)
print('The binary no. for %d is %s'%(x, string))

How to make JavaScript execute after page load?

Keep in mind that loading the page has more than one stage. Btw, this is pure JavaScript

"DOMContentLoaded"

This event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. At this stage you could programmatically optimize loading of images and css based on user device or bandwidth speed.

Executes after DOM is loaded (before img and css):

document.addEventListener("DOMContentLoaded", function(){
    //....
});

Note: Synchronous JavaScript pauses parsing of the DOM. If you want the DOM to get parsed as fast as possible after the user requested the page, you could turn your JavaScript asynchronous and optimize loading of stylesheets

"load"

A very different event, load, should only be used to detect a fully-loaded page. It is an incredibly popular mistake to use load where DOMContentLoaded would be much more appropriate, so be cautious.

Exectues after everything is loaded and parsed:

window.addEventListener("load", function(){
    // ....
});

MDN Resources:

https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded https://developer.mozilla.org/en-US/docs/Web/Events/load

MDN list of all events:

https://developer.mozilla.org/en-US/docs/Web/Events

Java generics - ArrayList initialization

The key lies in the differences between references and instances and what the reference can promise and what the instance can really do.

ArrayList<A> a = new ArrayList<A>();

Here a is a reference to an instance of a specific type - exactly an array list of As. More explicitly, a is a reference to an array list that will accept As and will produce As. new ArrayList<A>() is an instance of an array list of As, that is, an array list that will accept As and will produce As.

ArrayList<Integer> a = new ArrayList<Number>(); 

Here, a is a reference to exactly an array list of Integers, i.e. exactly an array list that can accept Integers and will produce Integers. It cannot point to an array list of Numbers. That array list of Numbers can not meet all the promises of ArrayList<Integer> a (i.e. an array list of Numbers may produce objects that are not Integers, even though its empty right then).

ArrayList<Number> a = new ArrayList<Integer>(); 

Here, declaration of a says that a will refer to exactly an array list of Numbers, that is, exactly an array list that will accept Numbers and will produce Numbers. It cannot point to an array list of Integers, because the type declaration of a says that a can accept any Number, but that array list of Integers cannot accept just any Number, it can only accept Integers.

ArrayList<? extends Object> a= new ArrayList<Object>();

Here a is a (generic) reference to a family of types rather than a reference to a specific type. It can point to any list that is member of that family. However, the trade-off for this nice flexible reference is that they cannot promise all of the functionality that it could if it were a type-specific reference (e.g. non-generic). In this case, a is a reference to an array list that will produce Objects. But, unlike a type-specific list reference, this a reference cannot accept any Object. (i.e. not every member of the family of types that a can point to can accept any Object, e.g. an array list of Integers can only accept Integers.)

ArrayList<? super Integer> a = new ArrayList<Number>();

Again, a is a reference to a family of types (rather than a single specific type). Since the wildcard uses super, this list reference can accept Integers, but it cannot produce Integers. Said another way, we know that any and every member of the family of types that a can point to can accept an Integer. However, not every member of that family can produce Integers.

PECS - Producer extends, Consumer super - This mnemonic helps you remember that using extends means the generic type can produce the specific type (but cannot accept it). Using super means the generic type can consume (accept) the specific type (but cannot produce it).

ArrayList<ArrayList<?>> a

An array list that holds references to any list that is a member of a family of array lists types.

= new ArrayList<ArrayList<?>>(); // correct

An instance of an array list that holds references to any list that is a member of a family of array lists types.

ArrayList<?> a

An reference to any array list (a member of the family of array list types).

= new ArrayList<?>()

ArrayList<?> refers to any type from a family of array list types, but you can only instantiate a specific type.


See also How can I add to List<? extends Number> data structures?

Find element's index in pandas Series

Often your value occurs at multiple indices:

>>> myseries = pd.Series([0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1])
>>> myseries.index[myseries == 1]
Int64Index([3, 4, 5, 6, 10, 11], dtype='int64')

Can I have multiple :before pseudo-elements for the same element?

If your main element has some child elements or text, you could make use of it.

Position your main element relative (or absolute/fixed) and use both :before and :after positioned absolute (in my situation it had to be absolute, don't know about your's).

Now if you want one more pseudo-element, attach an absolute :before to one of the main element's children (if you have only text, put it in a span, now you have an element), which is not relative/absolute/fixed.

This element will start acting like his owner is your main element.

HTML

<div class="circle">
    <span>Some text</span>
</div>

CSS

.circle {
    position: relative; /* or absolute/fixed */
}

.circle:before {
    position: absolute;
    content: "";
    /* more styles: width, height, etc */
}

.circle:after {
    position: absolute;
    content: "";
    /* more styles: width, height, etc */
}

.circle span {
    /* not relative/absolute/fixed */
}

.circle span:before {
    position: absolute;
    content: "";
    /* more styles: width, height, etc */
}

LINQ - Left Join, Group By, and Count

 (from p in context.ParentTable     
  join c in context.ChildTable 
    on p.ParentId equals c.ChildParentId into j1 
  from j2 in j1.DefaultIfEmpty() 
     select new { 
          ParentId = p.ParentId,
         ChildId = j2==null? 0 : 1 
      })
   .GroupBy(o=>o.ParentId) 
   .Select(o=>new { ParentId = o.key, Count = o.Sum(p=>p.ChildId) })

How can I get the current stack trace in Java?

In Java 9 there is a new way:

public static void showTrace() {

  List<StackFrame> frames =
    StackWalker.getInstance( Option.RETAIN_CLASS_REFERENCE )
               .walk( stream  -> stream.collect( Collectors.toList() ) );

  for ( StackFrame stackFrame : frames )
    System.out.println( stackFrame );
}

remove inner shadow of text input

Set border: 1px solid black to make all sides equals and remove any kind of custom border (other than solid). Also, set box-shadow: none to remove any inset shadow applied to it.

Is there any way to have a fieldset width only be as wide as the controls in them?

You can always use CSS to constrain the width of the fieldset, which would also constrain the controls inside.

I find that I often have to constrain the width of select controls, or else really long option text will make it totally unmanageable.

Simple and fast method to compare images for similarity

If you can be sure to have precise alignment of your template (the icon) to the testing region, then any old sum of pixel differences will work.

If the alignment is only going to be a tiny bit off, then you can low-pass both images with cv::GaussianBlur before finding the sum of pixel differences.

If the quality of the alignment is potentially poor then I would recommend either a Histogram of Oriented Gradients or one of OpenCV's convenient keypoint detection/descriptor algorithms (such as SIFT or SURF).

How to count frequency of characters in a string?

There is one more option and it looks quite nice. Since java 8 there is new method merge java doc

  public static void main(String[] args) {
    String s = "aaabbbcca";

    Map<Character, Integer> freqMap = new HashMap<>();
    for (int i = 0; i < s.length(); i++) {
        Character c = s.charAt(i);
        freqMap.merge(c, 1, (a, b) -> a + b);
    }
    freqMap.forEach((k, v) -> System.out.println(k + " and " + v));
}

Or even cleaner with ForEach

       for (Character c : s.toCharArray()) {
            freqMapSecond.merge(c, 1, Integer::sum);
           }

Rollback transaction after @Test

Aside: attempt to amend Tomasz Nurkiewicz's answer was rejected:

This edit does not make the post even a little bit easier to read, easier to find, more accurate or more accessible. Changes are either completely superfluous or actively harm readability.


Correct and permanent link to the relevant section of documentation about integration testing.

To enable support for transactions, you must configure a PlatformTransactionManager bean in the ApplicationContext that is loaded via @ContextConfiguration semantics.

@Configuration
@PropertySource("application.properties")
public class Persistence {
    @Autowired
    Environment env;

    @Bean
    DataSource dataSource() {
        return new DriverManagerDataSource(
                env.getProperty("datasource.url"),
                env.getProperty("datasource.user"),
                env.getProperty("datasource.password")
        );
    }

    @Bean
    PlatformTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }
}

In addition, you must declare Spring’s @Transactional annotation either at the class or method level for your tests.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {Persistence.class, SomeRepository.class})
@Transactional
public class SomeRepositoryTest { ... }

Annotating a test method with @Transactional causes the test to be run within a transaction that will, by default, be automatically rolled back after completion of the test. If a test class is annotated with @Transactional, each test method within that class hierarchy will be run within a transaction.

How do I find the maximum of 2 numbers?

max(value,run)

should do it.

How to connect to SQL Server from command prompt with Windows authentication

You can use different syntax to achieve different things. If it is windows authentication you want, you could try this:

sqlcmd /S  /d  -E

If you want to use SQL Server authentication you could try this:

sqlcmd /S  /d -U -P 

Definitions:

/S = the servername/instance name. Example: Pete's Laptop/SQLSERV
/d = the database name. Example: Botlek1
-E = Windows authentication.
-U = SQL Server authentication/user. Example: Pete
-P = password that belongs to the user. Example: 1234

Hope this helps!

How to run a specific Android app using Terminal?

I used all the above answers and it was giving me errors so I tried

adb shell monkey -p com.yourpackage.name -c android.intent.category.LAUNCHER 1

and it worked. One advantage is you dont have to specify your launcher activity if you use this command.

Disable button after click in JQuery

*Updated

jQuery version would be something like below:

function load(recieving_id){
    $('#roommate_but').prop('disabled', true);
    $.get('include.inc.php?i=' + recieving_id, function(data) {
        $("#roommate_but").html(data);
    });
}

How to convert entire dataframe to numeric while preserving decimals?

Using dplyr (a bit like sapply..)

df2 <- mutate_all(df1, function(x) as.numeric(as.character(x)))

which gives:

glimpse(df2)
Observations: 4
Variables: 2
$ a <dbl> 0.01, 0.02, 0.03, 0.04
$ b <dbl> 2, 4, 5, 7

from your df1 which was:

glimpse(df1)
Observations: 4
Variables: 2
$ a <fctr> 0.01, 0.02, 0.03, 0.04
$ b <dbl> 2, 4, 5, 7

Why does an onclick property set with setAttribute fail to work in IE?

to make this work in both FF and IE you must write both ways:


    button_element.setAttribute('onclick','doSomething();'); // for FF
    button_element.onclick = function() {doSomething();}; // for IE

thanks to this post.

UPDATE: This is to demonstrate that sometimes it is necessary to use setAttribute! This method works if you need to take the original onclick attribute from the HTML and add it to the onclick event, so that it doesn't get overridden:

// get old onclick attribute
var onclick = button_element.getAttribute("onclick");  

// if onclick is not a function, it's not IE7, so use setAttribute
if(typeof(onclick) != "function") { 
    button_element.setAttribute('onclick','doSomething();' + onclick); // for FF,IE8,Chrome

// if onclick is a function, use the IE7 method and call onclick() in the anonymous function
} else {
    button_element.onclick = function() { 
        doSomething();
        onclick();
    }; // for IE7
}

String to byte array in php

In PHP, strings are bytestreams. What exactly are you trying to do?

Re: edit

Ps. Why do I need this at all!? Well I need to send via fputs() bytearray to server written in java...

fputs takes a string as argument. Most likely, you just need to pass your string to it. On the Java side of things, you should decode the data in whatever encoding, you're using in php (the default is iso-8859-1).

Node.js getaddrinfo ENOTFOUND

I was getting the same error and used below below link to get help:

https://nodejs.org/api/http.html#http_http_request_options_callback

I was not having in my code:

req.end();

(NodeJs V: 5.4.0) once added above req.end(); line, I was able to get rid of the error and worked fine for me.

How to part DATE and TIME from DATETIME in MySQL

per the mysql documentation, the DATE() function will pull the date part of a datetime feild, and TIME() for the time portion. so I would try:

select DATE(dateTimeField) as Date, TIME(dateTimeField) as Time, col2, col3, FROM Table1 ...

How to properly stop the Thread in Java?

Some supplementary info. Both flag and interrupt are suggested in the Java doc.

https://docs.oracle.com/javase/8/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html

private volatile Thread blinker;

public void stop() {
    blinker = null;
}

public void run() {
    Thread thisThread = Thread.currentThread();
    while (blinker == thisThread) {
        try {
            Thread.sleep(interval);
        } catch (InterruptedException e){
        }
        repaint();
    }
}

For a thread that waits for long periods (e.g., for input), use Thread.interrupt

public void stop() {
     Thread moribund = waiter;
      waiter = null;
      moribund.interrupt();
 }

Android SDK Manager Not Installing Components

In my case I was using Windows 7 with the 64-bit OS. We installed the 64-bit Java SE and 64-bit ADT Bundle. With that set up, we couldn't get the SDK manager to work correctly (specifically, no downloads allowed and it didn't show all the API download options). After trying all of the above answers and from other posts, we decided to look into the Java set up and realized it might the 64-bit configuration that's giving the ADT bundle grief (I vaguely recall seeing/reading this issue before).

So we uninstalled Java 64-bit and reinstalled the 32-bit, and then used the 32-bit ADT bundle, and it worked correctly. The system user was already an admin, so we didn't need to "Run as Administrator"

Convert/cast an stdClass object to another class

BTW: Converting is highly important if you are serialized, mainly because the de-serialization breaks the type of objects and turns into stdclass, including DateTime objects.

I updated the example of @Jadrovski, now it allows objects and arrays.

example

$stdobj=new StdClass();
$stdobj->field=20;
$obj=new SomeClass();
fixCast($obj,$stdobj);

example array

$stdobjArr=array(new StdClass(),new StdClass());
$obj=array(); 
$obj[0]=new SomeClass(); // at least the first object should indicates the right class.
fixCast($obj,$stdobj);

code: (its recursive). However, i don't know if its recursive with arrays. May be its missing an extra is_array

public static function fixCast(&$destination,$source)
{
    if (is_array($source)) {
        $getClass=get_class($destination[0]);
        $array=array();
        foreach($source as $sourceItem) {
            $obj = new $getClass();
            fixCast($obj,$sourceItem);
            $array[]=$obj;
        }
        $destination=$array;
    } else {
        $sourceReflection = new \ReflectionObject($source);
        $sourceProperties = $sourceReflection->getProperties();
        foreach ($sourceProperties as $sourceProperty) {
            $name = $sourceProperty->getName();
            if (is_object(@$destination->{$name})) {
                fixCast($destination->{$name}, $source->$name);
            } else {
                $destination->{$name} = $source->$name;
            }
        }
    }
}

Replace CRLF using powershell

The following will be able to process very large files quickly.

$file = New-Object System.IO.StreamReader -Arg "file1.txt"
$outstream = [System.IO.StreamWriter] "file2.txt"
$count = 0 

while ($line = $file.ReadLine()) {
      $count += 1
      $s = $line -replace "`n", "`r`n"
      $outstream.WriteLine($s)
  }

$file.close()
$outstream.close()

Write-Host ([string] $count + ' lines have been processed.')

Are there benefits of passing by pointer over passing by reference in C++?

Clarifications to the preceding posts:


References are NOT a guarantee of getting a non-null pointer. (Though we often treat them as such.)

While horrifically bad code, as in take you out behind the woodshed bad code, the following will compile & run: (At least under my compiler.)

bool test( int & a)
{
  return (&a) == (int *) NULL;
}

int
main()
{
  int * i = (int *)NULL;
  cout << ( test(*i) ) << endl;
};

The real issue I have with references lies with other programmers, henceforth termed IDIOTS, who allocate in the constructor, deallocate in the destructor, and fail to supply a copy constructor or operator=().

Suddenly there's a world of difference between foo(BAR bar) and foo(BAR & bar). (Automatic bitwise copy operation gets invoked. Deallocation in destructor gets invoked twice.)

Thankfully modern compilers will pick up this double-deallocation of the same pointer. 15 years ago, they didn't. (Under gcc/g++, use setenv MALLOC_CHECK_ 0 to revisit the old ways.) Resulting, under DEC UNIX, in the same memory being allocated to two different objects. Lots of debugging fun there...


More practically:

  • References hide that you are changing data stored someplace else.
  • It's easy to confuse a Reference with a Copied object.
  • Pointers make it obvious!

Unable to compile class for JSP: The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files

If you are using maven then you can add the tomcat7-maven-plugin to your pom.xml and it shall run fine. This plugin will run the project on Tomcat servlet container version 7.0.47 which supports JDK 1.8.

    <plugins>
    <plugin>
     <groupId>org.apache.tomcat.maven</groupId>
     <artifactId>tomcat7-maven-plugin</artifactId>
     <version>2.2</version>
     <configuration>
<!-- Include context file for Datasource configuration -->
     <contextFile>./src/main/webapp/META-INF/context.xml</contextFile>
    <port>8080</port>
     </configuration>
     <dependencies>
<!-- Include jdbc driver dependency if using datasource (in my case oracle) -->
    <dependency>
        <groupId>com.oracle</groupId>
        <artifactId>ojdbc6</artifactId>
        <version>11.2.0.4.0</version>
    </dependency>
  </dependencies>
    </plugin>
    </plugins>

Hope this is useful! Thanks

Can a background image be larger than the div itself?

There is a very easy trick. Set padding of that div to a positive number and margin to negativ

#wrapper {
     background: url(xxx.jpeg);
     padding-left: 10px;
     margin-left: -10px;
}

How many parameters are too many?

I think the actual number really depends on what makes logical sense with the context of the function. I agree that around 4-5 parameters starts getting crowded.

In the case of setting flags, a great way to handle this situation is to enumerate the values and OR them together.

How to check if a string contains only digits in Java

According to Oracle's Java Documentation:

private static final Pattern NUMBER_PATTERN = Pattern.compile(
        "[\\x00-\\x20]*[+-]?(NaN|Infinity|((((\\p{Digit}+)(\\.)?((\\p{Digit}+)?)" +
        "([eE][+-]?(\\p{Digit}+))?)|(\\.((\\p{Digit}+))([eE][+-]?(\\p{Digit}+))?)|" +
        "(((0[xX](\\p{XDigit}+)(\\.)?)|(0[xX](\\p{XDigit}+)?(\\.)(\\p{XDigit}+)))" +
        "[pP][+-]?(\\p{Digit}+)))[fFdD]?))[\\x00-\\x20]*");
boolean isNumber(String s){
return NUMBER_PATTERN.matcher(s).matches()
}

How to create tar.gz archive file in Windows?

tar.gz file is just a tar file that's been gzipped. Both tar and gzip are available for windows.

If you like GUIs (Graphical user interface), 7zip can pack with both tar and gzip.

How to get Domain name from URL using jquery..?

To get the url as well as the protocol used we can try the code below.

For example to get the domain as well as the protocol used (http/https).

https://google.com

You can use -

host = window.location.protocol+'//'+window.location.hostname+'/';

It'll return you the protocol as well as domain name. https://google.com/

Python, compute list difference

When having a look at TimeComplexity of In-operator, in worst case it works with O(n). Even for Sets.

So when comparing two arrays we'll have a TimeComplexity of O(n) in best case and O(n^2) in worst case.

An alternative (but unfortunately more complex) solution, which works with O(n) in best and worst case is this one:

# Compares the difference of list a and b
# uses a callback function to compare items
def diff(a, b, callback):
  a_missing_in_b = []
  ai = 0
  bi = 0

  a = sorted(a, callback)
  b = sorted(b, callback)

  while (ai < len(a)) and (bi < len(b)):

    cmp = callback(a[ai], b[bi])
    if cmp < 0:
      a_missing_in_b.append(a[ai])
      ai += 1
    elif cmp > 0:
      # Item b is missing in a
      bi += 1
    else:
      # a and b intersecting on this item
      ai += 1
      bi += 1

  # if a and b are not of same length, we need to add the remaining items
  for ai in xrange(ai, len(a)):
    a_missing_in_b.append(a[ai])


  return a_missing_in_b

e.g.

>>> a=[1,2,3]
>>> b=[2,4,6]
>>> diff(a, b, cmp)
[1, 3]

using awk with column value conditions

If you're looking for a particular string, put quotes around it:

awk '$1 == "findtext" {print $3}'

Otherwise, awk will assume it's a variable name.

nodejs mysql Error: Connection lost The server closed the connection

I do not recall my original use case for this mechanism. Nowadays, I cannot think of any valid use case.

Your client should be able to detect when the connection is lost and allow you to re-create the connection. If it important that part of program logic is executed using the same connection, then use transactions.

tl;dr; Do not use this method.


A pragmatic solution is to force MySQL to keep the connection alive:

setInterval(function () {
    db.query('SELECT 1');
}, 5000);

I prefer this solution to connection pool and handling disconnect because it does not require to structure your code in a way thats aware of connection presence. Making a query every 5 seconds ensures that the connection will remain alive and PROTOCOL_CONNECTION_LOST does not occur.

Furthermore, this method ensures that you are keeping the same connection alive, as opposed to re-connecting. This is important. Consider what would happen if your script relied on LAST_INSERT_ID() and mysql connection have been reset without you being aware about it?

However, this only ensures that connection time out (wait_timeout and interactive_timeout) does not occur. It will fail, as expected, in all others scenarios. Therefore, make sure to handle other errors.

EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType

The problem is that your ApplicationUser inherits from IdentityUser, which is defined like this:

IdentityUser : IdentityUser<string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>, IUser
....
public virtual ICollection<TRole> Roles { get; private set; }
public virtual ICollection<TClaim> Claims { get; private set; }
public virtual ICollection<TLogin> Logins { get; private set; }

and their primary keys are mapped in the method OnModelCreating of the class IdentityDbContext:

modelBuilder.Entity<TUserRole>()
            .HasKey(r => new {r.UserId, r.RoleId})
            .ToTable("AspNetUserRoles");

modelBuilder.Entity<TUserLogin>()
            .HasKey(l => new {l.LoginProvider, l.ProviderKey, l.UserId})
            .ToTable("AspNetUserLogins");

and as your DXContext doesn't derive from it, those keys don't get defined.

If you dig into the sources of Microsoft.AspNet.Identity.EntityFramework, you will understand everything.

I came across this situation some time ago, and I found three possible solutions (maybe there are more):

  1. Use separate DbContexts against two different databases or the same database but different tables.
  2. Merge your DXContext with ApplicationDbContext and use one database.
  3. Use separate DbContexts against the same table and manage their migrations accordingly.

Option 1: See update the bottom.

Option 2: You will end up with a DbContext like this one:

public class DXContext : IdentityDbContext<User, Role,
    int, UserLogin, UserRole, UserClaim>//: DbContext
{
    public DXContext()
        : base("name=DXContext")
    {
        Database.SetInitializer<DXContext>(null);// Remove default initializer
        Configuration.ProxyCreationEnabled = false;
        Configuration.LazyLoadingEnabled = false;
    }

    public static DXContext Create()
    {
        return new DXContext();
    }

    //Identity and Authorization
    public DbSet<UserLogin> UserLogins { get; set; }
    public DbSet<UserClaim> UserClaims { get; set; }
    public DbSet<UserRole> UserRoles { get; set; }
    
    // ... your custom DbSets
    public DbSet<RoleOperation> RoleOperations { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();

        // Configure Asp Net Identity Tables
        modelBuilder.Entity<User>().ToTable("User");
        modelBuilder.Entity<User>().Property(u => u.PasswordHash).HasMaxLength(500);
        modelBuilder.Entity<User>().Property(u => u.Stamp).HasMaxLength(500);
        modelBuilder.Entity<User>().Property(u => u.PhoneNumber).HasMaxLength(50);

        modelBuilder.Entity<Role>().ToTable("Role");
        modelBuilder.Entity<UserRole>().ToTable("UserRole");
        modelBuilder.Entity<UserLogin>().ToTable("UserLogin");
        modelBuilder.Entity<UserClaim>().ToTable("UserClaim");
        modelBuilder.Entity<UserClaim>().Property(u => u.ClaimType).HasMaxLength(150);
        modelBuilder.Entity<UserClaim>().Property(u => u.ClaimValue).HasMaxLength(500);
    }
}

Option 3: You will have one DbContext equal to the option 2. Let's name it IdentityContext. And you will have another DbContext called DXContext:

public class DXContext : DbContext
{        
    public DXContext()
        : base("name=DXContext") // connection string in the application configuration file.
    {
        Database.SetInitializer<DXContext>(null); // Remove default initializer
        Configuration.LazyLoadingEnabled = false;
        Configuration.ProxyCreationEnabled = false;
    }

    // Domain Model
    public DbSet<User> Users { get; set; }
    // ... other custom DbSets
    
    public static DXContext Create()
    {
        return new DXContext();
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

        // IMPORTANT: we are mapping the entity User to the same table as the entity ApplicationUser
        modelBuilder.Entity<User>().ToTable("User"); 
    }

    public DbQuery<T> Query<T>() where T : class
    {
        return Set<T>().AsNoTracking();
    }
}

where User is:

public class User
{
    public int Id { get; set; }

    [Required, StringLength(100)]
    public string Name { get; set; }

    [Required, StringLength(128)]
    public string SomeOtherColumn { get; set; }
}

With this solution, I'm mapping the entity User to the same table as the entity ApplicationUser.

Then, using Code First Migrations you'll need to generate the migrations for the IdentityContext and THEN for the DXContext, following this great post from Shailendra Chauhan: Code First Migrations with Multiple Data Contexts

You'll have to modify the migration generated for DXContext. Something like this depending on which properties are shared between ApplicationUser and User:

        //CreateTable(
        //    "dbo.User",
        //    c => new
        //        {
        //            Id = c.Int(nullable: false, identity: true),
        //            Name = c.String(nullable: false, maxLength: 100),
        //            SomeOtherColumn = c.String(nullable: false, maxLength: 128),
        //        })
        //    .PrimaryKey(t => t.Id);
        AddColumn("dbo.User", "SomeOtherColumn", c => c.String(nullable: false, maxLength: 128));

and then running the migrations in order (first the Identity migrations) from the global.asax or any other place of your application using this custom class:

public static class DXDatabaseMigrator
{
    public static string ExecuteMigrations()
    {
        return string.Format("Identity migrations: {0}. DX migrations: {1}.", ExecuteIdentityMigrations(),
            ExecuteDXMigrations());
    }

    private static string ExecuteIdentityMigrations()
    {
        IdentityMigrationConfiguration configuration = new IdentityMigrationConfiguration();
        return RunMigrations(configuration);
    }

    private static string ExecuteDXMigrations()
    {
        DXMigrationConfiguration configuration = new DXMigrationConfiguration();
        return RunMigrations(configuration);
    }

    private static string RunMigrations(DbMigrationsConfiguration configuration)
    {
        List<string> pendingMigrations;
        try
        {
            DbMigrator migrator = new DbMigrator(configuration);
            pendingMigrations = migrator.GetPendingMigrations().ToList(); // Just to be able to log which migrations were executed

            if (pendingMigrations.Any())                
                    migrator.Update();     
        }
        catch (Exception e)
        {
            ExceptionManager.LogException(e);
            return e.Message;
        }
        return !pendingMigrations.Any() ? "None" : string.Join(", ", pendingMigrations);
    }
}

This way, my n-tier cross-cutting entities don't end up inheriting from AspNetIdentity classes, and therefore I don't have to import this framework in every project where I use them.

Sorry for the extensive post. I hope it could offer some guidance on this. I have already used options 2 and 3 in production environments.

UPDATE: Expand Option 1

For the last two projects I have used the 1st option: having an AspNetUser class that derives from IdentityUser, and a separate custom class called AppUser. In my case, the DbContexts are IdentityContext and DomainContext respectively. And I defined the Id of the AppUser like this:

public class AppUser : TrackableEntity
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    // This Id is equal to the Id in the AspNetUser table and it's manually set.
    public override int Id { get; set; }

(TrackableEntity is the custom abstract base class that I use in the overridden SaveChanges method of my DomainContext context)

I first create the AspNetUser and then the AppUser. The drawback with this approach is that you have ensured that your "CreateUser" functionality is transactional (remember that there will be two DbContexts calling SaveChanges separately). Using TransactionScope didn't work for me for some reason, so I ended up doing something ugly but that works for me:

        IdentityResult identityResult = UserManager.Create(aspNetUser, model.Password);

        if (!identityResult.Succeeded)
            throw new TechnicalException("User creation didn't succeed", new LogObjectException(result));

        AppUser appUser;
        try
        {
            appUser = RegisterInAppUserTable(model, aspNetUser);
        }
        catch (Exception)
        {
            // Roll back
            UserManager.Delete(aspNetUser);
            throw;
        }

(Please, if somebody comes with a better way of doing this part I appreciate commenting or proposing an edit to this answer)

The benefits are that you don't have to modify the migrations and you can use any crazy inheritance hierarchy over the AppUser without messing with the AspNetUser. And actually, I use Automatic Migrations for my IdentityContext (the context that derives from IdentityDbContext):

public sealed class IdentityMigrationConfiguration : DbMigrationsConfiguration<IdentityContext>
{
    public IdentityMigrationConfiguration()
    {
        AutomaticMigrationsEnabled = true;
        AutomaticMigrationDataLossAllowed = false;
    }

    protected override void Seed(IdentityContext context)
    {
    }
}

This approach also has the benefit of avoiding to have your n-tier cross-cutting entities inheriting from AspNetIdentity classes.

How to find Google's IP address?

Here is a bash script that returns the IP (v4 and v6) ranges using @WorkWise's answer:

domainsToDig=$(dig @8.8.8.8 _spf.google.com TXT +short | \
    sed \
        -e 's/"v=spf1//' \
        -e 's/ ~all"//' \
        -e 's/ include:/\n/g' | \
    tail -n+2)
for domain in $domainsToDig ; do
    dig @8.8.8.8 $domain TXT +short | \
        sed \
            -e 's/"v=spf1//' \
            -e 's/ ~all"//' \
            -e 's/ ip.:/\n/g' | \
        tail -n+2
done

Cannot read property 'push' of undefined when combining arrays

Generally, Push method is used to add elements at the end of an array.

Here, you have used the push method to an object and not an array which is 'order'.

Steps to debug...

Change the object into an empty array,

var order = [], stack = [];

Now you can use the push method for this array as usual.

To use push method to this 'order' array; you should not use the array index when calling push method to an array. Just use the name of the array only.

var order = [], stack = [];

for(var i = 0; i<a.length; i++){

   if(parseInt(a[i].daysleft) == 0){ 
     order.push(a[i]); 
   }

   if(parseInt(a[i].daysleft) > 0){ 
     order.push(a[i]); 
   }

   if(parseInt(a[i].daysleft) < 0){ 
     order.push(a[i]); 
   }
}

How to get option text value using AngularJS?

<div ng-controller="ExampleController">
  <form name="myForm">
    <label for="repeatSelect"> Repeat select: </label>
    <select name="repeatSelect" id="repeatSelect" ng-model="data.model">
      <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
    </select>
  </form>
  <hr>
  <tt>model = {{data.model}}</tt><br/>
</div>

AngularJS:

angular.module('ngrepeatSelect', [])
 .controller('ExampleController', ['$scope', function($scope) {
   $scope.data = {
    model: null,
    availableOptions: [
      {id: '1', name: 'Option A'},
      {id: '2', name: 'Option B'},
      {id: '3', name: 'Option C'}
    ]
   };
}]);

taken from AngularJS docs

ALTER TABLE to add a composite primary key

alter table table_name add primary key (col_name1, col_name2);

Git: Pull from other remote

git pull is really just a shorthand for git pull <remote> <branchname>, in most cases it's equivalent to git pull origin master. You will need to add another remote and pull explicitly from it. This page describes it in detail:

http://help.github.com/forking/

Is JavaScript a pass-by-reference or pass-by-value language?

Observation: If there isn't any way for an observer to examine the underlying memory of the engine, there is no way to determine whether an immutable value gets copied or a reference gets passed.

JavaScript is more or less agnostic to the underlying memory model. There is no such thing as a reference². JavaScript has values. Two variables can hold the same value (or more accurate: two environment records can bind the same value). The only type of values that can be mutated are objects through their abstract [[Get]] and [[Set]] operations. If you forget about computers and memory, this is all you need to describe JavaScript's behaviour, and it allows you to understand the specification.

 let a = { prop: 1 };
 let b = a; // a and b hold the same value
 a.prop = "test"; // The object gets mutated, can be observed through both a and b
 b = { prop: 2 }; // b holds now a different value

Now you might ask yourself how two variables can hold the same value on a computer. You might then look into the source code of a JavaScript engine and you'll most likely find something which a programmer of the language the engine was written in would call a reference.

So in fact you can say that JavaScript is "pass by value", whereas the value can be shared, and you can say that JavaScript is "pass by reference", which might be a useful logical abstraction for programmers from low level languages, or you might call the behaviour "call by sharing".

As there is no such thing as a reference in JavaScript, all of these are neither wrong nor on point. Therefore I don't think the answer is particularly useful to search for.

² The term Reference in the specification is not a reference in the traditional sense. It is a container for an object and the name of a property, and it is an intermediate value (e.g., a.b evaluates to Reference { value = a, name = "b" }). The term reference also sometimes appears in the specification in unrelated sections.

How to make a vertical SeekBar in Android?

Wrap it inside a FrameLayout so that there is no Size issue.

  <FrameLayout
                android:layout_width="@dimen/_20dp"
                android:layout_marginStart="@dimen/_15dp"
                android:layout_marginEnd="@dimen/_15dp"
                android:layout_height="match_parent"
                android:orientation="vertical">

                <SeekBar
                    android:layout_width="150dp"
                    android:layout_height="30dp"
                    android:layout_gravity="center"
                    android:rotation="270" />
  </FrameLayout>

Get names of all files from a folder with Ruby

In an IRB context, you can use the following to get the files in the current directory:

file_names = `ls`.split("\n")

You can make this work on other directories too:

file_names = `ls ~/Documents`.split("\n")

How do I activate C++ 11 in CMake?

I am using

include(CheckCXXCompilerFlag)
CHECK_CXX_COMPILER_FLAG("-std=c++11" COMPILER_SUPPORTS_CXX11)
CHECK_CXX_COMPILER_FLAG("-std=c++0x" COMPILER_SUPPORTS_CXX0X)
if(COMPILER_SUPPORTS_CXX11)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
elseif(COMPILER_SUPPORTS_CXX0X)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")
else()
        message(STATUS "The compiler ${CMAKE_CXX_COMPILER} has no C++11 support. Please use a different C++ compiler.")
endif()

But if you want to play with C++11, g++ 4.6.1 is pretty old. Try to get a newer g++ version.

How to add many functions in ONE ng-click?

The standard way to add Multiple functions

<button (click)="removeAt(element.bookId); openDeleteDialog()"> Click Here</button>

or

<button (click)="removeAt(element.bookId)" (click)="openDeleteDialog()"> Click Here</button>

Split string with PowerShell and do something with each token

"Once upon a time there were three little pigs".Split(" ") | ForEach {
    "$_ is a token"
 }

The key is $_, which stands for the current variable in the pipeline.

About the code you found online:

% is an alias for ForEach-Object. Anything enclosed inside the brackets is run once for each object it receives. In this case, it's only running once, because you're sending it a single string.

$_.Split(" ") is taking the current variable and splitting it on spaces. The current variable will be whatever is currently being looped over by ForEach.

How to export all data from table to an insertable sql format?

Another way to dump data as file from table by DumpDataFromTable sproc

EXEC dbo.DumpDataFromTable
     @SchemaName = 'dbo'
    ,@TableName = 'YourTableName'
    ,@PathOut = N'c:\tmp\scripts\' -- folder must exist !!!'

Note: SQL must have permission to create files, if is not set-up then exec follow line once

EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE WITH OVERRIDE;

By this script you can call the sproc: DumpDataFromTable.sql and dump more tables in one go, instead of doing manually one by one from Management Studio

By default the format of generated scrip will be like

INSERT INTO <TableName> SELECT <Values>

Or you can change the generated format into

SELECT ... FROM

by setting variable @BuildMethod = 2

full sproc code:

IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DumpDataFromTable]') AND type in (N'P', N'PC'))
    DROP PROCEDURE dbo.[DumpDataFromTable]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:    Oleg Ciobanu
-- Create date: 20171214
-- Version 1.02
-- Description:
-- dump data in 2 formats
-- @BuildMethod = 1 INSERT INTO format
-- @BuildMethod = 2 SELECT * FROM format
--
-- SQL must have permission to create files, if is not set-up then exec follow line once
-- EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE WITH OVERRIDE;
--
-- =============================================
CREATE PROCEDURE [dbo].[DumpDataFromTable]
(
     @SchemaName nvarchar(128) --= 'dbo'
    ,@TableName nvarchar(128) --= 'testTable'
    ,@WhereClause nvarchar (1000) = '' -- must start with AND
    ,@BuildMethod int = 1 -- taking values 1 for INSERT INTO forrmat or 2 for SELECT from value Table
    ,@PathOut nvarchar(250) = N'c:\tmp\scripts\' -- folder must exist !!!'
    ,@AsFileNAme nvarchar(250) = NULL -- if is passed then will use this value as FileName
    ,@DebugMode int = 0
)
AS
BEGIN  
    SET NOCOUNT ON;

        -- run follow next line if you get permission deny  for sp_OACreate,sp_OAMethod
        -- EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE WITH OVERRIDE;

    DECLARE @Sql nvarchar (max)
    DECLARE @SqlInsert nvarchar (max) = ''
    DECLARE @Columns nvarchar(max)
    DECLARE @ColumnsCast nvarchar(max)

    -- cleanUp/prepraring data
    SET @SchemaName = REPLACE(REPLACE(@SchemaName,'[',''),']','')
    SET @TableName = REPLACE(REPLACE(@TableName,'[',''),']','')
    SET @AsFileNAme = NULLIF(@AsFileNAme,'')
    SET @AsFileNAme = REPLACE(@AsFileNAme,'.','_')
    SET @AsFileNAme = COALESCE(@PathOut + @AsFileNAme + '.sql', @PathOut + @SchemaName + ISNULL('_' + @TableName,N'') + '.sql')


    --debug
    IF @DebugMode = 1
        PRINT @AsFileNAme

        -- Create temp SP what will be responsable for generating script files
    DECLARE @PRC_WritereadFile VARCHAR(max) =
        'IF EXISTS (SELECT * FROM sys.objects WHERE type = ''P'' AND name = ''PRC_WritereadFile'')
       BEGIN
          DROP  Procedure  PRC_WritereadFile
       END;'
    EXEC  (@PRC_WritereadFile)
       -- '  
    SET @PRC_WritereadFile =
    'CREATE Procedure PRC_WritereadFile (
        @FileMode INT -- Recreate = 0 or Append Mode 1
       ,@Path NVARCHAR(1000)
       ,@AsFileNAme NVARCHAR(500)
       ,@FileBody NVARCHAR(MAX)   
       )
    AS
        DECLARE @OLEResult INT
        DECLARE @FS INT
        DECLARE @FileID INT
        DECLARE @hr INT
        DECLARE @FullFileName NVARCHAR(1500) = @Path + @AsFileNAme

        -- Create Object
        EXECUTE @OLEResult = sp_OACreate ''Scripting.FileSystemObject'', @FS OUTPUT
        IF @OLEResult <> 0 BEGIN
            PRINT ''Scripting.FileSystemObject''
            GOTO Error_Handler
        END    

        IF @FileMode = 0 BEGIN  -- Create
            EXECUTE @OLEResult = sp_OAMethod @FS,''CreateTextFile'',@FileID OUTPUT, @FullFileName
            IF @OLEResult <> 0 BEGIN
                PRINT ''CreateTextFile''
                GOTO Error_Handler
            END
        END ELSE BEGIN          -- Append
            EXECUTE @OLEResult = sp_OAMethod @FS,''OpenTextFile'',@FileID OUTPUT, @FullFileName, 8, 0 -- 8- forappending
            IF @OLEResult <> 0 BEGIN
                PRINT ''OpenTextFile''
                GOTO Error_Handler
            END            
        END

        EXECUTE @OLEResult = sp_OAMethod @FileID, ''WriteLine'', NULL, @FileBody
        IF @OLEResult <> 0 BEGIN
            PRINT ''WriteLine''
            GOTO Error_Handler
        END     

        EXECUTE @OLEResult = sp_OAMethod @FileID,''Close''
        IF @OLEResult <> 0 BEGIN
            PRINT ''Close''
            GOTO Error_Handler
        END

        EXECUTE sp_OADestroy @FS
        EXECUTE sp_OADestroy @FileID

        GOTO Done

        Error_Handler:
            DECLARE @source varchar(30), @desc varchar (200)       
            EXEC @hr = sp_OAGetErrorInfo null, @source OUT, @desc OUT
            PRINT ''*** ERROR ***''
            SELECT OLEResult = @OLEResult, hr = CONVERT (binary(4), @hr), source = @source, description = @desc

       Done:
    ';
        -- '
    EXEC  (@PRC_WritereadFile) 
    EXEC PRC_WritereadFile 0 /*Create*/, '', @AsFileNAme, ''


    ;WITH steColumns AS (
        SELECT
            1 as rn,
            c.ORDINAL_POSITION
            ,c.COLUMN_NAME as ColumnName
            ,c.DATA_TYPE as ColumnType
        FROM INFORMATION_SCHEMA.COLUMNS c
        WHERE 1 = 1
        AND c.TABLE_SCHEMA = @SchemaName
        AND c.TABLE_NAME = @TableName
    )

    --SELECT *

       SELECT
            @ColumnsCast = ( SELECT
                                    CASE WHEN ColumnType IN ('date','time','datetime2','datetimeoffset','smalldatetime','datetime','timestamp')
                                        THEN
                                            'convert(nvarchar(1001), s.[' + ColumnName + ']' + ' , 121) AS [' + ColumnName + '],'
                                            --,convert(nvarchar, [DateTimeScriptApplied], 121) as [DateTimeScriptApplied]
                                        ELSE
                                            'CAST(s.[' + ColumnName + ']' + ' AS NVARCHAR(1001)) AS [' + ColumnName + '],'
                                    END
                                     as 'data()'                                  
                                    FROM
                                      steColumns t2
                                    WHERE 1 =1
                                      AND t1.rn = t2.rn
                                    FOR xml PATH('')
                                   )
            ,@Columns = ( SELECT
                                    '[' + ColumnName + '],' as 'data()'                                  
                                    FROM
                                      steColumns t2
                                    WHERE 1 =1
                                      AND t1.rn = t2.rn
                                    FOR xml PATH('')
                                   )

    FROM steColumns t1

    -- remove last char
    IF lEN(@Columns) > 0 BEGIN
        SET @Columns = SUBSTRING(@Columns, 1, LEN(@Columns)-1);
        SET @ColumnsCast = SUBSTRING(@ColumnsCast, 1, LEN(@ColumnsCast)-1);
    END

    -- debug
    IF @DebugMode = 1 BEGIN
        print @ColumnsCast
        print @Columns
        select @ColumnsCast ,  @Columns
    END

    -- build unpivoted Data
    SET @SQL = '
    SELECT
        u.rn
        , c.ORDINAL_POSITION as ColumnPosition
        , c.DATA_TYPE as ColumnType
        , u.ColumnName
        , u.ColumnValue
    FROM
    (SELECT
        ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS rn,
    '
    + CHAR(13) + @ColumnsCast
    + CHAR(13) + 'FROM [' + @SchemaName + '].[' + @TableName + '] s'
    + CHAR(13) + 'WHERE 1 = 1'
    + CHAR(13) + COALESCE(@WhereClause,'')
    + CHAR(13) + ') tt
    UNPIVOT
    (
      ColumnValue
      FOR ColumnName in (
    ' + CHAR(13) + @Columns
    + CHAR(13)
    + '
     )
    ) u

    LEFT JOIN INFORMATION_SCHEMA.COLUMNS c ON c.COLUMN_NAME = u.ColumnName
        AND c.TABLE_SCHEMA = '''+ @SchemaName + '''
        AND c.TABLE_NAME = ''' + @TableName +'''
    ORDER BY u.rn
            , c.ORDINAL_POSITION
    '

    -- debug
    IF @DebugMode = 1 BEGIN
        print @Sql     
        exec (@Sql)
    END

    -- prepare data for cursor

    IF OBJECT_ID('tempdb..#tmp') IS NOT NULL
        DROP TABLE #tmp
    CREATE TABLE #tmp
    (
        rn bigint
        ,ColumnPosition int
        ,ColumnType varchar (128)
        ,ColumnName varchar (128)
        ,ColumnValue nvarchar (2000) -- I hope this size will be enough for storring values
    )
    SET @Sql = 'INSERT INTO  #tmp ' + CHAR(13)  + @Sql

    -- debug
    IF @DebugMode = 1 BEGIN
        print @Sql
    END

    EXEC (@Sql)

 -- Insert dummy rec, otherwise will not proceed the last rec :)
INSERT INTO #tmp (rn)
SELECT MAX(rn) +  1 
FROM #tmp   

    IF @DebugMode = 1 BEGIN
        SELECT * FROM #tmp
    END

    DECLARE @rn bigint
        ,@ColumnPosition int
        ,@ColumnType varchar (128)
        ,@ColumnName varchar (128)
        ,@ColumnValue nvarchar (2000)
        ,@i int = -1 -- counter/flag
        ,@ColumnsInsert varchar(max) = NULL
        ,@ValuesInsert nvarchar(max) = NULL

    DECLARE cur CURSOR FOR
    SELECT rn, ColumnPosition, ColumnType, ColumnName, ColumnValue
    FROM #tmp
    ORDER BY rn, ColumnPosition -- note order is really important !!!
    OPEN cur

    FETCH NEXT FROM cur
    INTO @rn, @ColumnPosition, @ColumnType, @ColumnName, @ColumnValue

    IF @BuildMethod = 1
    BEGIN
        SET @SqlInsert = 'SET NOCOUNT ON;' + CHAR(13);
        EXEC PRC_WritereadFile 1 /*Add*/, '', @AsFileName, @SqlInsert
        SET @SqlInsert = ''
    END
    ELSE BEGIN
        SET @SqlInsert = 'SET NOCOUNT ON;' + CHAR(13);
        SET @SqlInsert = @SqlInsert
                        + 'SELECT *'
                        + CHAR(13) + 'FROM ('
                        + CHAR(13) + 'VALUES'
        EXEC PRC_WritereadFile 1 /*Add*/, '', @AsFileName, @SqlInsert
        SET @SqlInsert = NULL
    END

    SET @i = @rn

    WHILE @@FETCH_STATUS = 0
    BEGIN

        IF (@i <> @rn) -- is a new row
        BEGIN
            IF @BuildMethod = 1
            -- build as INSERT INTO -- as Default
            BEGIN
                SET @SqlInsert = 'INSERT INTO [' + @SchemaName + '].[' + @TableName + '] ('
                                + CHAR(13) + @ColumnsInsert + ')'
                                + CHAR(13) + 'VALUES ('
                                + @ValuesInsert
                                + CHAR(13) + ');'
            END
            ELSE
            BEGIN
                -- build as Table select
                IF (@i <> @rn) -- is a new row
                BEGIN
                    SET @SqlInsert = COALESCE(@SqlInsert + ',','') +  '(' + @ValuesInsert+ ')'
                    EXEC PRC_WritereadFile 1 /*Add*/, '', @AsFileNAme, @SqlInsert
                    SET @SqlInsert = '' -- in method 2 we should clear script
                END            
            END
            -- debug
            IF @DebugMode = 1
                print @SqlInsert
            EXEC PRC_WritereadFile 1 /*Add*/, '', @AsFileNAme, @SqlInsert

            -- we have new row
            -- initialise variables
            SET @i = @rn
            SET @ColumnsInsert = NULL
            SET @ValuesInsert = NULL
        END

        -- build insert values
        IF (@i = @rn) -- is same row
        BEGIN
            SET @ColumnsInsert = COALESCE(@ColumnsInsert + ',','') + '[' + @ColumnName + ']'
            SET @ValuesInsert =  CASE                              
                                    -- date
                                    --WHEN
                                    --  @ColumnType IN ('date','time','datetime2','datetimeoffset','smalldatetime','datetime','timestamp')
                                    --THEN
                                    --  COALESCE(@ValuesInsert + ',','') + '''''' + ISNULL(RTRIM(@ColumnValue),'NULL') + ''''''
                                    -- numeric
                                    WHEN
                                        @ColumnType IN ('bit','tinyint','smallint','int','bigint'
                                                        ,'money','real','','float','decimal','numeric','smallmoney')
                                    THEN
                                        COALESCE(@ValuesInsert + ',','') + '' + ISNULL(RTRIM(@ColumnValue),'NULL') + ''
                                    -- other types treat as string
                                    ELSE
                                        COALESCE(@ValuesInsert + ',','') + '''' + ISNULL(RTRIM( 
                                                                                            -- escape single quote
                                                                                            REPLACE(@ColumnValue, '''', '''''') 
                                                                                              ),'NULL') + ''''         
                                END
        END


        FETCH NEXT FROM cur
        INTO @rn, @ColumnPosition, @ColumnType, @ColumnName, @ColumnValue

        -- debug
        IF @DebugMode = 1
        BEGIN
            print CAST(@rn AS VARCHAR) + '-' + CAST(@ColumnPosition AS VARCHAR)
        END
    END
    CLOSE cur
    DEALLOCATE cur

    IF @BuildMethod = 1
    BEGIN
        PRINT 'ignore'
    END
    ELSE BEGIN
        SET @SqlInsert = CHAR(13) + ') AS vtable '
                        + CHAR(13) + ' (' + @Columns
                        + CHAR(13) + ')'
        EXEC PRC_WritereadFile 1 /*Add*/, '', @AsFileNAme, @SqlInsert
        SET @SqlInsert = NULL
    END
    PRINT 'Done: ' + @AsFileNAme
END

Or can be downloaded latest version from https://github.com/Zindur/MSSQL-DumpTable/tree/master/Scripts

Command line input in Python

Just Taking Input

the_input = raw_input("Enter input: ")

And that's it.

Moreover, if you want to make a list of inputs, you can do something like:

a = []

for x in xrange(1,10):
    a.append(raw_input("Enter Data: "))

In that case, you'll be asked for data 10 times to store 9 items in a list.

Output:

Enter data: 2
Enter data: 3
Enter data: 4
Enter data: 5
Enter data: 7
Enter data: 3
Enter data: 8
Enter data: 22
Enter data: 5
>>> a
['2', '3', '4', '5', '7', '3', '8', '22', '5']

You can search that list the fundamental way with something like (after making that list):

if '2' in a:
    print "Found"

else: print "Not found."

You can replace '2' with "raw_input()" like this:

if raw_input("Search for: ") in a:
    print "Found"
else: 
    print "Not found"

Taking Raw Data From Input File via Commandline Interface

If you want to take the input from a file you feed through commandline (which is normally what you need when doing code problems for competitions, like Google Code Jam or the ACM/IBM ICPC):

example.py

while(True):
    line = raw_input()
    print "input data: %s" % line

In command line interface:

example.py < input.txt

Hope that helps.

How to format JSON in notepad++

The answer was to install the plugin individually. I installed all the three plugins shown in the screenshot together. And it created the issue. I had to install each plugin individually and then it worked fine. I am able to format the JSON string.

How to setup FTP on xampp

XAMPP comes preloaded with the FileZilla FTP server. Here is how to setup the service, and create an account.

  1. Enable the FileZilla FTP Service through the XAMPP Control Panel to make it startup automatically (check the checkbox next to filezilla to install the service). Then manually start the service.

  2. Create an ftp account through the FileZilla Server Interface (its the essentially the filezilla control panel). There is a link to it Start Menu in XAMPP folder. Then go to Users->Add User->Stuff->Done.

  3. Try connecting to the server (localhost, port 21).

How to remove rows with any zero value

Well, you could swap your 0's for NA and then use one of those solutions, but for sake of a difference, you could notice that a number will only have a finite logarithm if it is greater than 0, so that rowSums of the log will only be finite if there are no zeros in a row.

dfr[is.finite(rowSums(log(dfr[-1]))),]

Correct way to add external jars (lib/*.jar) to an IntelliJ IDEA project

Libraries cannot be directly used in any program if not properly added to the project gradle files.

This can easily be done in smart IDEs like inteli J.

1) First as a convention add a folder names 'libs' under your project src file. (this can easily be done using the IDE itself)

2) then copy or add your library file (eg: .jar file) to the folder named 'libs'

3) now you can see the library file inside the libs folder. Now right click on the file and select 'add as library'. And this will fix all the relevant files in your program and library will be directly available for your use.

Please note:

Whenever you are adding libraries to a project, make sure that the project supports the library

How to fit a smooth curve to my data in R?

In ggplot2 you can do smooths in a number of ways, for example:

library(ggplot2)
ggplot(mtcars, aes(wt, mpg)) + geom_point() +
  geom_smooth(method = "gam", formula = y ~ poly(x, 2)) 
ggplot(mtcars, aes(wt, mpg)) + geom_point() +
  geom_smooth(method = "loess", span = 0.3, se = FALSE) 

enter image description here enter image description here

How to use IntelliJ IDEA to find all unused code?

Just use Analyze | Inspect Code with appropriate inspection enabled (Unused declaration under Declaration redundancy group).

Using IntelliJ 11 CE you can now "Analyze | Run Inspection by Name ... | Unused declaration"

Google Maps API Multiple Markers with Infowindows

function setMarkers(map,locations){

for (var i = 0; i < locations.length; i++)
 {  

 var loan = locations[i][0];
 var lat = locations[i][1];
 var long = locations[i][2];
 var add =  locations[i][3];

 latlngset = new google.maps.LatLng(lat, long);

 var marker = new google.maps.Marker({  
          map: map, title: loan , position: latlngset  
 });
 map.setCenter(marker.getPosition());


 marker.content = "<h3>Loan Number: " + loan +  '</h3>' + "Address: " + add;


 google.maps.events.addListener(marker,'click', function(map,marker){
          map.infowindow.setContent(marker.content);
          map.infowindow.open(map,marker);

 });

 }
}

Then move var infowindow = new google.maps.InfoWindow() to the initialize() function:

function initialize() {

    var myOptions = {
      center: new google.maps.LatLng(33.890542, 151.274856),
      zoom: 8,
      mapTypeId: google.maps.MapTypeId.ROADMAP

    };
    var map = new google.maps.Map(document.getElementById("default"),
        myOptions);
    map.infowindow = new google.maps.InfoWindow();

    setMarkers(map,locations)

  }

How to check if a string contains a substring in Bash

If you prefer the regex approach:

string='My string';

if [[ $string =~ "My" ]]; then
   echo "It's there!"
fi

How do you create a hidden div that doesn't create a line break or horizontal space?

Consider using <span> to isolate small segments of markup to be styled without breaking up layout. This would seem to be more idiomatic than trying to force a <div> not to display itself--if in fact the checkbox itself cannot be styled in the way you want.

Order of items in classes: Fields, Properties, Constructors, Methods

Usually I try to follow the next pattern:

  • static members (have usually an other context, must be thread-safe, etc.)
  • instance members

Each part (static and instance) consists of the following member types:

  • operators (are always static)
  • fields (initialized before constructors)
  • constructors
  • destructor (is a tradition to follow the constructors)
  • properties
  • methods
  • events

Then the members are sorted by visibility (from less to more visible):

  • private
  • internal
  • internal protected
  • protected
  • public

The order is not a dogma: simple classes are easier to read, however, more complex classes need context-specific grouping.

How do I change the database name using MySQL?

Unfortunately, MySQL does not explicitly support that (except for dumping and reloading database again).

From http://dev.mysql.com/doc/refman/5.1/en/rename-database.html:

13.1.32. RENAME DATABASE Syntax

RENAME {DATABASE | SCHEMA} db_name TO new_db_name;

This statement was added in MySQL 5.1.7 but was found to be dangerous and was removed in MySQL 5.1.23. ... Use of this statement could result in loss of database contents, which is why it was removed. Do not use RENAME DATABASE in earlier versions in which it is present.

Unit tests vs Functional tests

In Rails, the unit folder is meant to hold tests for your models, the functional folder is meant to hold tests for your controllers, and the integration folder is meant to hold tests that involve any number of controllers interacting. Fixtures are a way of organizing test data; they reside in the fixtures folder. The test_helper.rb file holds the default configuration for your tests. u can visit this.

Getting the error "Missing $ inserted" in LaTeX

I had this symbol _ in the head of one table and the code didn't run, so I had to delete.

In Angular, I need to search objects in an array

I know if that can help you a bit.

Here is something I tried to simulate for you.

Checkout the jsFiddle ;)

http://jsfiddle.net/migontech/gbW8Z/5/

Created a filter that you also can use in 'ng-repeat'

app.filter('getById', function() {
  return function(input, id) {
    var i=0, len=input.length;
    for (; i<len; i++) {
      if (+input[i].id == +id) {
        return input[i];
      }
    }
    return null;
  }
});

Usage in controller:

app.controller('SomeController', ['$scope', '$filter', function($scope, $filter) {
     $scope.fish = [{category:'freshwater', id:'1', name: 'trout', more:'false'},  {category:'freshwater', id:'2', name:'bass', more:'false'}]

     $scope.showdetails = function(fish_id){
         var found = $filter('getById')($scope.fish, fish_id);
         console.log(found);
         $scope.selected = JSON.stringify(found);
     }
}]);

If there are any questions just let me know.

How do I add a newline to a TextView in Android?

This solved my problem.

stringVar.replaceAll("\\\\n", "\\\n");

Escape quotes in JavaScript

<html>
    <body>
        <a href="#" onclick="DoEdit('Preliminary Assessment &quot;Mini&quot;'); return false;">edit</a>
    </body>
</html>

Should do the trick.

How do I convert from a money datatype in SQL server?

You can try like this:

SELECT PARSENAME('$'+ Convert(varchar,Convert(money,@MoneyValue),1),2)

Print Html template in Angular 2 (ng-print in Angular 2)

you can do like this in angular 2

in ts file

 export class Component{          
      constructor(){
      }
       printToCart(printSectionId: string){
        let popupWinindow
        let innerContents = document.getElementById(printSectionId).innerHTML;
        popupWinindow = window.open('', '_blank', 'width=600,height=700,scrollbars=no,menubar=no,toolbar=no,location=no,status=no,titlebar=no');
        popupWinindow.document.open();
        popupWinindow.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + innerContents + '</html>');
        popupWinindow.document.close();
  }

 }

in html

<div id="printSectionId" >
  <div>
    <h1>AngularJS Print html templates</h1>
    <form novalidate>
      First Name:
      <input type="text"  class="tb8">
      <br>
      <br> Last Name:
      <input type="text"  class="tb8">
      <br>
      <br>
      <button  class="button">Submit</button>
      <button (click)="printToCart('printSectionId')" class="button">Print</button>
    </form>
  </div>
  <div>
    <br/>
   </div>
</div>

Eclipse: Frustration with Java 1.7 (unbound library)

To set JDK you can watch this video : how to set JDK . Then when you'll have JDK:

  1. Right click on build path and select "Build Path"
  2. Choose "Configure Build Path"
  3. Click on "JRE System Library [JavaSE-1.7] (unbound)"
  4. Edit it
  5. Choose "Alternate JRE"
  6. Click on "Installed JREs.." button
  7. Press Add
  8. Choose to add "Standard VM"
  9. Choose JRE Home directory - usually it is locates in "C:\Program Files\Java\jre7" directory
  10. Press "Finish"
  11. Re-check newly appeared "Jre7": Verify that now when you edit "JRE System Library [JavaSE-1.7]" "Alternate JRE" is chosen for jre7.

from jquery $.ajax to angular $http

you can use $.param to assign data :

 $http({
  url: "http://example.appspot.com/rest/app",
  method: "POST",
  data: $.param({"foo":"bar"})
  }).success(function(data, status, headers, config) {
   $scope.data = data;
  }).error(function(data, status, headers, config) {
   $scope.status = status;
 });

look at this : AngularJS + ASP.NET Web API Cross-Domain Issue

Use Device Login on Smart TV / Console

Facebook login for smarttv/devices without facebook sdk is possible throught code , check the documentation here :

https://developers.facebook.com/docs/facebook-login/for-devices

Font size relative to the user's screen resolution?

You can use em, %, px. But in combination with media-queries See this Link to learn about media-queries. Also, CSS3 have some new values for sizing things relative to the current viewport size: vw, vh, and vmin. See link about that.

HTTP Error 403.14 - Forbidden - The Web server is configured to not list the contents of this directory

For my case, I received the same error after creating an empty Web Api project.

I solved it by editing RouteConfig.cs in the App_Start folder :)

I replaced the line of code reading :-

defaults: new { action = "Index", id = UrlParameter.Optional }

with the following :-

defaults: new { controller = "Index", action = "Index", id = UrlParameter.Optional }

Notice I just had to specify the Controller whose index action I would like to invoke first.

Well all the above responses didn't solve my case (as I wanted) e.g.

  • Enabling directory browsing from web.config just listed all files and folders in my project just like php would do when you don't have an index file
  • Setting defaultDocument also didn't work for me somehow still got the HTTP Error 403.14 (Still have no idea why)

If there may be anyone in similar circumstances as mine then give this a try.

How can I show dots ("...") in a span with hidden overflow?

 var tooLong = document.getElementById("longText").value;
    if (tooLong.length() > 18){
        $('#longText').css('text-overflow', 'ellipsis');
    }

How to detect when a youtube video finishes playing?

This can be done through the youtube player API:

http://jsfiddle.net/7Gznb/

Working example:

    <div id="player"></div>

    <script src="http://www.youtube.com/player_api"></script>

    <script>

        // create youtube player
        var player;
        function onYouTubePlayerAPIReady() {
            player = new YT.Player('player', {
              width: '640',
              height: '390',
              videoId: '0Bmhjf0rKe8',
              events: {
                onReady: onPlayerReady,
                onStateChange: onPlayerStateChange
              }
            });
        }

        // autoplay video
        function onPlayerReady(event) {
            event.target.playVideo();
        }

        // when video ends
        function onPlayerStateChange(event) {        
            if(event.data === 0) {          
                alert('done');
            }
        }

    </script>

What's the best way to detect a 'touch screen' device using JavaScript?

var isTouchScreen = 'createTouch' in document;

or

var isTouchScreen = 'createTouch' in document || screen.width <= 699 || 
    ua.match(/(iPhone|iPod|iPad)/) || ua.match(/BlackBerry/) || 
    ua.match(/Android/);

would be a more thorough check I suppose.

How to pass data from Javascript to PHP and vice versa?

Passing data from PHP is easy, you can generate JavaScript with it. The other way is a bit harder - you have to invoke the PHP script by a Javascript request.

An example (using traditional event registration model for simplicity):

<!-- headers etc. omitted -->
<script>
function callPHP(params) {
    var httpc = new XMLHttpRequest(); // simplified for clarity
    var url = "get_data.php";
    httpc.open("POST", url, true); // sending as POST

    httpc.onreadystatechange = function() { //Call a function when the state changes.
        if(httpc.readyState == 4 && httpc.status == 200) { // complete and no errors
            alert(httpc.responseText); // some processing here, or whatever you want to do with the response
        }
    };
    httpc.send(params);
}
</script>
<a href="#" onclick="callPHP('lorem=ipsum&foo=bar')">call PHP script</a>
<!-- rest of document omitted -->

Whatever get_data.php produces, that will appear in httpc.responseText. Error handling, event registration and cross-browser XMLHttpRequest compatibility are left as simple exercises to the reader ;)

See also Mozilla's documentation for further examples

Nodejs cannot find installed module on Windows

For windows, everybody said you should set environment variables for nodejs and npm modules, but do you know why? For some modules, they have command line tool, after installed the module, there'are [module].cmd file in C:\Program Files\nodejs, and it's used for launch in window command. So if you don't add the path containing the cmd file to environment variables %PATH% , you won't launch them successfully through command window.

adb doesn't show nexus 5 device

I have suffered the same issue and was able to solve it by simply changing on my Android device (Nexus 5X) in Developer options > Select USB Configuration to RNDIS (USB Ethernet)

Using PHP Replace SPACES in URLS with %20

Use urlencode() rather than trying to implement your own. Be lazy.

How to POST form data with Spring RestTemplate?

The POST method should be sent along the HTTP request object. And the request may contain either of HTTP header or HTTP body or both.

Hence let's create an HTTP entity and send the headers and parameter in body.

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
map.add("email", "[email protected]");

HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);

ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class );

http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html#postForObject-java.lang.String-java.lang.Object-java.lang.Class-java.lang.Object...-

In Java, remove empty elements from a list of Strings

List<String> list = new ArrayList<String>(Arrays.asList("", "Hi", "", "How"));
           Stream<String> stream = list .stream();
           Predicate<String> empty = empt->(empt.equals(""));
            Predicate<String> emptyRev = empty.negate();
           list=  stream.filter(emptyRev).collect(Collectors.toList());

OR

list =  list .stream().filter(empty->(!empty.equals(""))).collect(Collectors.toList());

Sorting Values of Set

If you sort the strings "12", "15" and "5" then "5" comes last because "5" > "1". i.e. the natural ordering of Strings doesn't work the way you expect.

If you want to store strings in your list but sort them numerically then you will need to use a comparator that handles this. e.g.

Collections.sort(list, new Comparator<String>() {
    public int compare(String o1, String o2) {
        Integer i1 = Integer.parseInt(o1);
        Integer i2 = Integer.parseInt(o2);
        return (i1 > i2 ? -1 : (i1 == i2 ? 0 : 1));
    }
});

Also, I think you are getting slightly mixed up between Collection types. A HashSet and a HashMap are different things.

How can I work with command line on synology?

for my example:

Windows XP ---> Synology:DS218+

  • Step1:
        > DNS: Control Panel (???)
             > Terminal & SNMP(??? & SNMP)
  • Step2:
        Enable Telnet service (?? Telnet ??)
        or Enable SSH Service (?? SSH ??)


    enter image description here
    enter image description here


  • Step3: Launch the terminal on Windows (or via executing

        cmd
    to launch the terminal)
    enter image description here


  • Step4: type: telnet your_nas_ip_or_domain_name, like below

        telnet 192.168.1.104
    enter image description here



  • Step5:
    demo a terminal application, like compiling the Java code

    Fzz login: tsungjung411

    Password:

    # shows the current working directory (?????????)
    $ pwd
    /var/services/homes/tsungjung411


    # edit a Java file (via vi), then compile and run it 
    # (?? vi ?? Java ??,???????)
    $ vi Main.java

    # show the file content (??????)
    $ cat Main.java
    public class Main {
        public static void main(String [] args) {
            System.out.println("hello, World!");
        }
    }

    # compiles the Java file (?? Java ??)
    javac Main.java

    # executes the Java file (?? Java ??)
    $ java Main
    hello, World!

    # shows the file list (??????)
    $ ls
    CloudStation  Main.class  Main.java  www

enter image description here


    # shows the JRE version on this Synology Disk Station
    $ java -version
    openjdk version "1.8.0_151"
    OpenJDK Runtime Environment (IcedTea 3.6.0) (linux-gnu build 1.8.0_151-b12)
    OpenJDK 64-Bit Server VM (build 25.151-b12, mixed mode)




  • Step6:
    demo another terminal application, like running the Python code

    $ python
    Python 2.7.12 (default, Nov 10 2017, 20:30:30)
    [GCC 4.9.3 20150311 (prerelease)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>>
    >>> import sys
    >>>
    >>> # shows the the python version
    >>> print(sys.version)
    2.7.12 (default, Nov 10 2017, 20:30:30)
    [GCC 4.9.3 20150311 (prerelease)]
    >>>
    >>> import os
    >>>
    >>> # shows the current working directory
    >>> print(os.getcwd())
    /volume1/homes/tsungjung411

enter image description here


    $ # launch Python 3
    $ python3
    Python 3.5.1 (default, Dec  9 2016, 00:20:03)
    [GCC 4.9.3 20150311 (prerelease)] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>>




Warning: Use the 'defaultValue' or 'value' props on <select> instead of setting 'selected' on <option>

What you could do is have the selected attribute on the <select> tag be an attribute of this.state that you set in the constructor. That way, the initial value you set (the default) and when the dropdown changes you need to change your state.

constructor(){
  this.state = {
    selectedId: selectedOptionId
  }
}

dropdownChanged(e){
  this.setState({selectedId: e.target.value});
}

render(){
  return(
    <select value={this.selectedId} onChange={this.dropdownChanged.bind(this)}>
      {option_id.map(id =>
        <option key={id} value={id}>{options[id].name}</option>
      )}
    </select>
  );
}

Firebase FCM notifications click_action payload

As far as I can tell, at this point it is not possible to set click_action in the console.

While not a strict answer to how to get the click_action set in the console, you can use curl as an alternative:

curl --header "Authorization: key=<YOUR_KEY_GOES_HERE>" --header Content-Type:"application/json" https://fcm.googleapis.com/fcm/send  -d "{\"to\":\"/topics/news\",\"notification\": {\"title\": \"Click Action Message\",\"text\": \"Sample message\",\"click_action\":\"OPEN_ACTIVITY_1\"}}"

This is an easy way to test click_action mapping. It requires an intent filter like the one specified in the FCM docs:

_x000D_
_x000D_
<intent-filter>_x000D_
  <action android:name="OPEN_ACTIVITY_1" />_x000D_
  <category android:name="android.intent.category.DEFAULT" />_x000D_
</intent-filter>
_x000D_
_x000D_
_x000D_

This also makes use of topics to set the audience. In order for this to work you will need to subscribe to a topic called "news".

FirebaseMessaging.getInstance().subscribeToTopic("news");

Even though it takes several hours to see a newly-created topic in the console, you may still send messages to it through the FCM apis.

Also, keep in mind, this will only work if the app is in the background. If it is in the foreground you will need to implement an extension of FirebaseMessagingService. In the onMessageReceived method, you will need to manually navigate to your click_action target:

    @Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    //This will give you the topic string from curl request (/topics/news)
    Log.d(TAG, "From: " + remoteMessage.getFrom());
    //This will give you the Text property in the curl request(Sample Message): 
    Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
    //This is where you get your click_action 
    Log.d(TAG, "Notification Click Action: " + remoteMessage.getNotification().getClickAction());
    //put code here to navigate based on click_action
}

As I said, at this time I cannot find a way to access notification payload properties through the console, but I thought this work around might be helpful.

jquery variable syntax

No, it certainly is not. It is just another variable name. The $() you're talking about is actually the jQuery core function. The $self is just a variable. You can even rename it to foo if you want, this doesn't change things. The $ (and _) are legal characters in a Javascript identifier.

Why this is done so is often just some code convention or to avoid clashes with reversed keywords. I often use it for $this as follows:

var $this = $(this);

How to fire a change event on a HTMLSelectElement if the new value is the same as the old?

It's not firing because the value hasn't "changed". It's the same value. Unfortunately, you can't achieve the desired behaviour using the change event.

You can handle the blur event and do whatever processing you need when the user leaves the select box. That way you can run the code you need even if the user selects the same value.

pass JSON to HTTP POST Request

I worked on this for too long. The answer that helped me was at: send Content-Type: application/json post with node.js

Which uses the following format:

request({
    url: url,
    method: "POST",
    headers: {
        "content-type": "application/json",
        },
    json: requestData
//  body: JSON.stringify(requestData)
    }, function (error, resp, body) { ...

How do I generate a random integer between min and max in Java?

Using the Random class is the way to go as suggested in the accepted answer, but here is a less straight-forward correct way of doing it if you didn't want to create a new Random object :

min + (int) (Math.random() * (max - min + 1));

how to setup ssh keys for jenkins to publish via ssh

For Windows:

  1. Install the necessary plugins for the repository (ex: GitHub install GitHub and GitHub Authentication plugins) in Jenkins.
  2. You can generate a key with Putty key generator, or by running the following command in git bash: $ ssh-keygen -t rsa -b 4096 -C [email protected]
  3. Private key must be OpenSSH. You can convert your private key to OpenSSH in putty key generator
  4. SSH keys come in pairs, public and private. Public keys are inserted in the repository to be cloned. Private keys are saved as credentials in Jenkins
  5. You need to copy the SSH URL not the HTTPS to work with ssh keys.

Convert double to string C++?

std::string stringify(double x)
 {
   std::ostringstream o;
   if (!(o << x))
     throw BadConversion("stringify(double)");
   return o.str();
 }

C++ FAQ: http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.1

SQL Query for Logins

Selecting from sysusers will get you information about users on the selected database, not logins on the server.

Change a Nullable column to NOT NULL with Default Value

you need to execute two queries:

One - to add the default value to the column required

ALTER TABLE 'Table_Name` ADD DEFAULT 'value' FOR 'Column_Name'

i want add default value to Column IsDeleted as below:

Example: ALTER TABLE [dbo].[Employees] ADD Default 0 for IsDeleted

Two - to alter the column value nullable to not null

ALTER TABLE 'table_name' ALTER COLUMN 'column_name' 'data_type' NOT NULL

i want to make the column IsDeleted as not null

ALTER TABLE [dbo].[Employees] Alter Column IsDeleted BIT NOT NULL

Change output format for MySQL command line results to CSV

It is how to save results to CSV on the client-side without additional non-standard tools. This example uses only mysql client and awk.

One-line:

mysql --skip-column-names --batch -e 'select * from dump3' t | awk -F'\t' '{ sep=""; for(i = 1; i <= NF; i++) { gsub(/\\t/,"\t",$i); gsub(/\\n/,"\n",$i); gsub(/\\\\/,"\\",$i); gsub(/"/,"\"\"",$i); printf sep"\""$i"\""; sep=","; if(i==NF){printf"\n"}}}'

Logical explanation of what is needed to do

  1. First, let see how data looks like in RAW mode (with --raw option). the database and table are respectively t and dump3

    You can see the field starting from "new line" (in the first row) is splitted into three lines due to new lines placed in the value.

mysql --skip-column-names --batch --raw -e 'select * from dump3' t

one line        2       new line
quotation marks " backslash \ two quotation marks "" two backslashes \\ two tabs                new line
the end of field

another line    1       another line description without any special chars
  1. OUTPUT data in batch mode (without --raw option) - each record changed to the one-line texts by escaping characters like \ <tab> and new-lines
mysql --skip-column-names --batch -e 'select * from dump3' t

one line      2  new line\nquotation marks " backslash \\ two quotation marks "" two backslashes \\\\ two tabs\t\tnew line\nthe end of field
another line  1  another line description without any special chars
  1. And data output in CSV format

The clue is to save data in CSV format with escaped characters.

The way to do that is to convert special entities which mysql --batch produces (\t as tabs \\ as backshlash and \n as newline) into equivalent bytes for each value (field). Then whole value is escaped by " and enclosed also by ". Btw - using the same characters for escaping and enclosing gently simplifies output and processing, because you don't have two special characters. For this reason all you have to do with values (from csv format perspective) is to change " to "" whithin values. In more common way (with escaping and enclosing respectively \ and ") you would have to first change \ to \\ and then change " into \".

And the commands' explanation step by step:

# we produce one-line output as showed in step 2.
mysql --skip-column-names --batch -e 'select * from dump3' t

# set fields separator to  because mysql produces in that way
| awk -F'\t' 

# this start iterating every line/record from the mysql data - standard behaviour of awk
'{ 

# field separator is empty because we don't print a separator before the first output field
sep=""; 

-- iterating by every field and converting the field to csv proper value
for(i = 1; i <= NF; i++) { 
-- note: \\ two shlashes below mean \ for awk because they're escaped

-- changing \t into byte corresponding to <tab> 
    gsub(/\\t/, "\t",$i); 

-- changing \n into byte corresponding to new line
    gsub(/\\n/, "\n",$i); 

-- changing two \\ into one \  
    gsub(/\\\\/,"\\",$i);

-- changing value into CSV proper one literally - change " into ""
    gsub(/"/,   "\"\"",$i); 

-- print output field enclosed by " and adding separator before
    printf sep"\""$i"\"";  

-- separator is set after first field is processed - because earlier we don't need it
    sep=","; 

-- adding new line after the last field processed - so this indicates csv record separator
    if(i==NF) {printf"\n"} 
    }
}'

OSError - Errno 13 Permission denied

Another option is to ensure the file is not open anywhere else on your machine.

How to randomize (or permute) a dataframe rowwise and columnwise?

Given the R data.frame:

> df1
  a b c
1 1 1 0
2 1 0 0
3 0 1 0
4 0 0 0

Shuffle row-wise:

> df2 <- df1[sample(nrow(df1)),]
> df2
  a b c
3 0 1 0
4 0 0 0
2 1 0 0
1 1 1 0

By default sample() randomly reorders the elements passed as the first argument. This means that the default size is the size of the passed array. Passing parameter replace=FALSE (the default) to sample(...) ensures that sampling is done without replacement which accomplishes a row wise shuffle.

Shuffle column-wise:

> df3 <- df1[,sample(ncol(df1))]
> df3
  c a b
1 0 1 1
2 0 1 0
3 0 0 1
4 0 0 0

How does @synchronized lock/unlock in Objective-C?

The Objective-C language level synchronization uses the mutex, just like NSLock does. Semantically there are some small technical differences, but it is basically correct to think of them as two separate interfaces implemented on top of a common (more primitive) entity.

In particular with a NSLock you have an explicit lock whereas with @synchronized you have an implicit lock associated with the object you are using to synchronize. The benefit of the language level locking is the compiler understands it so it can deal with scoping issues, but mechanically they behave basically the same.

You can think of @synchronized as a compiler rewrite:

- (NSString *)myString {
  @synchronized(self) {
    return [[myString retain] autorelease];
  }
}

is transformed into:

- (NSString *)myString {
  NSString *retval = nil;
  pthread_mutex_t *self_mutex = LOOK_UP_MUTEX(self);
  pthread_mutex_lock(self_mutex);
  retval = [[myString retain] autorelease];
  pthread_mutex_unlock(self_mutex);
  return retval;
}

That is not exactly correct because the actual transform is more complex and uses recursive locks, but it should get the point across.

jQuery plugin returning "Cannot read property of undefined"

Usually that problem is that in the last iteration you have an empty object or undefine object. use console.log() inside you cicle to check that this doent happend.

Sometimes a prototype in some place add an extra element.

How to enable remote access of mysql in centos?

In case of Allow IP to mysql server linux machine. you can do following command--

 nano /etc/httpd/conf.d/phpMyAdmin.conf  and add Desired IP.

<Directory /usr/share/phpMyAdmin/>
   AddDefaultCharset UTF-8
   Order allow,deny
   allow from all
   <IfModule mod_authz_core.c>
     # Apache 2.4
     <RequireAny>

    Require ip 192.168.9.1(Desired IP)

</RequireAny>
   </IfModule>
 <IfModule !mod_authz_core.c>
     # Apache 2.2
     Order Deny,Allow
     #Allow from All

     Allow from 192.168.9.1(Desired IP)

</IfModule>

And after Update, please restart using following command--

sudo systemctl restart httpd.service

Java: Rotating Images

This is how you can do it. This code assumes the existance of a buffered image called 'image' (like your comment says)

// The required drawing location
int drawLocationX = 300;
int drawLocationY = 300;

// Rotation information

double rotationRequired = Math.toRadians (45);
double locationX = image.getWidth() / 2;
double locationY = image.getHeight() / 2;
AffineTransform tx = AffineTransform.getRotateInstance(rotationRequired, locationX, locationY);
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);

// Drawing the rotated image at the required drawing locations
g2d.drawImage(op.filter(image, null), drawLocationX, drawLocationY, null);

Docker container will automatically stop after "docker run -d"

If you are using CMD at the end of your Dockerfile, what you can do is adding the code at the end. This will only work if your docker is built on ubuntu, or any OS that can use bash.

&& /bin/bash

Briefly the end of your Dockerfile will look like something like this.

...

CMD ls && ... && /bin/bash

So if you have anything running automatically after you run your docker image, and when the task is complete the bash terminal will be active inside your docker. Thereby, you can enter you shell commands.

how to refresh Select2 dropdown menu after ajax loading different content?

select2 has the placeholder parameter. Use that one

$("#state").select2({
   placeholder: "Choose a Country"
 });

How to find out which processes are using swap space in Linux?

Here's another variant of the script, but meant to give more readable output (you need to run this as root to get exact results):

#!/bin/bash

    # find-out-what-is-using-your-swap.sh
    # -- Get current swap usage for all running processes
    # --
    # -- rev.0.3, 2012-09-03, Jan Smid          - alignment and intendation, sorting
    # -- rev.0.2, 2012-08-09, Mikko Rantalainen - pipe the output to "sort -nk3" to get sorted output
    # -- rev.0.1, 2011-05-27, Erik Ljungstrom   - initial version


SCRIPT_NAME=`basename $0`;
SORT="kb";                 # {pid|kB|name} as first parameter, [default: kb]
[ "$1" != "" ] && { SORT="$1"; }

[ ! -x `which mktemp` ] && { echo "ERROR: mktemp is not available!"; exit; }
MKTEMP=`which mktemp`;
TMP=`${MKTEMP} -d`;
[ ! -d "${TMP}" ] && { echo "ERROR: unable to create temp dir!"; exit; }

>${TMP}/${SCRIPT_NAME}.pid;
>${TMP}/${SCRIPT_NAME}.kb;
>${TMP}/${SCRIPT_NAME}.name;

SUM=0;
OVERALL=0;
    echo "${OVERALL}" > ${TMP}/${SCRIPT_NAME}.overal;

for DIR in `find /proc/ -maxdepth 1 -type d -regex "^/proc/[0-9]+"`;
do
    PID=`echo $DIR | cut -d / -f 3`
    PROGNAME=`ps -p $PID -o comm --no-headers`

    for SWAP in `grep Swap $DIR/smaps 2>/dev/null| awk '{ print $2 }'`
    do
        let SUM=$SUM+$SWAP
    done

    if (( $SUM > 0 ));
    then
        echo -n ".";
        echo -e "${PID}\t${SUM}\t${PROGNAME}" >> ${TMP}/${SCRIPT_NAME}.pid;
        echo -e "${SUM}\t${PID}\t${PROGNAME}" >> ${TMP}/${SCRIPT_NAME}.kb;
        echo -e "${PROGNAME}\t${SUM}\t${PID}" >> ${TMP}/${SCRIPT_NAME}.name;
    fi
    let OVERALL=$OVERALL+$SUM
    SUM=0
done
echo "${OVERALL}" > ${TMP}/${SCRIPT_NAME}.overal;
echo;
echo "Overall swap used: ${OVERALL} kB";
echo "========================================";
case "${SORT}" in
    name )
        echo -e "name\tkB\tpid";
        echo "========================================";
        cat ${TMP}/${SCRIPT_NAME}.name|sort -r;
        ;;

    kb )
        echo -e "kB\tpid\tname";
        echo "========================================";
        cat ${TMP}/${SCRIPT_NAME}.kb|sort -rh;
        ;;

    pid | * )
        echo -e "pid\tkB\tname";
        echo "========================================";
        cat ${TMP}/${SCRIPT_NAME}.pid|sort -rh;
        ;;
esac
rm -fR "${TMP}/";

Is it possible to decompile an Android .apk file?

Are the users able to convert the apk file of my application back to the actual code?

yes.

People can use various tools to:

  • analysis: your apk
  • decode/hack your apk
    • using FDex2 to dump out dex file
      • then using dex2jar to convert to jar
        • then using jadx to conver to java source code

If they do - is there any way to prevent this?

yes. Several (can combined) ways to prevent (certain degree) this:

  • low level: code obfuscation
    • using Android ProGuard
  • high level: use android harden scenario

More details can refer my Chinese tutorial: ??????????

CSS: Background image and padding

setting direction CSS property to rtl should work with you. I guess it isn't supported on IE6.

e.g

<ul style="direction:rtl;">
<li> item </li>
<li> item </li>
</ul>

How to include() all PHP files from a directory?

Do no write a function() to include files in a directory. You may lose the variable scopes, and may have to use "global". Just loop on the files.

Also, you may run into difficulties when an included file has a class name that will extend to the other class defined in the other file - which is not yet included. So, be careful.

Get a list of resources from classpath directory

So in terms of the PathMatchingResourcePatternResolver this is what is needed in the code:

@Autowired
ResourcePatternResolver resourceResolver;

public void getResources() {
  resourceResolver.getResources("classpath:config/*.xml");
}

Where is the user's Subversion config file stored on the major operating systems?

In TortoiseSVN you can access and modify some settings in the context menu "Settings/General" in explorer.

E.g. the "Global ignore pattern" can be edited directly in the dialog box. Such changings are the stored in the registry as bahrep pointed out in her answer.

(Win10/TortoiseSVN 1.13.1, Build 28686 - 64 Bit)

Convert int to char in java

Whenever you type cast integer to char it will return the ascii value of that int (once go through the ascii table for better understanding)

    int a=68;
    char b=(char)a;

    System.out.println(b);//it will return ascii value of 68

    //output- D

Recyclerview inside ScrollView not scrolling smoothly

Summary of all answers (Advantages & Disadvantages)

For single recyclerview

you can use it inside Coordinator layout.

Advantage - it will not load entire recyclerview items. So smooth loading.

Disadvantage - you can't load two recyclerview inside Coordinator layout - it produce scrolling problems

reference - https://stackoverflow.com/a/33143512/3879847

For multiple recylerview with minimum rows

you can load inside NestedScrollView

Advantage - it will scroll smoothly

Disadvantage - It load all rows of recyclerview so your activity open with delay

reference - https://stackoverflow.com/a/33143512/3879847

For multiple recylerview with large rows(more than 100)

You must go with recyclerview.

Advantage - Scroll smoothly, load smoothly

Disadvantage - You need to write more code and logic

Load each recylerview inside main recyclerview with help of multi-viewholders

ex:

MainRecyclerview

-ChildRecyclerview1 (ViewHolder1)

-ChildRecyclerview2 (ViewHolder2)

-ChildRecyclerview3 (ViewHolder3) 

-Any other layout   (ViewHolder4)

Reference for multi-viewHolder - https://stackoverflow.com/a/26245463/3879847

How can I pass POST parameters in a URL?

First off, a disclaimer: I don't think marrying POST with URL parameters is a brilliant idea. Like others suggested, you're better off using a hidden form for passing user information.

However, a question made me curious how PHP is handling such a case. It turned out that it's possible in theory. Here's a proof:

post_url_params.html

<!DOCTYPE html>
<html>
    <head></head>
    <body>
        <form method="post" action="post_url_params.php?key1=value1">
            <input type="hidden" name="key2" value="value2">
            <input type="hidden" name="key3" value="value3">
            <input type="submit" value="click me">
        </form>
    </body>
</html>

post_url_params.php

<?php
    print_r($_POST);
    print_r($_GET);
    echo $_SERVER['REQUEST_METHOD'];
?>

Output

Array ( [key2] => value2 [key3] => value3 )
Array ( [key1] => value1 )
POST

One can clearly see that PHP stores URL parameters in the $_GET variable and form data in the $_POST variable. I suspect it's very PHP- and server-specific, though, and is definitely not a thing to rely on.

What is the `data-target` attribute in Bootstrap 3?

data-target is used by bootstrap to make your life easier. You (mostly) do not need to write a single line of Javascript to use their pre-made JavaScript components.

The data-target attribute should contain a CSS selector that points to the HTML Element that will be changed.

Modal Example Code from BS3:

<!-- Button trigger modal -->
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  [...]
</div>

In this example, the button has data-target="#myModal", if you click on it, <div id="myModal">...</div> will be modified (in this case faded in). This happens because #myModal in CSS selectors points to elements that have an id attribute with the myModal value.

Further information about the HTML5 "data-" attribute: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes

How to split strings over multiple lines in Bash?

However, if you have indented code, it doesn't work out so well:

    echo "continuation \
    lines"
>continuation     lines

Try with single quotes and concatenating the strings:

    echo 'continuation' \
    'lines'
>continuation lines

Note: the concatenation includes a whitespace.

Regular expression for address field validation

Here is the approach I have taken to finding addresses using regular expressions:

A set of patterns is useful to find many forms that we might expect from an address starting with simply a number followed by set of strings (ex. 1 Basic Road) and then getting more specific such as looking for "P.O. Box", "c/o", "attn:", etc.

Below is a simple test in python. The test will find all the addresses but not the last 4 items which are company names. This example is not comprehensive, but can be altered to suit your needs and catch examples you find in your data.

import re
strings = [
    '701 FIFTH AVE',
    '2157 Henderson Highway',
    'Attn: Patent Docketing',
    'HOLLYWOOD, FL 33022-2480',
    '1940 DUKE STREET',
    '111 MONUMENT CIRCLE, SUITE 3700',
    'c/o Armstrong Teasdale LLP',
    '1 Almaden Boulevard',
    '999 Peachtree Street NE',
    'P.O. BOX 2903',
    '2040 MAIN STREET',
    '300 North Meridian Street',
    '465 Columbus Avenue',
    '1441 SEAMIST DR.',
    '2000 PENNSYLVANIA AVENUE, N.W.',
    '465 Columbus Avenue',
    '28 STATE STREET',
    'P.O, Drawer 800889.',
    '2200 CLARENDON BLVD.',
    '840 NORTH PLANKINTON AVENUE',
    '1025 Connecticut Avenue, NW',
    '340 Commercial Street',
    '799 Ninth Street, NW',
    '11318 Lazarro Ln',
    'P.O, Box 65745',
    'c/o Ballard Spahr LLP',
    '8210 SOUTHPARK TERRACE',
    '1130 Connecticut Ave., NW, Suite 420',
    '465 Columbus Avenue',
    "BANNER & WITCOFF , LTD",
    "CHIP LAW GROUP",
    "HAMMER & ASSOCIATES, P.C.",
    "MH2 TECHNOLOGY LAW GROUP, LLP",
]

patterns = [
    "c\/o [\w ]{2,}",
    "C\/O [\w ]{2,}",
    "P.O\. [\w ]{2,}",
    "P.O\, [\w ]{2,}",
    "[\w\.]{2,5} BOX [\d]{2,8}",
    "^[#\d]{1,7} [\w ]{2,}",
    "[A-Z]{2,2} [\d]{5,5}",
    "Attn: [\w]{2,}",
    "ATTN: [\w]{2,}",
    "Attention: [\w]{2,}",
    "ATTENTION: [\w]{2,}"
]
contact_list = []
total_count = len(strings)
found_count = 0
for string in strings:
    pat_no = 1
    for pattern in patterns:
        match = re.search(pattern, string.strip())
        if match:
            print("Item found: " + match.group(0) + " | Pattern no: " + str(pat_no))
            found_count += 1
        pat_no += 1

print("-- Total: " + str(total_count) + " Found: " + str(found_count)) 

How to Check if value exists in a MySQL database

For Exact Match

"SELECT * FROM yourTable WHERE city = 'c7'"

For Pattern / Wildcard Search

"SELECT * FROM yourTable WHERE city LIKE '%c7%'"

Of course you can change '%c7%' to '%c7' or 'c7%' depending on how you want to search it. For exact match, use first query example.

PHP

$result = mysql_query("SELECT * FROM yourTable WHERE city = 'c7'");
$matchFound = mysql_num_rows($result) > 0 ? 'yes' : 'no';
echo $matchFound;

You can also use if condition there.

"SMTP Error: Could not authenticate" in PHPMailer

I received this error because of percentage signs in the password.

How to validate phone number in laravel 5.2?

You can try out this phone validator package. Laravel Phone

Update

I recently discovered another package Lavarel Phone Validator (stuyam/laravel-phone-validator), that uses the free Twilio phone lookup service

How to redirect and append both stdout and stderr to a file with Bash?

In Bash you can also explicitly specify your redirects to different files:

cmd >log.out 2>log_error.out

Appending would be:

cmd >>log.out 2>>log_error.out

Finding the direction of scrolling in a UIScrollView?

This is what it worked for me (in Objective-C):

    - (void)scrollViewDidScroll:(UIScrollView *)scrollView{

        NSString *direction = ([scrollView.panGestureRecognizer translationInView:scrollView.superview].y >0)?@"up":@"down";
        NSLog(@"%@",direction);
    }

IOException: Too many open files

Aside from looking into root cause issues like file leaks, etc. in order to do a legitimate increase the "open files" limit and have that persist across reboots, consider editing

/etc/security/limits.conf

by adding something like this

jetty soft nofile 2048
jetty hard nofile 4096

where "jetty" is the username in this case. For more details on limits.conf, see http://linux.die.net/man/5/limits.conf

log off and then log in again and run

ulimit -n

to verify that the change has taken place. New processes by this user should now comply with this change. This link seems to describe how to apply the limit on already running processes but I have not tried it.

The default limit 1024 can be too low for large Java applications.

Can't change z-index with JQuery

zIndex is part of javaScript notation.(camelCase)
but jQuery.css uses same as CSS syntax.
so it is z-index.

you forgot .css("attr","value"). use ' or " in both, attr and val. so, .css("z-index","3000");

Bootstrap 4 align navbar items to the right

If you want Home, Features and Pricing on left immediately after your nav-brand, and then login and register on right then wrap the two lists in <div> and use .justify-content-between:

<div class="collapse navbar-collapse justify-content-between">
<ul>....</ul>
<ul>...</ul>
</div>

jQuery: Return data after ajax call success

Idk if you guys solved it but I recommend another way to do it, and it works :)

    ServiceUtil = ig.Class.extend({
        base_url : 'someurl',

        sendRequest: function(request)
        {
            var url = this.base_url + request;
            var requestVar = new XMLHttpRequest();
            dataGet = false;

            $.ajax({
                url: url,
                async: false,
                type: "get",
                success: function(data){
                    ServiceUtil.objDataReturned = data;
                }
            });
            return ServiceUtil.objDataReturned;                
        }
    })

So the main idea here is that, by adding async: false, then you make everything waits until the data is retrieved. Then you assign it to a static variable of the class, and everything magically works :)

Iterate over each line in a string in PHP

preg_split the variable containing the text, and iterate over the returned array:

foreach(preg_split("/((\r?\n)|(\r\n?))/", $subject) as $line){
    // do stuff with $line
} 

Do you have to include <link rel="icon" href="favicon.ico" type="image/x-icon" />?

I use it for two reasons:

  1. I can force a refresh of the icon by adding a query parameter for example ?v=2. like this: <link rel="icon" href="/favicon.ico?v=2" type="image/x-icon" />

  2. In case I need to specify the path.

Checking during array iteration, if the current element is the last element

you can use PHP's end()

$array = array('a' => 1,'b' => 2,'c' => 3);
$lastElement = end($array);
foreach($array as $k => $v) {
    echo $v . '<br/>';
    if($v == $lastElement) {
         // 'you can do something here as this condition states it just entered last element of an array'; 
    }
}

Update1

as pointed out by @Mijoja the above could will have problem if you have same value multiple times in array. below is the fix for it.

$array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 2);
//point to end of the array
end($array);
//fetch key of the last element of the array.
$lastElementKey = key($array);
//iterate the array
foreach($array as $k => $v) {
    if($k == $lastElementKey) {
        //during array iteration this condition states the last element.
    }
}

Update2

I found solution by @onteria_ to be better then what i have answered since it does not modify arrays internal pointer, i am updating the answer to match his answer.

$array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 2);
// Get array keys
$arrayKeys = array_keys($array);
// Fetch last array key
$lastArrayKey = array_pop($arrayKeys);
//iterate array
foreach($array as $k => $v) {
    if($k == $lastArrayKey) {
        //during array iteration this condition states the last element.
    }
}

Thank you @onteria_

Update3

As pointed by @CGundlach PHP 7.3 introduced array_key_last which seems much better option if you are using PHP >= 7.3

$array = array('a' => 1,'b' => 2,'c' => 3);
$lastKey = array_key_last($array);
foreach($array as $k => $v) {
    echo $v . '<br/>';
    if($k == $lastKey) {
         // 'you can do something here as this condition states it just entered last element of an array'; 
    }
}

CSS how to make scrollable list

Another solution would be as below where the list is placed under a drop-down button.

  <button class="btn dropdown-toggle btn-primary btn-sm" data-toggle="dropdown"
    >Markets<span class="caret"></span></button>

    <ul class="dropdown-menu", style="height:40%; overflow:hidden; overflow-y:scroll;">
      {{ form.markets }}
    </ul>

React Router v4 - How to get current route?

In react router 4 the current route is in - this.props.location.pathname. Just get this.props and verify. If you still do not see location.pathname then you should use the decorator withRouter.

This might look something like this:

import {withRouter} from 'react-router-dom';

const SomeComponent = withRouter(props => <MyComponent {...props}/>);

class MyComponent extends React.Component {
  SomeMethod () {
    const {pathname} = this.props.location;
  }
}

Flutter: Trying to bottom-center an item in a Column, but it keeps left-aligning

I have used this approach,

What i want is, A layout always in bottom but whenever Keyboard pops-up that layout also comes over it

enter image description here

body: Container(
        color: Colors.amber,
        height: double.maxFinite,
        child: new Stack(
          //alignment:new Alignment(x, y)
          children: <Widget>[
            new Positioned(
              child: myWidget(context, data.iconName, Colors.red),
            ),
            new Positioned(
              child: new Align(
                alignment: FractionalOffset.bottomCenter,
                child: myWidget(context, data.iconName, Colors.green)
              ),
            )
          ],
        ),
      ),

Random record from MongoDB

You can also use MongoDB's geospatial indexing feature to select the documents 'nearest' to a random number.

First, enable geospatial indexing on a collection:

db.docs.ensureIndex( { random_point: '2d' } )

To create a bunch of documents with random points on the X-axis:

for ( i = 0; i < 10; ++i ) {
    db.docs.insert( { key: i, random_point: [Math.random(), 0] } );
}

Then you can get a random document from the collection like this:

db.docs.findOne( { random_point : { $near : [Math.random(), 0] } } )

Or you can retrieve several document nearest to a random point:

db.docs.find( { random_point : { $near : [Math.random(), 0] } } ).limit( 4 )

This requires only one query and no null checks, plus the code is clean, simple and flexible. You could even use the Y-axis of the geopoint to add a second randomness dimension to your query.

Windows batch script launch program and exit console

Use start notepad.exe.

More info with start /?.

Create a new database with MySQL Workbench

  1. Launch MySQL Workbench.
  2. On the left pane of the welcome window, choose a database to connect to under "Open Connection to Start Querying".
  3. The query window will open. On its left pane, there is a section titled "Object Browser", which shows the list of databases. (Side note: The terms "schema" and "database" are synonymous in this program.)
  4. Right-click on one of the existing databases and click "Create Schema...". This will launch a wizard that will help you create a database.

If you'd prefer to do it in SQL, enter this query into the query window:

CREATE SCHEMA Test

Press CTRL + Enter to submit it, and you should see confirmation in the output pane underneath the query window. You'll have to right-click on an existing schema in the Object panel and click "Refresh All" to see it show up, though.

"insufficient memory for the Java Runtime Environment " message in eclipse

If you are using Virtual Machine (VM), allocate more RAM to your VM and your problem will be solved.

How to generate Class Diagram (UML) on Android Studio (IntelliJ Idea)

For those who want to use simpleUML in Android Studio and having issues in running SimpleUML.

First download simpleUML jar from here https://plugins.jetbrains.com/plugin/4946-simpleumlce

Now follow the below steps.

Step 1:

Click on File and go to Settings (File ? Settings)

Step 2

Select Plugins from Left Panel and click Install plugin from disk


1]

Step 3:

Locate the SimpleUML jar file and select it.

2]

Step 4:

Now Restart Android Studio (File ? Invalidate Caches/Restart ? Just Restart)

Step 5:

After you restart Right Click the Package name and Select New Diagram or Add to simpleUML Diagram ? New Diagram.

3

Step 6:

Set a file name and create UML file. I created with name NewDiagram

enter image description here Step 7:

Now Right Click the Package name and Select the file you created. In my case it was NewDiagram

enter image description here

Step 8:

All files are stacked on top of one another. You can just drag and drop them and set a hierarchy.

enter image description here

Like this below, you can drag these classes

enter image description here

Convert a secure string to plain text

You are close, but the parameter you pass to SecureStringToBSTR must be a SecureString. You appear to be passing the result of ConvertFrom-SecureString, which is an encrypted standard string. So call ConvertTo-SecureString on this before passing to SecureStringToBSTR.

$SecurePassword = ConvertTo-SecureString $PlainPassword -AsPlainText -Force
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecurePassword)
$UnsecurePassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)

Joining two lists together

As long as they are of the same type, it's very simple with AddRange:

list2.AddRange(list1);

Apply function to each column in a data frame observing each columns existing data type

df <- head(mtcars)
df$string <- c("a","b", "c", "d","e", "f"); df

my.min <- unlist(lapply(df, min))
my.max <- unlist(lapply(df, max))

Find and replace Android studio

Use ctrl+R or cmd+R in OSX

Upgrade to python 3.8 using conda

You can update your python version to 3.8 in conda using the command

conda install -c anaconda python=3.8

as per https://anaconda.org/anaconda/python. Though not all packages support 3.8 yet, running

conda update --all

may resolve some dependency failures. You can also create a new environment called py38 using this command

conda create -n py38 python=3.8

Edit - note that the conda install option will potentially take a while to solve the environment, and if you try to abort this midway through you will lose your Python installation (usually this means it will resort to non-conda pre-installed system Python installation).

Struct memory layout in C

In C, the compiler is allowed to dictate some alignment for every primitive type. Typically the alignment is the size of the type. But it's entirely implementation-specific.

Padding bytes are introduced so every object is properly aligned. Reordering is not allowed.

Possibly every remotely modern compiler implements #pragma pack which allows control over padding and leaves it to the programmer to comply with the ABI. (It is strictly nonstandard, though.)

From C99 §6.7.2.1:

12 Each non-bit-field member of a structure or union object is aligned in an implementation- defined manner appropriate to its type.

13 Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.

Drag and drop a DLL to the GAC ("assembly") in windows server 2008 .net 4.0

The gacutil utility is not available on client machines, and the Window SDK license forbids redistributing it to your customers. When your customer can not, will not, (and really should not) download the 300MB Windows SDK as part of your application's install process.

There is an officially supported API you (or your installer) can use to register an assembly in the global assembly cache. Microsoft's Windows Installer technology knows how to call this API for you. You would have to consult your MSI installer utility (e.g. WiX, InnoSetup) for their own syntax of how to indicate you want an assembly to be registered in the Global Assembly Cache.

But MSI, and gacutil, are doing nothing special. They simply call the same API you can call yourself. For documentation on how to register an assembly through code, see:

KB317540: DOC: Global Assembly Cache (GAC) APIs Are Not Documented in the .NET Framework Software Development Kit (SDK) Documentation

var IAssemblyCache assemblyCache;
CreateAssemblyCache(ref assemblyCache, 0);


String manifestPath = "D:\Program Files\Contoso\Frobber\Grob.dll";

FUSION_INSTALL_REFERENCE refData;
refData.cbSize = SizeOf(refData); //The size of the structure in bytes
refData.dwFlags = 0; //Reserved, must be zero
refData.guidScheme = FUSION_REFCOUNT_FILEPATH_GUID; //The assembly is referenced by an application that is represented by a file in the file system. The szIdentifier field is the path to this file.
refData.szIdentifier = "D:\Program Files\Contoso\Frobber\SuperGrob.exe"; //A unique string that identifies the application that installed the assembly
refData.szNonCannonicalData = "Super cool grobber 9000"; //A string that is only understood by the entity that adds the reference. The GAC only stores this string

//Add a new assembly to the GAC. 
//The assembly must be persisted in the file system and is copied to the GAC.
assemblyCache.InstallAssembly(
      IASSEMBLYCACHE_INSTALL_FLAG_FORCE_REFRESH, //The files of an existing assembly are overwritten regardless of their version number
      manifestPath, //A string pointing to the dynamic-linked library (DLL) that contains the assembly manifest. Other assembly files must reside in the same directory as the DLL that contains the assembly manifest.
      refData);

More documentation before the KB article is deleted:

The fields of the structure are defined as follows:

  • cbSize - The size of the structure in bytes.
  • dwFlags - Reserved, must be zero.
  • guidScheme - The entity that adds the reference.
  • szIdentifier - A unique string that identifies the application that installed the assembly.
  • szNonCannonicalData - A string that is only understood by the entity that adds the reference. The GAC only stores this string.

Possible values for the guidScheme field can be one of the following:

FUSION_REFCOUNT_MSI_GUID - The assembly is referenced by an application that has been installed by using Windows Installer. The szIdentifier field is set to MSI, and szNonCannonicalData is set to Windows Installer. This scheme must only be used by Windows Installer itself. FUSION_REFCOUNT_UNINSTALL_SUBKEY_GUID - The assembly is referenced by an application that appears in Add/Remove Programs. The szIdentifier field is the token that is used to register the application with Add/Remove programs. FUSION_REFCOUNT_FILEPATH_GUID - The assembly is referenced by an application that is represented by a file in the file system. The szIdentifier field is the path to this file. FUSION_REFCOUNT_OPAQUE_STRING_GUID - The assembly is referenced by an application that is only represented by an opaque string. The szIdentifier is this opaque string. The GAC does not perform existence checking for opaque references when you remove this.

How can I shrink the drawable on a button?

You should use a ImageButton and specify the image in android:src, and set android:scaletype to fitXY


Setting scaled drawable in code

Drawable drawable = getResources().getDrawable(R.drawable.s_vit);
drawable.setBounds(0, 0, (int)(drawable.getIntrinsicWidth()*0.5), 
                         (int)(drawable.getIntrinsicHeight()*0.5));
ScaleDrawable sd = new ScaleDrawable(drawable, 0, scaleWidth, scaleHeight);
Button btn = findViewbyId(R.id.yourbtnID);
btn.setCompoundDrawables(sd.getDrawable(), null, null, null); //set drawableLeft for example

Vertical divider CSS

.headerDivider {
     border-left:1px solid #38546d; 
     border-right:1px solid #16222c; 
     height:80px;
     position:absolute;
     right:249px;
     top:10px; 
}

<div class="headerDivider"></div>

Styling input buttons for iPad and iPhone

I recently came across this problem myself.

<!--Instead of using input-->
<input type="submit"/>
<!--Use button-->
<button type="submit">
<!--You can then attach your custom CSS to the button-->

Hope that helps.

How to break out of nested loops?

for(int i = 0; i < 1000; i++) {
    for(int j = 0; j < 1000; i++) {
       if(condition) {
          func(para1, para2...);
          return;
       }
    }
}

func(para1, para2...) {
    stmt2;
}

Can't find AVD or SDK manager in Eclipse

Window -> Custom Perspective -> Command Groups Availability -> Android SDK and AVD Manager check it

Error CS1705: "which has a higher version than referenced assembly"

In my scenario, I edited the .csproj file for my dotnetCore app. I noticed that the TargetFramework tag had a value of netcoreapp2.1 and the RuntimeFrameworkVersion tag a value of 2.0.0. So I changed the RuntimeFrameworkVersion to 2.1.0, saved, restarted VS and rebuilt and then it resolved the errors.

Hope this will help you ...

Good Luck,

Sugeshan

Git push hangs when pushing to Github?

I just wanted to say that I'm having this issue on my AWS EC2 instances. I was trying to push from my EC2 instance itself, when I have it configured to only allow traffic in from the load balancer. I changed the rule to allow HTTP in from everywhere, but it still didn't fix the problem. Then I realized it's because my security groups are configured to not allow outbound traffic from my EC2 instances over HTTPS. I didn't have allow HTTPS inbound traffic to make it work, even though it's probably a good policy for you to have HTTPS available inbound.

Convert absolute path into relative path given a current directory using Bash

Using realpath from GNU coreutils 8.23 is the simplest, I think:

$ realpath --relative-to="$file1" "$file2"

For example:

$ realpath --relative-to=/usr/bin/nmap /tmp/testing
../../../tmp/testing

How to add a right button to a UINavigationController?

Why are you subclasses UINavigationController? There is no need to subclass it if all you need to do is add a button to it.

Set up a hierarchy with a UINavigationController at the top, and then in your root view controller's viewDidLoad: method: set up the button and attach it to the navigation item by calling

[[self navigationItem] setRightBarButtonItem:myBarButtonItem];

Writing a string to a cell in excel

I think you may be getting tripped up on the sheet protection. I streamlined your code a little and am explicitly setting references to the workbook and worksheet objects. In your example, you explicitly refer to the workbook and sheet when you're setting the TxtRng object, but not when you unprotect the sheet.

Try this:

Sub varchanger()

    Dim wb As Workbook
    Dim ws As Worksheet
    Dim TxtRng  As Range

    Set wb = ActiveWorkbook
    Set ws = wb.Sheets("Sheet1")
    'or ws.Unprotect Password:="yourpass"
    ws.Unprotect

    Set TxtRng = ws.Range("A1")
    TxtRng.Value = "SubTotal"
    'http://stackoverflow.com/questions/8253776/worksheet-protection-set-using-ws-protect-but-doesnt-unprotect-using-the-menu
    ' or ws.Protect Password:="yourpass"
    ws.Protect

End Sub

If I run the sub with ws.Unprotect commented out, I get a run-time error 1004. (Assuming I've protected the sheet and have the range locked.) Uncommenting the line allows the code to run fine.

NOTES:

  1. I'm re-setting sheet protection after writing to the range. I'm assuming you want to do this if you had the sheet protected in the first place. If you are re-setting protection later after further processing, you'll need to remove that line.
  2. I removed the error handler. The Excel error message gives you a lot more detail than Err.number. You can put it back in once you get your code working and display whatever you want. Obviously you can use Err.Description as well.
  3. The Cells(1, 1) notation can cause a huge amount of grief. Be careful using it. Range("A1") is a lot easier for humans to parse and tends to prevent forehead-slapping mistakes.

Javascript call() & apply() vs bind()?

I created this comparison between function objects, function calls, call/apply and bind a while ago:

enter image description here

.bind allows you to set the this value now while allowing you to execute the function in the future, because it returns a new function object.

How to change Visual Studio 2012,2013 or 2015 License Key?

The ISO is probably pre-pidded. You'll need to delete the key from the setup files. It should then ask you for a key during installation.

How to pass the button value into my onclick event function?

You can pass the element into the function <input type="button" value="mybutton1" onclick="dosomething(this)">test by passing this. Then in the function you can access the value like this:

function dosomething(element) {
  console.log(element.value);
}

How can I add (simple) tracing in C#?

I followed around five different answers as well as all the blog posts in the previous answers and still had problems. I was trying to add a listener to some existing code that was tracing using the TraceSource.TraceEvent(TraceEventType, Int32, String) method where the TraceSource object was initialised with a string making it a 'named source'.

For me the issue was not creating a valid combination of source and switch elements to target this source. Here is an example that will log to a file called tracelog.txt. For the following code:

TraceSource source = new TraceSource("sourceName");
source.TraceEvent(TraceEventType.Verbose, 1, "Trace message");

I successfully managed to log with the following diagnostics configuration:

<system.diagnostics>
    <sources>
        <source name="sourceName" switchName="switchName">
            <listeners>
                <add
                    name="textWriterTraceListener"
                    type="System.Diagnostics.TextWriterTraceListener"
                    initializeData="tracelog.txt" />
            </listeners>
        </source>
    </sources>

    <switches>
        <add name="switchName" value="Verbose" />
    </switches>
</system.diagnostics>

Current time formatting with Javascript

A JavaScript Date has several methods allowing you to extract its parts:

getFullYear() - Returns the 4-digit year
getMonth() - Returns a zero-based integer (0-11) representing the month of the year.
getDate() - Returns the day of the month (1-31).
getDay() - Returns the day of the week (0-6). 0 is Sunday, 6 is Saturday.
getHours() - Returns the hour of the day (0-23).
getMinutes() - Returns the minute (0-59).
getSeconds() - Returns the second (0-59).
getMilliseconds() - Returns the milliseconds (0-999).
getTimezoneOffset() - Returns the number of minutes between the machine local time and UTC.

There are no built-in methods allowing you to get localized strings like "Friday", "February", or "PM". You have to code that yourself. To get the string you want, you at least need to store string representations of days and months:

var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

Then, put it together using the methods above:

_x000D_
_x000D_
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];_x000D_
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];_x000D_
var d = new Date();_x000D_
var day = days[d.getDay()];_x000D_
var hr = d.getHours();_x000D_
var min = d.getMinutes();_x000D_
if (min < 10) {_x000D_
    min = "0" + min;_x000D_
}_x000D_
var ampm = "am";_x000D_
if( hr > 12 ) {_x000D_
    hr -= 12;_x000D_
    ampm = "pm";_x000D_
}_x000D_
var date = d.getDate();_x000D_
var month = months[d.getMonth()];_x000D_
var year = d.getFullYear();_x000D_
var x = document.getElementById("time");_x000D_
x.innerHTML = day + " " + hr + ":" + min + ampm + " " + date + " " + month + " " + year;
_x000D_
<span id="time"></span>
_x000D_
_x000D_
_x000D_

I have a date format function I like to include in my standard library. It takes a format string parameter that defines the desired output. The format strings are loosely based on .Net custom Date and Time format strings. For the format you specified the following format string would work: "dddd h:mmtt d MMM yyyy".

var d = new Date();
var x = document.getElementById("time");
x.innerHTML = formatDate(d, "dddd h:mmtt d MMM yyyy");

Demo: jsfiddle.net/BNkkB/1

Here is my full date formatting function:

function formatDate(date, format, utc) {
    var MMMM = ["\x00", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
    var MMM = ["\x01", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    var dddd = ["\x02", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
    var ddd = ["\x03", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];

    function ii(i, len) {
        var s = i + "";
        len = len || 2;
        while (s.length < len) s = "0" + s;
        return s;
    }

    var y = utc ? date.getUTCFullYear() : date.getFullYear();
    format = format.replace(/(^|[^\\])yyyy+/g, "$1" + y);
    format = format.replace(/(^|[^\\])yy/g, "$1" + y.toString().substr(2, 2));
    format = format.replace(/(^|[^\\])y/g, "$1" + y);

    var M = (utc ? date.getUTCMonth() : date.getMonth()) + 1;
    format = format.replace(/(^|[^\\])MMMM+/g, "$1" + MMMM[0]);
    format = format.replace(/(^|[^\\])MMM/g, "$1" + MMM[0]);
    format = format.replace(/(^|[^\\])MM/g, "$1" + ii(M));
    format = format.replace(/(^|[^\\])M/g, "$1" + M);

    var d = utc ? date.getUTCDate() : date.getDate();
    format = format.replace(/(^|[^\\])dddd+/g, "$1" + dddd[0]);
    format = format.replace(/(^|[^\\])ddd/g, "$1" + ddd[0]);
    format = format.replace(/(^|[^\\])dd/g, "$1" + ii(d));
    format = format.replace(/(^|[^\\])d/g, "$1" + d);

    var H = utc ? date.getUTCHours() : date.getHours();
    format = format.replace(/(^|[^\\])HH+/g, "$1" + ii(H));
    format = format.replace(/(^|[^\\])H/g, "$1" + H);

    var h = H > 12 ? H - 12 : H == 0 ? 12 : H;
    format = format.replace(/(^|[^\\])hh+/g, "$1" + ii(h));
    format = format.replace(/(^|[^\\])h/g, "$1" + h);

    var m = utc ? date.getUTCMinutes() : date.getMinutes();
    format = format.replace(/(^|[^\\])mm+/g, "$1" + ii(m));
    format = format.replace(/(^|[^\\])m/g, "$1" + m);

    var s = utc ? date.getUTCSeconds() : date.getSeconds();
    format = format.replace(/(^|[^\\])ss+/g, "$1" + ii(s));
    format = format.replace(/(^|[^\\])s/g, "$1" + s);

    var f = utc ? date.getUTCMilliseconds() : date.getMilliseconds();
    format = format.replace(/(^|[^\\])fff+/g, "$1" + ii(f, 3));
    f = Math.round(f / 10);
    format = format.replace(/(^|[^\\])ff/g, "$1" + ii(f));
    f = Math.round(f / 10);
    format = format.replace(/(^|[^\\])f/g, "$1" + f);

    var T = H < 12 ? "AM" : "PM";
    format = format.replace(/(^|[^\\])TT+/g, "$1" + T);
    format = format.replace(/(^|[^\\])T/g, "$1" + T.charAt(0));

    var t = T.toLowerCase();
    format = format.replace(/(^|[^\\])tt+/g, "$1" + t);
    format = format.replace(/(^|[^\\])t/g, "$1" + t.charAt(0));

    var tz = -date.getTimezoneOffset();
    var K = utc || !tz ? "Z" : tz > 0 ? "+" : "-";
    if (!utc) {
        tz = Math.abs(tz);
        var tzHrs = Math.floor(tz / 60);
        var tzMin = tz % 60;
        K += ii(tzHrs) + ":" + ii(tzMin);
    }
    format = format.replace(/(^|[^\\])K/g, "$1" + K);

    var day = (utc ? date.getUTCDay() : date.getDay()) + 1;
    format = format.replace(new RegExp(dddd[0], "g"), dddd[day]);
    format = format.replace(new RegExp(ddd[0], "g"), ddd[day]);

    format = format.replace(new RegExp(MMMM[0], "g"), MMMM[M]);
    format = format.replace(new RegExp(MMM[0], "g"), MMM[M]);

    format = format.replace(/\\(.)/g, "$1");

    return format;
};

What is MVC and what are the advantages of it?

It separates Model and View controlled by a Controller, As far as Model is concerned, Your Models has to follow OO architecture, future enhancements and other maintenance of the code base should be very easy and the code base should be reusable.

Same model can have any no.of views e.g) same info can be shown in as different graphical views. Same view can have different no.of models e.g) different detailed can be shown as a single graph say as a bar graph. This is what is re-usability of both View and Model.

Enhancements in views and other support of new technologies for building the view can be implemented easily.

Guy who is working on view dose not need to know about the underlying Model code base and its architecture, vise versa for the model.

Disabling browser caching for all browsers from ASP.NET

See also How to prevent google chrome from caching my inputs, esp hidden ones when user click back? without which Chrome might reload but preserve the previous content of <input> elements -- in other words, use autocomplete="off".

bad operand types for binary operator "&" java

Because & has a lesser priority than ==.

Your code is equivalent to a[0] & (1 == 0), and unless a[0] is a boolean this won't compile...

You need to:

(a[0] & 1) == 0

etc etc.

(yes, Java does hava a boolean & operator -- a non shortcut logical and)

How to schedule a stored procedure in MySQL

If you're open to out-of-the-DB solution: You could set up a cron job that runs a script that will itself call the procedure.

PHP cURL HTTP PUT

You have mixed 2 standard.

The error is in $header = "Content-Type: multipart/form-data; boundary='123456f'";

The function http_build_query($filedata) is only for "Content-Type: application/x-www-form-urlencoded", or none.