Programs & Examples On #Nsnetservicebrowser

How to set a default value with Html.TextBoxFor?

You can simply do :

<%= Html.TextBoxFor(x => x.Age, new { @Value = "0"}) %>

or better, this will switch to default value '0' if the model is null, for example if you have the same view for both editing and creating :

@Html.TextBoxFor(x => x.Age, new { @Value = (Model==null) ? "0" : Model.Age.ToString() })

How to recover stashed uncommitted changes

you can stash the uncommitted changes using "git stash" then checkout to a new branch using "git checkout -b " then apply the stashed commits "git stash apply"

Error ITMS-90717: "Invalid App Store Icon"

If you're facing this issue in Flutter then you're good to go here.

Issue is indicating you're using .png as image asset. Just try to replace .png to .jpg and build your project again..!!

Use this plugin. - flutter_launcher_icons: ^0.8.1

flutter_icons:
  android: "ic_launcher"
  image_path_android: "assets/logo_panda.jpg"
  ios: true
  image_path_ios: "assets/logo_panda.jpg"

Make sure you're using the .jpg image extension as the image path.

This help me to upload the app to the App Store.

Fatal error: Call to undefined function mb_strlen()

The function mb_strlen() is not enabled by default in PHP. Please read the manual for installation details:

http://www.php.net/manual/en/mbstring.installation.php

'^M' character at end of lines

Try using dos2unix to strip off the ^M.

How do you kill a Thread in Java?

Generally you don't..

You ask it to interrupt whatever it is doing using Thread.interrupt() (javadoc link)

A good explanation of why is in the javadoc here (java technote link)

How do I remove the passphrase for the SSH key without having to create a new key?

Short answer:

$ ssh-keygen -p

This will then prompt you to enter the keyfile location, the old passphrase, and the new passphrase (which can be left blank to have no passphrase).


If you would like to do it all on one line without prompts do:

$ ssh-keygen -p [-P old_passphrase] [-N new_passphrase] [-f keyfile]

Important: Beware that when executing commands they will typically be logged in your ~/.bash_history file (or similar) in plain text including all arguments provided (i.e. the passphrases in this case). It is, therefore, is recommended that you use the first option unless you have a specific reason to do otherwise.

Notice though that you can still use -f keyfile without having to specify -P nor -N, and that the keyfile defaults to ~/.ssh/id_rsa, so in many cases, it's not even needed.

You might want to consider using ssh-agent, which can cache the passphrase for a time. The latest versions of gpg-agent also support the protocol that is used by ssh-agent.

CURL Command Line URL Parameters

The application/x-www-form-urlencoded Content-type header is not needed. Unless the request handler expects the parameters coming from request body. Try it out:

curl -X DELETE "http://localhost:5000/locations?id=3"

or

curl -X GET "http://localhost:5000/locations?id=3"

Changing variable names with Python for loops

Use a list.

groups = [0]*3
for i in xrange(3):
    groups[i] = self.getGroup(selected, header + i)

or more "Pythonically":

groups = [self.getGroup(selected, header + i) for i in xrange(3)]

For what it's worth, you could try to create variables the "wrong" way, i.e. by modifying the dictionary which holds their values:

l = locals()
for i in xrange(3):
    l['group' + str(i)] = self.getGroup(selected, header + i)

but that's really bad form, and possibly not even guaranteed to work.

List columns with indexes in PostgreSQL

@cope360 's excellent answer, converted to use join syntax.

select t.relname as table_name
     , i.relname as index_name
     , array_to_string(array_agg(a.attname), ', ') as column_names
from pg_class t
join pg_index ix
on t.oid = ix.indrelid
join pg_class i
on i.oid = ix.indexrelid
join pg_attribute a
on a.attrelid = t.oid
and a.attnum = ANY(ix.indkey)
where t.relkind = 'r'
and t.relname like 'test%'
group by t.relname
       , i.relname
order by t.relname
       , i.relname
;

How to allocate aligned memory only using the standard library?

I'm surprised noone's voted up Shao's answer that, as I understand it, it is impossible to do what's asked in standard C99, since converting a pointer to an integral type formally is undefined behavior. (Apart from the standard allowing conversion of uintptr_t <-> void*, but the standard does not seem to allow doing any manipulations of the uintptr_t value and then converting it back.)

git returns http error 407 from proxy after CONNECT

Your password seems to be incorrect. Recheck your credentials.

Calculating Time Difference

Here is a piece of code to do so:

def(StringChallenge(str1)):

#str1 = str1[1:-1]
h1 = 0
h2 = 0
m1 = 0
m2 = 0

def time_dif(h1,m1,h2,m2):
    if(h1 == h2):
        return m2-m1
    else:
        return ((h2-h1-1)*60 + (60-m1) + m2)
count_min = 0

if str1[1] == ':':
    h1=int(str1[:1])
    m1=int(str1[2:4])
else:
    h1=int(str1[:2])
    m1=int(str1[3:5])

if str1[-7] == '-':
    h2=int(str1[-6])
    m2=int(str1[-4:-2])
else:
    h2=int(str1[-7:-5])
    m2=int(str1[-4:-2])

if h1 == 12:
    h1 = 0
if h2 == 12:
    h2 = 0

if "am" in str1[:8]:
    flag1 = 0
else:
    flag1= 1

if "am" in str1[7:]:
    flag2 = 0
else:
    flag2 = 1

if flag1 == flag2:
    if h2 > h1 or (h2 == h1 and m2 >= m1):
        count_min += time_dif(h1,m1,h2,m2)
    else:
        count_min += 1440 - time_dif(h2,m2,h1,m1)
else:
    count_min += (12-h1-1)*60
    count_min += (60 - m1)
    count_min += (h2*60)+m2


return count_min

How to compare two JSON have the same properties without order?

This code will verify the json independently of param object order.

_x000D_
_x000D_
var isEqualsJson = (obj1,obj2)=>{
    keys1 = Object.keys(obj1);
    keys2 = Object.keys(obj2);

    //return true when the two json has same length and all the properties has same value key by key
    return keys1.length === keys2.length && Object.keys(obj1).every(key=>obj1[key]==obj2[key]);
}

var obj1 = {a:1,b:2,c:3};
var obj2 = {a:1,b:2,c:3}; 

console.log("json is equals: "+ isEqualsJson(obj1,obj2));
alert("json is equals: "+ isEqualsJson(obj1,obj2));
_x000D_
_x000D_
_x000D_

What's the difference between import java.util.*; and import java.util.Date; ?

You probably have some other "Date" class imported somewhere (or you have a Date class in you package, which does not need to be imported). With "import java.util.*" you are using the "other" Date. In this case it's best to explicitly specify java.util.Date in the code.

Or better, try to avoid naming your classes "Date".

SQL Server format decimal places with commas

From a related SO question: Format a number with commas but without decimals in SQL Server 2008 R2?

SELECT CONVERT(varchar, CAST(1112 AS money), 1)

This was tested in SQL Server 2008 R2.

iPhone get SSID without private library

As of iOS 7 or 8, you can do this (need Entitlement for iOS 12+ as shown below):

@import SystemConfiguration.CaptiveNetwork;

/** Returns first non-empty SSID network info dictionary.
 *  @see CNCopyCurrentNetworkInfo */
- (NSDictionary *)fetchSSIDInfo {
    NSArray *interfaceNames = CFBridgingRelease(CNCopySupportedInterfaces());
    NSLog(@"%s: Supported interfaces: %@", __func__, interfaceNames);

    NSDictionary *SSIDInfo;
    for (NSString *interfaceName in interfaceNames) {
        SSIDInfo = CFBridgingRelease(
            CNCopyCurrentNetworkInfo((__bridge CFStringRef)interfaceName));
        NSLog(@"%s: %@ => %@", __func__, interfaceName, SSIDInfo);

        BOOL isNotEmpty = (SSIDInfo.count > 0);
        if (isNotEmpty) {
            break;
        }
    }
    return SSIDInfo;
}

Example output:

2011-03-04 15:32:00.669 ShowSSID[4857:307] -[ShowSSIDAppDelegate fetchSSIDInfo]: Supported interfaces: (
    en0
)
2011-03-04 15:32:00.693 ShowSSID[4857:307] -[ShowSSIDAppDelegate fetchSSIDInfo]: en0 => {
    BSSID = "ca:fe:ca:fe:ca:fe";
    SSID = XXXX;
    SSIDDATA = <01234567 01234567 01234567>;
}

Note that no ifs are supported on the simulator. Test on your device.

iOS 12

You must enable access wifi info from capabilities.

Important To use this function in iOS 12 and later, enable the Access WiFi Information capability for your app in Xcode. When you enable this capability, Xcode automatically adds the Access WiFi Information entitlement to your entitlements file and App ID. Documentation link

Swift 4.2

func getConnectedWifiInfo() -> [AnyHashable: Any]? {

    if let ifs = CFBridgingRetain( CNCopySupportedInterfaces()) as? [String],
        let ifName = ifs.first as CFString?,
        let info = CFBridgingRetain( CNCopyCurrentNetworkInfo((ifName))) as? [AnyHashable: Any] {

        return info
    }
    return nil

}

How to focus on a form input text field on page load using jQuery?

The Simple and easiest way to achieve this

$('#button').on('click', function () {
    $('.form-group input[type="text"]').attr('autofocus', 'true');
});

Creating a recursive method for Palindrome

Try this:

package javaapplicationtest;

public class Main {

    public static void main(String[] args) {

        String source = "mango";
        boolean isPalindrome = true;

        //looping through the string and checking char by char from reverse
        for(int loop = 0; loop < source.length(); loop++){          
            if( source.charAt(loop) != source.charAt(source.length()-loop-1)){
                isPalindrome = false;
                break;
            }
        }

         if(isPalindrome == false){
             System.out.println("Not a palindrome");
         }
         else
             System.out.println("Pailndrome");

    }

}

img tag displays wrong orientation

It's the EXIF data that your Samsung phone incorporates.

CSS display:inline property with list-style-image: property on <li> tags

Try using float: left (or right) instead of display: inline. Inline display replaces list-item display, which is what adds the bullet points.

How to tell whether a point is to the right or left side of a line

A(x1,y1) B(x2,y2) a line segment with length L=sqrt( (y2-y1)^2 + (x2-x1)^2 )

and a point M(x,y)

making a transformation of coordinates in order to be the point A the new start and B a point of the new X axis

we have the new coordinates of the point M

which are newX = ((x-x1)(x2-x1)+(y-y1)(y2-y1)) / L
from (x-x1)*cos(t)+(y-y1)*sin(t) where cos(t)=(x2-x1)/L, sin(t)=(y2-y1)/L

newY = ((y-y1)(x2-x1)-(x-x1)(y2-y1)) / L
from (y-y1)*cos(t)-(x-x1)*sin(t)

because "left" is the side of axis X where the Y is positive, if the newY (which is the distance of M from AB) is positive, then it is on the left side of AB (the new X axis) You may omit the division by L (allways positive), if you only want the sign

Finding duplicate values in MySQL

As a variation on Levik's answer that allows you to find also the ids of the duplicate results, I used the following:

SELECT * FROM table1 WHERE column1 IN (SELECT column1 AS duplicate_value FROM table1 GROUP BY column1 HAVING COUNT(*) > 1)

Can't draw Histogram, 'x' must be numeric

Use the dec argument to set "," as the decimal point by adding:

 ce <- read.table("file.txt", header = TRUE, dec = ",")

jQuery check if it is clicked or not

You could use .data():

$("#element").click(function(){
    $(this).data('clicked', true);
});

and then check it with:

if($('#element').data('clicked')) {
    alert('yes');
}

To get a better answer you need to provide more information.

Update:

Based on your comment, I understand you want something like:

$("#element").click(function(){
    var $this = $(this);
    if($this.data('clicked')) {
        func(some, other, parameters);
    }
    else {
        $this.data('clicked', true);
        func(some, parameter);
    }
});

How to get the date from jQuery UI datepicker

Try this, works like charm, gives the date you have selected. onsubmit form try to get this value:-

var date = $("#scheduleDate").datepicker({ dateFormat: 'dd,MM,yyyy' }).val();

Reference here

How to stop/cancel 'git log' command in terminal?

You can hit the key q (for quit) and it should take you to the prompt.

Please see this link.

How to delete all files older than 3 days when "Argument list too long"?

Another solution for the original question, esp. useful if you want to remove only SOME of the older files in a folder, would be smth like this:

find . -name "*.sess" -mtime +100 

and so on.. Quotes block shell wildcards, thus allowing you to "find" millions of files :)

Chrome Dev Tools - Modify javascript and reload

Yes, just open the "Source" Tab in the dev-tools and navigate to the script you want to change . Make your adjustments directly in the dev tools window and then hit ctrl+s to save the script - know the new js will be used until you refresh the whole page.

Resize a large bitmap file to scaled output file on Android

Why not use the API?

int h = 48; // height in pixels
int w = 48; // width in pixels    
Bitmap scaled = Bitmap.createScaledBitmap(largeBitmap, w, h, true);

mysqli or PDO - what are the pros and cons?

Personally I use PDO, but I think that is mainly a question of preference.

PDO has some features that help agains SQL injection (prepared statements), but if you are careful with your SQL you can achieve that with mysqli, too.

Moving to another database is not so much a reason to use PDO. As long as you don't use "special SQL features", you can switch from one DB to another. However as soon as you use for example "SELECT ... LIMIT 1" you can't go to MS-SQL where it is "SELECT TOP 1 ...". So this is problematic anyway.

Get current url in Angular

You can make use of location service available in @angular/common and via this below code you can get the location or current URL

import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Router } from '@angular/router';

@Component({
  selector: 'app-top-nav',
  templateUrl: './top-nav.component.html',
  styleUrls: ['./top-nav.component.scss']
})
export class TopNavComponent implements OnInit {

  route: string;

  constructor(location: Location, router: Router) {
    router.events.subscribe((val) => {
      if(location.path() != ''){
        this.route = location.path();
      } else {
        this.route = 'Home'
      }
    });
  }

  ngOnInit() {
  }

}

here is the reference link from where I have copied thing to get location for my project. https://github.com/elliotforbes/angular-2-admin/blob/master/src/app/common/top-nav/top-nav.component.ts

Call a REST API in PHP

You will need to know if the REST API you are calling supports GET or POST, or both methods. The code below is something that works for me, I'm calling my own web service API, so I already know what the API takes and what it will return. It supports both GET and POST methods, so the less sensitive info goes into the URL (GET), and the info like username and password is submitted as POST variables. Also, everything goes over the HTTPS connection.

Inside the API code, I encode an array I want to return into json format, then simply use PHP command echo $my_json_variable to make that json string availabe to the client.

So as you can see, my API returns json data, but you need to know (or look at the returned data to find out) what format the response from the API is in.

This is how I connect to the API from the client side:

$processed = FALSE;
$ERROR_MESSAGE = '';

// ************* Call API:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.myapi.com/api.php?format=json&action=subscribe&email=" . $email_to_subscribe);
curl_setopt($ch, CURLOPT_POST, 1);// set post data to true
curl_setopt($ch, CURLOPT_POSTFIELDS,"username=myname&password=mypass");   // post data
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$json = curl_exec($ch);
curl_close ($ch);

// returned json string will look like this: {"code":1,"data":"OK"}
// "code" may contain an error code and "data" may contain error string instead of "OK"
$obj = json_decode($json);

if ($obj->{'code'} == '1')
{
  $processed = TRUE;
}else{
  $ERROR_MESSAGE = $obj->{'data'};
}

...

if (!$processed && $ERROR_MESSAGE != '') {
    echo $ERROR_MESSAGE;
}

BTW, I also tried to use file_get_contents() method as some of the users here suggested, but that din't work well for me. I found out the curl method to be faster and more reliable.

How to handle query parameters in angular 2

(For Childs Route Only such as /hello-world)

In the case you would like to make this kind of call :

/hello-world?foo=bar&fruit=banana

Angular2 doesn't use ? nor & but ; instead. So the correct URL should be :

/hello-world;foo=bar;fruit=banana

And to get those data :

import { Router, ActivatedRoute, Params } from '@angular/router';

private foo: string;
private fruit: string;

constructor(
  private route: ActivatedRoute,
  private router: Router
  ) {}

ngOnInit() {
  this.route.params.forEach((params: Params) => {
      this.foo = params['foo'];
      this.fruit = params['fruit'];
  });
  console.log(this.foo, this.fruit); // you should get your parameters here
}

Source : https://angular.io/docs/ts/latest/guide/router.html

Find unused npm packages in package.json

if you want to choose upon which giant's shoulders you will stand

here is a link to generate a short list of options available to npm; it filters on the keywords unused packages

https://www.npmjs.com/search?q=unused%20packages

How to automatically update an application without ClickOnce?

There are a lot of questions already about this, so I will refer you to those.

One thing you want to make sure to prevent the need for uninstallation, is that you use the same upgrade code on every release, but change the product code. These values are located in the Installshield project properties.

Some references:

How to iterate through LinkedHashMap with lists as values

In Java 8:

Map<String, List<String>> test1 = new LinkedHashMap<String, List<String>>();
test1.forEach((key,value) -> {
    System.out.println(key + " -> " + value);
});

How do you add a timer to a C# console application

You can also use your own timing mechanisms if you want a little more control, but possibly less accuracy and more code/complexity, but I would still recommend a timer. Use this though if you need to have control over the actual timing thread:

private void ThreadLoop(object callback)
{
    while(true)
    {
        ((Delegate) callback).DynamicInvoke(null);
        Thread.Sleep(5000);
    }
}

would be your timing thread(modify this to stop when reqiuired, and at whatever time interval you want).

and to use/start you can do:

Thread t = new Thread(new ParameterizedThreadStart(ThreadLoop));

t.Start((Action)CallBack);

Callback is your void parameterless method that you want called at each interval. For example:

private void CallBack()
{
    //Do Something.
}

How do I find the last column with data?

I think we can modify the UsedRange code from @Readify's answer above to get the last used column even if the starting columns are blank or not.

So this lColumn = ws.UsedRange.Columns.Count modified to

this lColumn = ws.UsedRange.Column + ws.UsedRange.Columns.Count - 1 will give reliable results always

enter image description here

?Sheet1.UsedRange.Column + Sheet1.UsedRange.Columns.Count - 1

Above line Yields 9 in the immediate window.

Dynamically Add C# Properties at Runtime

Have you taken a look at ExpandoObject?

see: http://blogs.msdn.com/b/csharpfaq/archive/2009/10/01/dynamic-in-c-4-0-introducing-the-expandoobject.aspx

From MSDN:

The ExpandoObject class enables you to add and delete members of its instances at run time and also to set and get values of these members. This class supports dynamic binding, which enables you to use standard syntax like sampleObject.sampleMember instead of more complex syntax like sampleObject.GetAttribute("sampleMember").

Allowing you to do cool things like:

dynamic dynObject = new ExpandoObject();
dynObject.SomeDynamicProperty = "Hello!";
dynObject.SomeDynamicAction = (msg) =>
    {
        Console.WriteLine(msg);
    };

dynObject.SomeDynamicAction(dynObject.SomeDynamicProperty);

Based on your actual code you may be more interested in:

public static dynamic GetDynamicObject(Dictionary<string, object> properties)
{
    return new MyDynObject(properties);
}

public sealed class MyDynObject : DynamicObject
{
    private readonly Dictionary<string, object> _properties;

    public MyDynObject(Dictionary<string, object> properties)
    {
        _properties = properties;
    }

    public override IEnumerable<string> GetDynamicMemberNames()
    {
        return _properties.Keys;
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        if (_properties.ContainsKey(binder.Name))
        {
            result = _properties[binder.Name];
            return true;
        }
        else
        {
            result = null;
            return false;
        }
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        if (_properties.ContainsKey(binder.Name))
        {
            _properties[binder.Name] = value;
            return true;
        }
        else
        {
            return false;
        }
    }
}

That way you just need:

var dyn = GetDynamicObject(new Dictionary<string, object>()
    {
        {"prop1", 12},
    });

Console.WriteLine(dyn.prop1);
dyn.prop1 = 150;

Deriving from DynamicObject allows you to come up with your own strategy for handling these dynamic member requests, beware there be monsters here: the compiler will not be able to verify a lot of your dynamic calls and you won't get intellisense, so just keep that in mind.

List vs tuple, when to use each?

But if I am the one who designs the API and gets to choose the data types, then what are the guidelines?

For input parameters it's best to accept the most generic interface that does what you need. It is seldom just a tuple or list - more often it's sequence, sliceable or even iterable. Python's duck typing usually gets it for free, unless you explicitly check input types. Don't do that unless absolutely unavoidable.

For the data that you produce (output parameters) just return what's most convenient for you, e.g. return whatever datatype you keep or whatever your helper function returns.

One thing to keep in mind is to avoid returning a list (or any other mutable) that's part of your state, e.g.

class ThingsKeeper
    def __init__(self):
        self.__things = []

    def things(self):
        return self.__things  #outside objects can now modify your state

    def safer(self):
        return self.__things[:]  #it's copy-on-write, shouldn't hurt performance

JQuery show and hide div on mouse click (animate)

Try this:

<script type="text/javascript">
$.fn.toggleFuncs = function() {
    var functions = Array.prototype.slice.call(arguments),
    _this = this.click(function(){
        var i = _this.data('func_count') || 0;
        functions[i%functions.length]();
        _this.data('func_count', i+1);
    });
}
$('$showmenu').toggleFuncs(
        function() {
           $( ".menu" ).toggle( "drop" );
            },
            function() {
                $( ".menu" ).toggle( "drop" );
            }
); 

</script>

First fuction is an alternative to JQuery deprecated toggle :) . Works good with JQuery 2.0.3 and JQuery UI 1.10.3

Split string by single spaces

You can even develop your own split function (I know, little old-fashioned):

size_t split(const std::string &txt, std::vector<std::string> &strs, char ch)
{
    size_t pos = txt.find( ch );
    size_t initialPos = 0;
    strs.clear();

    // Decompose statement
    while( pos != std::string::npos ) {
        strs.push_back( txt.substr( initialPos, pos - initialPos ) );
        initialPos = pos + 1;

        pos = txt.find( ch, initialPos );
    }

    // Add the last one
    strs.push_back( txt.substr( initialPos, std::min( pos, txt.size() ) - initialPos + 1 ) );

    return strs.size();
}

Then you just need to invoke it with a vector<string> as argument:

int main()
{
    std::vector<std::string> v;

    split( "This  is a  test", v, ' ' );
    dump( cout, v );

    return 0;
}

Find the code for splitting a string in IDEone.

Hope this helps.

Java GUI frameworks. What to choose? Swing, SWT, AWT, SwingX, JGoodies, JavaFX, Apache Pivot?

I've been quite happy with Swing for the desktop applications I've been involved in. However, I do share your view on Swing not offering advanced components. What I've done in these cases is to go for JIDE. It's not free, but not that pricey either and it gives you a whole lot more tools under your belt. Specifically, they do offer a filterable TreeTable.

Remove the last line from a file in Bash

Ruby(1.9+)

ruby -ne 'BEGIN{prv=""};print prv ; prv=$_;' file

ArrayBuffer to base64 encoded string

You can derive a normal array from the ArrayBuffer by using Array.prototype.slice. Use a function like Array.prototype.map to convert bytes in to characters and join them together to forma string.

function arrayBufferToBase64(ab){

    var dView = new Uint8Array(ab);   //Get a byte view        

    var arr = Array.prototype.slice.call(dView); //Create a normal array        

    var arr1 = arr.map(function(item){        
      return String.fromCharCode(item);    //Convert
    });

    return window.btoa(arr1.join(''));   //Form a string

}

This method is faster since there are no string concatenations running in it.

MySQL table is marked as crashed and last (automatic?) repair failed

I tried the options in the existing answers, mainly the one marked correct which did not work in my scenario. However, what did work was using phpMyAdmin. Select the database and then select the table, from the bottom drop down menu select "Repair table".

  • Server type: MySQL
  • Server version: 5.7.23 - MySQL Community Server (GPL)
  • phpMyAdmin: Version information: 4.7.7

When should I use the new keyword in C++?

Method 1 (using new)

  • Allocates memory for the object on the free store (This is frequently the same thing as the heap)
  • Requires you to explicitly delete your object later. (If you don't delete it, you could create a memory leak)
  • Memory stays allocated until you delete it. (i.e. you could return an object that you created using new)
  • The example in the question will leak memory unless the pointer is deleted; and it should always be deleted, regardless of which control path is taken, or if exceptions are thrown.

Method 2 (not using new)

  • Allocates memory for the object on the stack (where all local variables go) There is generally less memory available for the stack; if you allocate too many objects, you risk stack overflow.
  • You won't need to delete it later.
  • Memory is no longer allocated when it goes out of scope. (i.e. you shouldn't return a pointer to an object on the stack)

As far as which one to use; you choose the method that works best for you, given the above constraints.

Some easy cases:

  • If you don't want to worry about calling delete, (and the potential to cause memory leaks) you shouldn't use new.
  • If you'd like to return a pointer to your object from a function, you must use new

String formatting: % vs. .format vs. string literal

As I discovered today, the old way of formatting strings via % doesn't support Decimal, Python's module for decimal fixed point and floating point arithmetic, out of the box.

Example (using Python 3.3.5):

#!/usr/bin/env python3

from decimal import *

getcontext().prec = 50
d = Decimal('3.12375239e-24') # no magic number, I rather produced it by banging my head on my keyboard

print('%.50f' % d)
print('{0:.50f}'.format(d))

Output:

0.00000000000000000000000312375239000000009907464850 0.00000000000000000000000312375239000000000000000000

There surely might be work-arounds but you still might consider using the format() method right away.

There is an error in XML document (1, 41)

I had the same thing. All came down to a "d" instead of a "D" in a tag name in the schema.

Insert php variable in a href

in php

echo '<a href="' . $folder_path . '">Link text</a>';

or

<a href="<?=$folder_path?>">Link text</a>;

or

<a href="<?php echo $folder_path ?>">Link text</a>;

What GRANT USAGE ON SCHEMA exactly do?

Well, this is my final solution for a simple db, for Linux:

# Read this before!
#
# * roles in postgres are users, and can be used also as group of users
# * $ROLE_LOCAL will be the user that access the db for maintenance and
#   administration. $ROLE_REMOTE will be the user that access the db from the webapp
# * you have to change '$ROLE_LOCAL', '$ROLE_REMOTE' and '$DB'
#   strings with your desired names
# * it's preferable that $ROLE_LOCAL == $DB

#-------------------------------------------------------------------------------

//----------- SKIP THIS PART UNTIL POSTGRES JDBC ADDS SCRAM - START ----------//

cd /etc/postgresql/$VERSION/main
sudo cp pg_hba.conf pg_hba.conf_bak
sudo -e pg_hba.conf

# change all `md5` with `scram-sha-256`
# save and exit

//------------ SKIP THIS PART UNTIL POSTGRES JDBC ADDS SCRAM - END -----------//

sudo -u postgres psql

# in psql:
create role $ROLE_LOCAL login createdb;
\password $ROLE_LOCAL
create role $ROLE_REMOTE login;
\password $ROLE_REMOTE

create database $DB owner $ROLE_LOCAL encoding "utf8";
\connect $DB $ROLE_LOCAL

# Create all tables and objects, and after that:

\connect $DB postgres

revoke connect on database $DB from public;
revoke all on schema public from public;
revoke all on all tables in schema public from public;

grant connect on database $DB to $ROLE_LOCAL;
grant all on schema public to $ROLE_LOCAL;
grant all on all tables in schema public to $ROLE_LOCAL;
grant all on all sequences in schema public to $ROLE_LOCAL;
grant all on all functions in schema public to $ROLE_LOCAL;

grant connect on database $DB to $ROLE_REMOTE;
grant usage on schema public to $ROLE_REMOTE;
grant select, insert, update, delete on all tables in schema public to $ROLE_REMOTE;
grant usage, select on all sequences in schema public to $ROLE_REMOTE;
grant execute on all functions in schema public to $ROLE_REMOTE;

alter default privileges for role $ROLE_LOCAL in schema public
    grant all on tables to $ROLE_LOCAL;

alter default privileges for role $ROLE_LOCAL in schema public
    grant all on sequences to $ROLE_LOCAL;

alter default privileges for role $ROLE_LOCAL in schema public
    grant all on functions to $ROLE_LOCAL;

alter default privileges for role $ROLE_REMOTE in schema public
    grant select, insert, update, delete on tables to $ROLE_REMOTE;

alter default privileges for role $ROLE_REMOTE in schema public
    grant usage, select on sequences to $ROLE_REMOTE;

alter default privileges for role $ROLE_REMOTE in schema public
    grant execute on functions to $ROLE_REMOTE;

# CTRL+D

How to make nginx to listen to server_name:port

The server_namedocs directive is used to identify virtual hosts, they're not used to set the binding.

netstat tells you that nginx listens on 0.0.0.0:80 which means that it will accept connections from any IP.

If you want to change the IP nginx binds on, you have to change the listendocs rule.
So, if you want to set nginx to bind to localhost, you'd change that to:

listen 127.0.0.1:80;

In this way, requests that are not coming from localhost are discarded (they don't even hit nginx).

What is The difference between ListBox and ListView

Listview derives from listbox control. One most important difference is listview uses the extended selection mode by default . listview also adds a property called view which enables you to customize the view in a richer way than a custom itemspanel. One real life example of listview with gridview is file explorer's details view. Listview with grid view is a less powerful data grid. After the introduction of datagrid control listview lost its importance.

How make background image on newsletter in outlook?

The only way I was able to do this is via this code (TD tables). I tested in outlook client 2010. I also tested via webmail client and it worked for both.

The only things you have to do is change your_image.jpg (there are two instances of this for the same image make sure you update both for your code) and #your_color.

<td bgcolor="#your_color" background="your_image.jpg">

<!--[if gte mso 9]>

<v:image xmlns:v="urn:schemas-microsoft-com:vml" id="theImage" style='behavior: url(#default#VML); display:inline-block; position:absolute; height:300px; width:600px; top:0; left:0; border:0; z-index:1;' src="your_image.jpg"/>

<v:shape xmlns:v="urn:schemas-microsoft-com:vml" id="theText" style='behavior: url(#default#VML); display:inline-block; position:absolute; height:300px; width:600px; top:-5; left:-10; border:0; z-index:2;'>

<![endif]-->

<p>Text over background image.</p>

<!--[if gte mso 9]>

</v:shape>

<![endif]-->

</td>

source

Skip Git commit hooks

From man githooks:

pre-commit
This hook is invoked by git commit, and can be bypassed with --no-verify option. It takes no parameter, and is invoked before obtaining the proposed commit log message and making a commit. Exiting with non-zero status from this script causes the git commit to abort.

Append text to textarea with javascript

Give this a try:

<!DOCTYPE html>
<html>
<head>
    <title>List Test</title>
    <style>
        li:hover {
            cursor: hand; cursor: pointer;
        }
    </style>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("li").click(function(){
                $('#alltext').append($(this).text());
            });
        });
    </script>
</head>
<body>

    <h2>List items</h2>
    <ol>
        <li>Hello</li>
        <li>World</li>
        <li>Earthlings</li>
    </ol>
    <form>
        <textarea id="alltext"></textarea>
    </form>

</body>
</html>

HTML5 Audio stop function

From my own javascript function to toggle Play/Pause - since I'm handling a radio stream, I wanted it to clear the buffer so that the listener does not end up coming out of sync with the radio station.

function playStream() {

        var player = document.getElementById('player');

        (player.paused == true) ? toggle(0) : toggle(1);

}

function toggle(state) {

        var player = document.getElementById('player');
        var link = document.getElementById('radio-link');
        var src = "http://192.81.248.91:8159/;";

        switch(state) {
                case 0:
                        player.src = src;
                        player.load();
                        player.play();
                        link.innerHTML = 'Pause';
                        player_state = 1;
                        break;
                case 1:
                        player.pause();
                        player.currentTime = 0;
                        player.src = '';
                        link.innerHTML = 'Play';
                        player_state = 0;
                        break;
        }
}

Turns out, just clearing the currentTime doesn't cut it under Chrome, needed to clear the source too and load it back in. Hope this helps.

android - listview get item view by position

You can get only visible View from ListView because row views in ListView are reuseable. If you use mListView.getChildAt(0) you get first visible view. This view is associated with item from adapter at position mListView.getFirstVisiblePosition().

How to split large text file in windows?

If you have installed Git for Windows, you should have Git Bash installed, since that comes with Git.

Use the split command in Git Bash to split a file:

  • into files of size 500MB each: split myLargeFile.txt -b 500m

  • into files with 10000 lines each: split myLargeFile.txt -l 10000

Tips:

  • If you don't have Git/Git Bash, download at https://git-scm.com/download

  • If you lost the shortcut to Git Bash, you can run it using C:\Program Files\Git\git-bash.exe

That's it!


I always like examples though...

Example:

enter image description here

You can see in this image that the files generated by split are named xaa, xab, xac, etc.

These names are made up of a prefix and a suffix, which you can specify. Since I didn't specify what I want the prefix or suffix to look like, the prefix defaulted to x, and the suffix defaulted to a two-character alphabetical enumeration.

Another Example:

This example demonstrates

  • using a filename prefix of MySlice (instead of the default x),
  • the -d flag for using numerical suffixes (instead of aa, ab, ac, etc...),
  • and the option -a 5 to tell it I want the suffixes to be 5 digits long:

enter image description here

How can I force component to re-render with hooks in React?

Generally, you can use any state handling approach you want to trigger an update.

With TypeScript

codesandbox example

useState

const forceUpdate: () => void = React.useState()[1].bind(null, {})  // see NOTE below

useReducer

const forceUpdate = React.useReducer(() => ({}), {})[1] as () => void

as custom hook

Just wrap whatever approach you prefer like this

function useForceUpdate(): () => void {
  return React.useReducer(() => ({}), {})[1] as () => void // <- paste here
}

How this works?

"To trigger an update" means to tell React engine that some value has changed and that it should rerender your component.

[, setState] from useState() requires a parameter. We get rid of it by binding a fresh object {}.
() => ({}) in useReducer is a dummy reducer that returns a fresh object each time an action is dispatched.
{} (fresh object) is required so that it triggers an update by changing a reference in the state.

PS: useState just wraps useReducer internally. source

NOTE: Using .bind with useState causes a change in function reference between renders. It is possible to wrap it inside useCallback as already explained here, but then it wouldn't be a sexy one-liner™. The Reducer version already keeps reference equality between renders. This is important if you want to pass the forceUpdate function in props.

plain JS

const forceUpdate = React.useState()[1].bind(null, {})  // see NOTE above
const forceUpdate = React.useReducer(() => ({}))[1]

how to add new <li> to <ul> onclick with javascript

You have not appended your li as a child to your ul element

Try this

function function1() {
  var ul = document.getElementById("list");
  var li = document.createElement("li");
  li.appendChild(document.createTextNode("Four"));
  ul.appendChild(li);
}

If you need to set the id , you can do so by

li.setAttribute("id", "element4");

Which turns the function into

function function1() {
  var ul = document.getElementById("list");
  var li = document.createElement("li");
  li.appendChild(document.createTextNode("Four"));
  li.setAttribute("id", "element4"); // added line
  ul.appendChild(li);
  alert(li.id);
}

swift How to remove optional String Character

when you define any variable as a optional then you need to unwrap that optional value.Convert ? to !

Command to get nth line of STDOUT

Another poster suggested

ls -l | head -2 | tail -1

but if you pipe head into tail, it looks like everything up to line N is processed twice.

Piping tail into head

ls -l | tail -n +2 | head -n1

would be more efficient?

Edit Crystal report file without Crystal Report software

If this is something you are only going to need to do once, have you considered downloading a demo version of Crystal? There's a 30-day trial version available here: http://www.developers.net/businessobjectsshowcase/view/3154

Of course, if you need to edit these files after the 30 day period is over, you would be better off buying Crystal.

Alternatively, if all you need to do is replace a few static literal words, have you tried doing a search and replace in a text editor? (Don't forget to save the original files somewhere safe first!)

jQuery override default validation error message display (Css) Popup/Tooltip like

You can use the errorPlacement option to override the error message display with little css. Because css on its own will not be enough to produce the effect you need.

$(document).ready(function(){
    $("#myForm").validate({
        rules: {
            "elem.1": {
                required: true,
                digits: true
            },
            "elem.2": {
                required: true
            }
        },
        errorElement: "div",
        wrapper: "div",  // a wrapper around the error message
        errorPlacement: function(error, element) {
            offset = element.offset();
            error.insertBefore(element)
            error.addClass('message');  // add a class to the wrapper
            error.css('position', 'absolute');
            error.css('left', offset.left + element.outerWidth());
            error.css('top', offset.top);
        }

    });
});

You can play with the left and top css attributes to show the error message on top, left, right or bottom of the element. For example to show the error on the top:

    errorPlacement: function(error, element) {
        element.before(error);
        offset = element.offset();
        error.css('left', offset.left);
        error.css('top', offset.top - element.outerHeight());
    }

And so on. You can refer to jQuery documentation about css for more options.

Here is the css I used. The result looks exactly like the one you want. With as little CSS as possible:

div.message{
    background: transparent url(msg_arrow.gif) no-repeat scroll left center;
    padding-left: 7px;
}

div.error{
    background-color:#F3E6E6;
    border-color: #924949;
    border-style: solid solid solid none;
    border-width: 2px;
    padding: 5px;
}

And here is the background image you need:

alt text
(source: scriptiny.com)

If you want the error message to be displayed after a group of options or fields. Then group all those elements inside one container a 'div' or a 'fieldset'. Add a special class to all of them 'group' for example. And add the following to the begining of the errorPlacement function:

errorPlacement: function(error, element) {
    if (element.hasClass('group')){
        element = element.parent();
    }
    ...// continue as previously explained

If you only want to handle specific cases you can use attr instead:

if (element.attr('type') == 'radio'){
    element = element.parent();
}

That should be enough for the error message to be displayed next to the parent element.

You may need to change the width of the parent element to be less than 100%.


I've tried your code and it is working perfectly fine for me. Here is a preview: alt text

I just made a very small adjustment to the message padding to make it fit in the line:

div.error {
    padding: 2px 5px;
}

You can change those numbers to increase/decrease the padding on top/bottom or left/right. You can also add a height and width to the error message. If you are still having issues, try to replace the span with a div

<div class="group">
<input type="radio" class="checkbox" value="P" id="radio_P" name="radio_group_name"/>
<label for="radio_P">P</label>
<input type="radio" class="checkbox" value="S" id="radio_S" name="radio_group_name"/>
<label for="radio_S">S</label>
</div>

And then give the container a width (this is very important)

div.group {
    width: 50px; /* or any other value */
}

About the blank page. As I said I tried your code and it is working for me. It might be something else in your code that is causing the issue.

Why fragments, and when to use fragments instead of activities?

Adding to above answers, I shall tell using example of an app I released on playstore.

This was the first app I developed when learning android there fore I worked only with activities There are multiple activity pages I think about 12. Most of these had content that could be reused in other pages yet I ended up with a separate activity page for almost every single click on the app. Once I learnt fragments I realised how all reusables could just be implemented and separate fragments and just be used with very few activities. My user may not see any difference, but the same can be done with lesser code besides fragments are light weight, apart from the reusability and modularity they offer.

Android Get Current timestamp?

java.time

I should like to contribute the modern answer.

    String ts = String.valueOf(Instant.now().getEpochSecond());
    System.out.println(ts);

Output when running just now:

1543320466

While division by 1000 won’t come as a surprise to many, doing your own time conversions can get hard to read pretty fast, so it’s a bad habit to get into when you can avoid it.

The Instant class that I am using is part of java.time, the modern Java date and time API. It’s built-in on new Android versions, API level 26 and up. If you are programming for older Android, you may get the backport, see below. If you don’t want to do that, understandably, I’d still use a built-in conversion:

    String ts = String.valueOf(TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()));
    System.out.println(ts);

This is the same as the answer by sealskej. Output is the same as before.

Question: Can I use java.time on Android?

Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

Pandas - How to flatten a hierarchical index in columns

The easiest and most intuitive solution for me was to combine the column names using get_level_values. This prevents duplicate column names when you do more than one aggregation on the same column:

level_one = df.columns.get_level_values(0).astype(str)
level_two = df.columns.get_level_values(1).astype(str)
df.columns = level_one + level_two

If you want a separator between columns, you can do this. This will return the same thing as Seiji Armstrong's comment on the accepted answer that only includes underscores for columns with values in both index levels:

level_one = df.columns.get_level_values(0).astype(str)
level_two = df.columns.get_level_values(1).astype(str)
column_separator = ['_' if x != '' else '' for x in level_two]
df.columns = level_one + column_separator + level_two

I know this does the same thing as Andy Hayden's great answer above, but I think it is a bit more intuitive this way and is easier to remember (so I don't have to keep referring to this thread), especially for novice pandas users.

This method is also more extensible in the case where you may have 3 column levels.

level_one = df.columns.get_level_values(0).astype(str)
level_two = df.columns.get_level_values(1).astype(str)
level_three = df.columns.get_level_values(2).astype(str)
df.columns = level_one + level_two + level_three

Uploading file using POST request in Node.js

Leonid Beschastny's answer works but I also had to convert ArrayBuffer to Buffer that is used in the Node's request module. After uploading file to the server I had it in the same format that comes from the HTML5 FileAPI (I'm using Meteor). Full code below - maybe it will be helpful for others.

function toBuffer(ab) {
  var buffer = new Buffer(ab.byteLength);
  var view = new Uint8Array(ab);
  for (var i = 0; i < buffer.length; ++i) {
    buffer[i] = view[i];
  }
  return buffer;
}

var req = request.post(url, function (err, resp, body) {
  if (err) {
    console.log('Error!');
  } else {
    console.log('URL: ' + body);
  }
});
var form = req.form();
form.append('file', toBuffer(file.data), {
  filename: file.name,
  contentType: file.type
});

How do I skip an iteration of a `foreach` loop?

You could also flip your if test:


foreach ( int number in numbers )
{
     if ( number >= 0 )
     {
        //process number
     }
 }

Simple example for Intent and Bundle

For example :

In MainActivity :

Intent intent = new Intent(this, OtherActivity.class);
intent.putExtra(OtherActivity.KEY_EXTRA, yourDataObject);
startActivity(intent);

In OtherActivity :

public static final String KEY_EXTRA = "com.example.yourapp.KEY_BOOK";

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  String yourDataObject = null;

  if (getIntent().hasExtra(KEY_EXTRA)) {
      yourDataObject = getIntent().getStringExtra(KEY_EXTRA);
  } else {
      throw new IllegalArgumentException("Activity cannot find  extras " + KEY_EXTRA);
  }
  // do stuff
}

More informations here : http://developer.android.com/reference/android/content/Intent.html

Failed to resolve: com.google.android.gms:play-services in IntelliJ Idea with gradle

I just replaced version 11.2.0 with 11.0.0 and then it seemed to work fine, so that had to mean that 11.2.0 wasn't included with the latest Android SDK.

So, after struggling with all the available scattered documentation, I reached this document by pure chance (I guess it is not indexed high enough by Google): https://developers.google.com/android/guides/releases

I quote from there:

Highlights from the Google Play services 11.2 release. Google Play services dependencies are now available via maven.google.com

Now, even when that shouldn't necessarily mean that they are not available with the downloaded SDK anymore, it seems that this is actually the case.

Anyway, adding google() to my build.gradle didn't work (not found, undefined, or whatever...), so I used a different approach that I found in this document referenced from the previous one:

https://developer.android.com/studio/build/dependencies.html#google-maven

I modified my build.gradle file adding that line to allprojects/repositories, as in:

allprojects {
...
    repositories {
...
        maven { url "https://maven.google.com/"}
    }
}

And then also in the android section in the same build.gradle file:

project(":android") {
...
    dependencies {
...
        compile 'com.google.android.gms:play-services-ads:11.2.0'
    }
}

Those two lines were enough to make Gradle sync without problems. I didn't need to add any plugins apart from the ones that are already added in my libGDX project by default.

After that, I got a few different errors, but none about Gradle or dependencies. In a brief, JFTR:

First, I had a minSdkVersion of 8. Solved by raising it to 14. I think I could live without supporting all those devices below 14.

Second, I had problems with the dex upper limit of references. I've never faced this problem before, but maybe you've already noticed the solution I used: instead of compiling the whole 'com.google.android.gms:play-services' I used only 'com.google.android.gms:play-services-ads' that's the API I'm actually interested right now. For those other particular cases where a solution like this may not be useful, this document could provide some better insight: https://developer.android.com/studio/build/multidex.html

Third, even after that I got this "jumbo" thing problem described and answered here: https://stackoverflow.com/a/26248495/1160360

And that's it. As of now, everything builds and my game does finally shows those Admob banners.

I've spent hours with this, thought, which makes me wonder if all these building automation systems we are using lately are worth the extra load they add.

I mean, the first time I had to add Admob to an app five years ago or so, I just had to download a .jar file and put it on a directory on my project. It was pretty obvious and the whole process, from googling "how to setup Admob in my android project" to have my app showing an Admob banner took me just a few minutes. I'm gonna leave it here, since this is not the place for such kind of debate.

Nonetheless, I hope my own experience is useful for someone else further.

How do you use variables in a simple PostgreSQL script?

You can use:

\set list '''foobar'''
SELECT * FROM dbo.PubLists WHERE name = :list;

That will do

How to control font sizes in pgf/tikz graphics in latex?

I found the better control would be using scalefnt package:

\usepackage{scalefnt}
...
{\scalefont{0.5}
\begin{tikzpicture}
...
\end{tikzpicture}
}

How can I set the default value for an HTML <select> element?

An improvement for nobita's answer. Also you can improve the visual view of the drop down list, by hiding the element 'Choose here'.

_x000D_
_x000D_
<select>_x000D_
  <option selected disabled hidden>Choose here</option>_x000D_
  <option value="1">One</option>_x000D_
  <option value="2">Two</option>_x000D_
  <option value="3">Three</option>_x000D_
  <option value="4">Four</option>_x000D_
  <option value="5">Five</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

HTML not loading CSS file

With HTML5 all you need is the rel, not even the type.

<link href="custom.css" rel="stylesheet"></link>

python-How to set global variables in Flask?

With:

global index_add_counter

You are not defining, just declaring so it's like saying there is a global index_add_counter variable elsewhere, and not create a global called index_add_counter. As you name don't exists, Python is telling you it can not import that name. So you need to simply remove the global keyword and initialize your variable:

index_add_counter = 0

Now you can import it with:

from app import index_add_counter

The construction:

global index_add_counter

is used inside modules' definitions to force the interpreter to look for that name in the modules' scope, not in the definition one:

index_add_counter = 0
def test():
  global index_add_counter # means: in this scope, use the global name
  print(index_add_counter)

How to Use Multiple Columns in Partition By And Ensure No Duplicate Row is Returned

If your table columns contains duplicate data and If you directly apply row_ number() and create PARTITION on column, there is chance to have result in duplicated row and with row number value.

To remove duplicate row, you need one more INNER query in from clause which eliminates duplicate rows and then it will give output to it's foremost outer FROM clause where you can apply PARTITION and ROW_NUMBER ().

As like below example:

SELECT DATE, STATUS, TITLE, ROW_NUMBER() OVER (PARTITION BY DATE, STATUS, TITLE ORDER BY QUANTITY ASC) AS Row_Num
FROM (
     SELECT DISTINCT <column names>...
) AS tbl

How to remove old Docker containers

To remove ALL containers:

sudo docker ps -a | grep -v CONTAINER | awk '{print $1}' | xargs --no-run-if-empty sudo docker rm -f

Explanation:

sudo docker ps -a

Returns a list of containers.

awk '{print $1}'

Gets the first column which is the container ID.

grep -v CONTAINER

Remove the title.

The last pipe sends the IDs to sudo docker rm -f safely.

iPhone viewWillAppear not firing

I think what they mean "directly" is by hooking things up just the same way as the xcode "Navigation Application" template does, which sets the UINavigationController as the sole subview of the application's UIWindow.

Using that template is the only way I've been able to get the Will/Did/Appear/Disappear methods called on the object ViewControllers upon push/pops of those controllers in the UINavigationController. None of the other solutions in the answers here worked for me, including implementing them in the RootController and passing them through to the (child) NavigationController. Those functions (will/did/appear/disappear) were only called in my RootController upon showing/hiding the top-level VCs, my "login" and navigationVCs, not the sub-VCs in the navigation controller, so I had no opportunity to "pass them through" to the Nav VC.

I ended up using the UINavigationController's delegate functionality to look for the particular transitions that required follow-up functionality in my app, and that works, but it requires a bit more work in order to get both the disappear and appear functionality "simulated".

Also it's a matter of principle to get it to work after banging my head against this problem for hours today. Any working code snippets using a custom RootController and a child navigation VC would be much appreciated.

How to serve up a JSON response using Go?

You may use this package renderer, I have written to solve this kind of problem, it's a wrapper to serve JSON, JSONP, XML, HTML etc.

HTTP POST using JSON in Java

Here is what you need to do:

  1. Get the Apache HttpClient, this would enable you to make the required request
  2. Create an HttpPost request with it and add the header application/x-www-form-urlencoded
  3. Create a StringEntity that you will pass JSON to it
  4. Execute the call

The code roughly looks like (you will still need to debug it and make it work):

// @Deprecated HttpClient httpClient = new DefaultHttpClient();
HttpClient httpClient = HttpClientBuilder.create().build();
try {
    HttpPost request = new HttpPost("http://yoururl");
    StringEntity params = new StringEntity("details={\"name\":\"xyz\",\"age\":\"20\"} ");
    request.addHeader("content-type", "application/x-www-form-urlencoded");
    request.setEntity(params);
    HttpResponse response = httpClient.execute(request);
} catch (Exception ex) {
} finally {
    // @Deprecated httpClient.getConnectionManager().shutdown(); 
}

What is a good regular expression to match a URL?

(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})

Will match the following cases

  • http://www.foufos.gr
  • https://www.foufos.gr
  • http://foufos.gr
  • http://www.foufos.gr/kino
  • http://werer.gr
  • www.foufos.gr
  • www.mp3.com
  • www.t.co
  • http://t.co
  • http://www.t.co
  • https://www.t.co
  • www.aa.com
  • http://aa.com
  • http://www.aa.com
  • https://www.aa.com

Will NOT match the following

  • www.foufos
  • www.foufos-.gr
  • www.-foufos.gr
  • foufos.gr
  • http://www.foufos
  • http://foufos
  • www.mp3#.com

_x000D_
_x000D_
var expression = /(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})/gi;_x000D_
var regex = new RegExp(expression);_x000D_
_x000D_
var check = [_x000D_
  'http://www.foufos.gr',_x000D_
  'https://www.foufos.gr',_x000D_
  'http://foufos.gr',_x000D_
  'http://www.foufos.gr/kino',_x000D_
  'http://werer.gr',_x000D_
  'www.foufos.gr',_x000D_
  'www.mp3.com',_x000D_
  'www.t.co',_x000D_
  'http://t.co',_x000D_
  'http://www.t.co',_x000D_
  'https://www.t.co',_x000D_
  'www.aa.com',_x000D_
  'http://aa.com',_x000D_
  'http://www.aa.com',_x000D_
  'https://www.aa.com',_x000D_
  'www.foufos',_x000D_
  'www.foufos-.gr',_x000D_
  'www.-foufos.gr',_x000D_
  'foufos.gr',_x000D_
  'http://www.foufos',_x000D_
  'http://foufos',_x000D_
  'www.mp3#.com'_x000D_
];_x000D_
_x000D_
check.forEach(function(entry) {_x000D_
  if (entry.match(regex)) {_x000D_
    $("#output").append( "<div >Success: " + entry + "</div>" );_x000D_
  } else {_x000D_
    $("#output").append( "<div>Fail: " + entry + "</div>" );_x000D_
  }_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="output"></div>
_x000D_
_x000D_
_x000D_

Check it in rubular - NEW version

Check it in rubular - old version

How to convert a command-line argument to int?

Like that we can do....

int main(int argc, char *argv[]) {

    int a, b, c;
    *// Converting string type to integer type
    // using function "atoi( argument)"* 

    a = atoi(argv[1]);     
    b = atoi(argv[2]);
    c = atoi(argv[3]);

 }

Curl to return http status code along with the response

This is a way to retrieve the body "AND" the status code and format it to a proper json or whatever format works for you. Some may argue it's the incorrect use of write format option but this works for me when I need both body and status code in my scripts to check status code and relay back the responses from server.

curl -X GET -w "%{stderr}{\"status\": \"%{http_code}\", \"body\":\"%{stdout}\"}"  -s -o - “https://github.com” 2>&1

run the code above and you should get back a json in this format:

{
"status" : <status code>,
"body" : <body of response>
}

with the -w write format option, since stderr is printed first, you can format your output with the var http_code and place the body of the response in a value (body) and follow up the enclosing using var stdout. Then redirect your stderr output to stdout and you'll be able to combine both http_code and response body into a neat output

How to determine a user's IP address in node

If you're using express version 3.x or greater, you can use the trust proxy setting (http://expressjs.com/api.html#trust.proxy.options.table) and it will walk the chain of addresses in the x-forwarded-for header and put the latest ip in the chain that you've not configured as a trusted proxy into the ip property on the req object.

C# LINQ find duplicates in List

Find out if an enumerable contains any duplicate :

var anyDuplicate = enumerable.GroupBy(x => x.Key).Any(g => g.Count() > 1);

Find out if all values in an enumerable are unique :

var allUnique = enumerable.GroupBy(x => x.Key).All(g => g.Count() == 1);

String.contains in Java

The obvious answer to this is "that's what the JLS says."

Thinking about why that is, consider that this behavior can be useful in certain cases. Let's say you want to check a string against a set of other strings, but the number of other strings can vary.

So you have something like this:

for(String s : myStrings) {
   check(aString.contains(s));
}

where some s's are empty strings.

If the empty string is interpreted as "no input," and if your purpose here is ensure that aString contains all the "inputs" in myStrings, then it is misleading for the empty string to return false. All strings contain it because it is nothing. To say they didn't contain it would imply that the empty string had some substance that was not captured in the string, which is false.

Can I call curl_setopt with CURLOPT_HTTPHEADER multiple times to set multiple headers?

/**
 * If $header is an array of headers
 * It will format and return the correct $header
 * $header = [
 *  'Accept' => 'application/json',
 *  'Content-Type' => 'application/x-www-form-urlencoded'
 * ];
 */
$i_header = $header;
if(is_array($i_header) === true){
    $header = [];
    foreach ($i_header as $param => $value) {
        $header[] = "$param: $value";
    }
}

Make child visible outside an overflow:hidden parent

This is an old question but encountered it myself.

I have semi-solutions that work situational for the former question("Children visible in overflow:hidden parent")

If the parent div does not need to be position:relative, simply set the children styles to visibility:visible.

If the parent div does need to be position:relative, the only way possible I found to show the children was position:fixed. This worked for me in my situation luckily enough but I would imagine it wouldn't work in others.

Here is a crappy example just post into a html file to view.

<div style="background: #ff00ff; overflow: hidden; width: 500px; height: 500px; position: relative;">
    <div style="background: #ff0000;position: fixed; top: 10px; left: 10px;">asd
        <div style="background: #00ffff; width: 200px; overflow: visible; position: absolute; visibility: visible; clear:both; height: 1000px; top: 100px; left: 10px;"> a</div>
    </div>
</div>

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

I think you are looking for text-overflow: ellipsis in combination with white-space: nowrap

See some more details here

Running a command as Administrator using PowerShell?

To append the output of the command to a text filename which includes the current date you can do something like this:

$winupdfile = 'Windows-Update-' + $(get-date -f MM-dd-yyyy) + '.txt'
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -Command `"Get-WUInstall -AcceptAll | Out-File $env:USERPROFILE\$winupdfile -Append`"" -Verb RunAs; exit } else { Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -Command `"Get-WUInstall -AcceptAll | Out-File $env:USERPROFILE\$winupdfile -Append`""; exit }

css transition opacity fade background

It's not fading to "black transparent" or "white transparent". It's just showing whatever color is "behind" the image, which is not the image's background color - that color is completely hidden by the image.

If you want to fade to black(ish), you'll need a black container around the image. Something like:

.ctr {
    margin: 0; 
    padding: 0;
    background-color: black;
    display: inline-block;
}

and

<div class="ctr"><img ... /></div>

how to release localhost from Error: listen EADDRINUSE

Error: listen EADDRINUSE to solve it in Ubuntu run in terminal netstat -nptl and after this kill -9 {process-number} this command is to kill node process and now you can try to run again node server.js command

Ex

listen EADDRINUSE :::8080

netstat -nptl

tcp6 0 0 :::9000 :::* LISTEN 9660/java
tcp6 0 0 :::5800 :::* LISTEN -
tcp6 0 0 :::5900 :::* LISTEN -
tcp6 0 0 :::8080 :::* LISTEN 10401/node
tcp6 0 0 :::20080 :::* LISTEN 9660/java
tcp6 0 0 :::80 :::* LISTEN -
tcp6 0 0 :::22 :::* LISTEN -
tcp6 0 0 :::10137 :::* LISTEN 9660/java

kill -9 10401

How do I drop a foreign key in SQL Server?

alter table company drop constraint Company_CountryID_FK

Send value of submit button when form gets posted

You could use something like this to give your button a value:

<?php
if (isset($_POST['submit'])) {
  $aSubmitVal = array_keys($_POST['submit'])[0];
  echo 'The button value is: ' . $aSubmitVal;
}
?>
<form action="/" method="post">
  <input id="someId" type="submit" name="submit[SomeValue]" value="Button name">
</form>

This will give you the string "SomeValue" as a result

https://i.imgur.com/28gr7Uy.gif

error_reporting(E_ALL) does not produce error

That error is a parse error. The parser is throwing it while going through the code, trying to understand it. No code is being executed yet in the parsing stage. Because of that it hasn't yet executed the error_reporting line, therefore the error reporting settings aren't changed yet.

You cannot change error reporting settings (or really, do anything) in a file with syntax errors.

Correctly Parsing JSON in Swift 3

I built quicktype exactly for this purpose. Just paste your sample JSON and quicktype generates this type hierarchy for your API data:

struct Forecast {
    let hourly: Hourly
    let daily: Daily
    let currently: Currently
    let flags: Flags
    let longitude: Double
    let latitude: Double
    let offset: Int
    let timezone: String
}

struct Hourly {
    let icon: String
    let data: [Currently]
    let summary: String
}

struct Daily {
    let icon: String
    let data: [Datum]
    let summary: String
}

struct Datum {
    let precipIntensityMax: Double
    let apparentTemperatureMinTime: Int
    let apparentTemperatureLowTime: Int
    let apparentTemperatureHighTime: Int
    let apparentTemperatureHigh: Double
    let apparentTemperatureLow: Double
    let apparentTemperatureMaxTime: Int
    let apparentTemperatureMax: Double
    let apparentTemperatureMin: Double
    let icon: String
    let dewPoint: Double
    let cloudCover: Double
    let humidity: Double
    let ozone: Double
    let moonPhase: Double
    let precipIntensity: Double
    let temperatureHigh: Double
    let pressure: Double
    let precipProbability: Double
    let precipIntensityMaxTime: Int
    let precipType: String?
    let sunriseTime: Int
    let summary: String
    let sunsetTime: Int
    let temperatureMax: Double
    let time: Int
    let temperatureLow: Double
    let temperatureHighTime: Int
    let temperatureLowTime: Int
    let temperatureMin: Double
    let temperatureMaxTime: Int
    let temperatureMinTime: Int
    let uvIndexTime: Int
    let windGust: Double
    let uvIndex: Int
    let windBearing: Int
    let windGustTime: Int
    let windSpeed: Double
}

struct Currently {
    let precipProbability: Double
    let humidity: Double
    let cloudCover: Double
    let apparentTemperature: Double
    let dewPoint: Double
    let ozone: Double
    let icon: String
    let precipIntensity: Double
    let temperature: Double
    let pressure: Double
    let precipType: String?
    let summary: String
    let uvIndex: Int
    let windGust: Double
    let time: Int
    let windBearing: Int
    let windSpeed: Double
}

struct Flags {
    let sources: [String]
    let isdStations: [String]
    let units: String
}

It also generates dependency-free marshaling code to coax the return value of JSONSerialization.jsonObject into a Forecast, including a convenience constructor that takes a JSON string so you can quickly parse a strongly typed Forecast value and access its fields:

let forecast = Forecast.from(json: jsonString)!
print(forecast.daily.data[0].windGustTime)

You can install quicktype from npm with npm i -g quicktype or use the web UI to get the complete generated code to paste into your playground.

Is there a way to take a screenshot using Java and save it to some sort of image?

I never liked using Robot, so I made my own simple method for making screenshots of JFrame objects:

public static final void makeScreenshot(JFrame argFrame) {
    Rectangle rec = argFrame.getBounds();
    BufferedImage bufferedImage = new BufferedImage(rec.width, rec.height, BufferedImage.TYPE_INT_ARGB);
    argFrame.paint(bufferedImage.getGraphics());

    try {
        // Create temp file
        File temp = File.createTempFile("screenshot", ".png");

        // Use the ImageIO API to write the bufferedImage to a temporary file
        ImageIO.write(bufferedImage, "png", temp);

        // Delete temp file when program exits
        temp.deleteOnExit();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
}

convert double to int

You can use a cast if you want the default truncate-towards-zero behaviour. Alternatively, you might want to use Math.Ceiling, Math.Round, Math.Floor etc - although you'll still need a cast afterwards.

Don't forget that the range of int is much smaller than the range of double. A cast from double to int won't throw an exception if the value is outside the range of int in an unchecked context, whereas a call to Convert.ToInt32(double) will. The result of the cast (in an unchecked context) is explicitly undefined if the value is outside the range.

How should you diagnose the error SEHException - External component has thrown an exception

The component makers say that this has been fixed in the latest version of their component which we are using in-house, but this has been given to the customer yet.

Ask the component maker how to test whether the problem that the customer is getting is the problem which they say they've fixed in their latest version, without/before deploying their latest version to the customer.

How Do I Replace/Change The Heading Text Inside <h3></h3>, Using jquery?

try this,

$(".head h3").html("New header");

or

$(".head h3").text("New header");

remember class selectors returns all the matching elements.

What does href expression <a href="javascript:;"></a> do?

There are several mechanisms to avoid a link to reach its destination. The one from the question is not much intuitive.

A cleaner option is to use href="#no" where #no is a non-defined anchor in the document.

You can use a more semantic name such as #disable, or #action to increase readability.

Benefits of the approach:

  • Avoids the "moving to the top" effect of the empty href="#"
  • Avoids the use of javascript

Drawbacks:

  • You must be sure the anchor name is not used in the document.
  • The URL changes to include the (non-existing) anchor as fragment and a new browser history entry is created. This means that clicking the "back" button after clicking the link won't behave as expected.

Since the <a> element is not acting as a link, the best option in these cases is not using an <a> element but a <div> and provide the desired link-like style.

HTML img onclick Javascript

This might work for you...

<script type="text/javascript">
function image(img) {
    var src = img.src;
    window.open(src);
}
</script>
<img src="pond1.jpg" height="150" size="150" alt="Johnson Pond" onclick="image(this)">

What is the best way to implement "remember me" for a website?

Store their UserId and a RememberMeToken. When they login with remember me checked generate a new RememberMeToken (which invalidate any other machines which are marked are remember me).

When they return look them up by the remember me token and make sure the UserId matches.

How to use GROUP BY to concatenate strings in MySQL?

SELECT id, GROUP_CONCAT( string SEPARATOR ' ') FROM table GROUP BY id

More details here.

From the link above, GROUP_CONCAT: This function returns a string result with the concatenated non-NULL values from a group. It returns NULL if there are no non-NULL values.

@angular/material/index.d.ts' is not a module

@angular/material has changed its folder structure. Now you need to use all the modules from their respective folders instead of just material folder

For example:

import { MatDialogModule } from "@angular/material";

has now changed to

import { MatDialogModule } from "@angular/material/dialog";

You can check the following to find the correct path for your module

https://material.angular.io/components/categories

Just navigate to the API tab of required module and find the correct path like this 1

XPath - Selecting elements that equal a value

Try

//*[text()='qwerty'] because . is your current element

Laravel: How do I parse this json data in view blade?

It's pretty easy. First of all send to the view decoded variable (see Laravel Views):

view('your-view')->with('leads', json_decode($leads, true));

Then just use common blade constructions (see Laravel Templating):

@foreach($leads['member'] as $member)
    Member ID: {{ $member['id'] }}
    Firstname: {{ $member['firstName'] }}
    Lastname: {{ $member['lastName'] }}
    Phone: {{ $member['phoneNumber'] }}

    Owner ID: {{ $member['owner']['id'] }}
    Firstname: {{ $member['owner']['firstName'] }} 
    Lastname: {{ $member['owner']['lastName'] }}
@endforeach

Eclipse does not highlight matching variables

If highlighting is not working for large files, scalability mode has to be off. Properties / (c/c++) / Editor / Scalability

Array String Declaration

I think the beginning to the resolution to this issue is the fact that the use of the for loop or any other function or action can not be done in the class definition but needs to be included in a method/constructor/block definition inside of a class.

What is the difference between procedural programming and functional programming?

Funtional Programming

num = 1 
def function_to_add_one(num):
    num += 1
    return num


function_to_add_one(num)
function_to_add_one(num)
function_to_add_one(num)
function_to_add_one(num)
function_to_add_one(num)

#Final Output: 2

Procedural Programming

num = 1 
def procedure_to_add_one():
    global num
    num += 1
    return num


procedure_to_add_one()
procedure_to_add_one()
procedure_to_add_one()
procedure_to_add_one()
procedure_to_add_one()

#Final Output: 6

function_to_add_one is a function

procedure_to_add_one is a procedure

Even if you run the function five times, every time it will return 2

If you run the procedure five times, at the end of fifth run it will give you 6.

DISCLAIMER: Obviously this is a hyper-simplified view of reality. This answer just gives a taste of "functions" as opposed to "procedures". Nothing more. Once you have tasted this superficial yet deeply penetrative intuition, start exploring the two paradigms, and you will start to see the difference quite clearly.

Helps my students, hope it helps you too.

How do you get the width and height of a multi-dimensional array?

Use GetLength(), rather than Length.

int rowsOrHeight = ary.GetLength(0);
int colsOrWidth = ary.GetLength(1);

Formula to convert date to number

The Excel number for a modern date is most easily calculated as the number of days since 12/30/1899 on the Gregorian calendar.

Excel treats the mythical date 01/00/1900 (i.e., 12/31/1899) as corresponding to 0, and incorrectly treats year 1900 as a leap year. So for dates before 03/01/1900, the Excel number is effectively the number of days after 12/31/1899.

However, Excel will not format any number below 0 (-1 gives you ##########) and so this only matters for "01/00/1900" to 02/28/1900, making it easier to just use the 12/30/1899 date as a base.

A complete function in DB2 SQL that accounts for the leap year 1900 error:

SELECT
   DAYS(INPUT_DATE)                 
   - DAYS(DATE('1899-12-30'))
   - CASE                       
        WHEN INPUT_DATE < DATE('1900-03-01')  
           THEN 1               
           ELSE 0               
     END

MVC controller : get JSON object from HTTP body?

you can get the json string as a param of your ActionResult and afterwards serialize it using JSON.Net

HERE an example is being shown


in order to receive it in the serialized form as a param of the controller action you must either write a custom model binder or a Action filter (OnActionExecuting) so that the json string is serialized into the model of your liking and is available inside the controller body for use.


HERE is an implementation using the dynamic object

passing 2 $index values within nested ng-repeat

Way more elegant solution than $parent.$index is using ng-init:

<ul ng-repeat="section in sections" ng-init="sectionIndex = $index">
    <li  class="section_title {{section.active}}" >
        {{section.name}}
    </li>
    <ul>
        <li class="tutorial_title {{tutorial.active}}" ng-click="loadFromMenu(sectionIndex)" ng-repeat="tutorial in section.tutorials">
            {{tutorial.name}}
        </li>
    </ul>
</ul>

Plunker: http://plnkr.co/edit/knwGEnOsAWLhLieKVItS?p=info

Failure during conversion to COFF: file invalid or corrupt

Do you have Visual Studio 2012 installed as well? If so, 2012 stomps your 2010 IDE, possibly because of compatibility issues with .NET 4.5 and .NET 4.0.

See http://social.msdn.microsoft.com/Forums/da-DK/vssetup/thread/d10adba0-e082-494a-bb16-2bfc039faa80

What's the best strategy for unit-testing database-driven applications?

I use the first (running the code against a test database). The only substantive issue I see you raising with this approach is the possibilty of schemas getting out of sync, which I deal with by keeping a version number in my database and making all schema changes via a script which applies the changes for each version increment.

I also make all changes (including to the database schema) against my test environment first, so it ends up being the other way around: After all tests pass, apply the schema updates to the production host. I also keep a separate pair of testing vs. application databases on my development system so that I can verify there that the db upgrade works properly before touching the real production box(es).

Android LinearLayout Gradient Background

In XML Drawable File:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape>
            <gradient android:angle="90"
                android:endColor="#9b0493"
                android:startColor="#38068f"
                android:type="linear" />
        </shape>
    </item>
</selector>

In your layout file: android:background="@drawable/gradient_background"

  <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/gradient_background"
        android:orientation="vertical"
        android:padding="20dp">
        .....

</LinearLayout>

enter image description here

How can I disable a button on a jQuery UI dialog?

You can disable a button when you construct the dialog:

_x000D_
_x000D_
$(function() {_x000D_
  $("#dialog").dialog({_x000D_
    modal: true,_x000D_
    buttons: [_x000D_
      { text: "Confirm", click: function() { $(this).dialog("close"); }, disabled: true },_x000D_
      { text: "Cancel", click: function() { $(this).dialog("close"); } }_x000D_
    ]_x000D_
  });_x000D_
});
_x000D_
@import url("https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.min.css");
_x000D_
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>_x000D_
_x000D_
<div id="dialog" title="Confirmation">_x000D_
  <p>Proceed?</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Or you can disable it anytime after the dialog is created:

_x000D_
_x000D_
$(function() {_x000D_
  $("#dialog").dialog({_x000D_
    modal: true,_x000D_
    buttons: [_x000D_
      { text: "Confirm", click: function() { $(this).dialog("close"); }, "class": "confirm" },_x000D_
      { text: "Cancel", click: function() { $(this).dialog("close"); } }_x000D_
    ]_x000D_
  });_x000D_
  setTimeout(function() {_x000D_
    $("#dialog").dialog("widget").find("button.confirm").button("disable");_x000D_
  }, 2000);_x000D_
});
_x000D_
@import url("https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.min.css");
_x000D_
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>_x000D_
_x000D_
<div id="dialog" title="Confirmation">_x000D_
  <p>Button will disable after two seconds.</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to change the name of a Django app?

In many cases, I believe @allcaps's answer works well.

However, sometimes it is necessary to actually rename an app, e.g. to improve code readability or prevent confusion.

Most of the other answers involve either manual database manipulation or tinkering with existing migrations, which I do not like very much.

As an alternative, I like to create a new app with the desired name, copy everything over, make sure it works, then remove the original app:

  1. Start a new app with the desired name, and copy all code from the original app into that. Make sure you fix the namespaced stuff, in the newly copied code, to match the new app name.

  2. makemigrations and migrate

  3. Create a data migration that copies the relevant data from the original app's tables into the new app's tables, and migrate again.

At this point, everything still works, because the original app and its data are still in place.

  1. Now you can refactor all the dependent code, so it only makes use of the new app. See other answers for examples of what to look out for.

  2. Once you are certain that everything works, you can remove the original app.

This has the advantage that every step uses the normal Django migration mechanism, without manual database manipulation, and we can track everything in source control. In addition, we keep the original app and its data in place until we are sure everything works.

npm can't find package.json

Node comes with npm installed so you should have a version of npm. However, npm gets updated more frequently than Node does, so you'll want to make sure it's the latest version.

sudo npm install npm -g

Test:

npm -v //The version should be higher than 2.1.8

After this you should be able to run:

npm install

Global Angular CLI version greater than local version

This is how I solved the issue.

Install latest Angular CLI package locally

Copy and run these commands

ng --version
npm install --save-dev @angular/cli@latest
ng --version

Bootstrap 3 Flush footer to bottom. not fixed

use flexbox as you can use it at your disposal. The solution offered by bootstrap 4 still hunting overlap content in responsive layout, e.g: it will break in mobile view, i come across the most neat trick is to use flexbox solution demo shown at here:(https://philipwalton.github.io/solved-by-flexbox/demos/sticky-footer/) this way we do not have to deal with fixed height issue which is an obsolete solution by now...this solution works for bootstrap 3 and 4 whichever you using.

<body class="Site">
  <header>…</header>
  <main class="Site-content">…</main>
  <footer>…</footer>
</body>

.Site {
  display: flex;
  min-height: 100vh;
  flex-direction: column;
}

.Site-content {
  flex: 1;
}

How to checkout in Git by date?

Andy's solution does not work for me. Here I found another way:

git checkout `git rev-list -n 1 --before="2009-07-27 13:37" master`

Git: checkout by date

HtmlSpecialChars equivalent in Javascript?

Chances are you don't need such a function. Since your code is already in the browser*, you can access the DOM directly instead of generating and encoding HTML that will have to be decoded backwards by the browser to be actually used.

Use innerText property to insert plain text into the DOM safely and much faster than using any of the presented escape functions. Even faster than assigning a static preencoded string to innerHTML.

Use classList to edit classes, dataset to set data- attributes and setAttribute for others.

All of these will handle escaping for you. More precisely, no escaping is needed and no encoding will be performed underneath**, since you are working around HTML, the textual representation of DOM.

_x000D_
_x000D_
// use existing element_x000D_
var author = 'John "Superman" Doe <[email protected]>';_x000D_
var el = document.getElementById('first');_x000D_
el.dataset.author = author;_x000D_
el.textContent = 'Author: '+author;_x000D_
_x000D_
// or create a new element_x000D_
var a = document.createElement('a');_x000D_
a.classList.add('important');_x000D_
a.href = '/search?q=term+"exact"&n=50';_x000D_
a.textContent = 'Search for "exact" term';_x000D_
document.body.appendChild(a);_x000D_
_x000D_
// actual HTML code_x000D_
console.log(el.outerHTML);_x000D_
console.log(a.outerHTML);
_x000D_
.important { color: red; }
_x000D_
<div id="first"></div>
_x000D_
_x000D_
_x000D_

* This answer is not intended for server-side JavaScript users (Node.js, etc.)

** Unless you explicitly convert it to actual HTML afterwards. E.g. by accessing innerHTML - this is what happens when you run $('<div/>').text(value).html(); suggested in other answers. So if your final goal is to insert some data into the document, by doing it this way you'll be doing the work twice. Also you can see that in the resulting HTML not everything is encoded, only the minimum that is needed for it to be valid. It is done context-dependently, that's why this jQuery method doesn't encode quotes and therefore should not be used as a general purpose escaper. Quotes escaping is needed when you're constructing HTML as a string with untrusted or quote-containing data at the place of an attribute's value. If you use the DOM API, you don't have to care about escaping at all.

Validate SSL certificates with Python

From release version 2.7.9/3.4.3 on, Python by default attempts to perform certificate validation.

This has been proposed in PEP 467, which is worth a read: https://www.python.org/dev/peps/pep-0476/

The changes affect all relevant stdlib modules (urllib/urllib2, http, httplib).

Relevant documentation:

https://docs.python.org/2/library/httplib.html#httplib.HTTPSConnection

This class now performs all the necessary certificate and hostname checks by default. To revert to the previous, unverified, behavior ssl._create_unverified_context() can be passed to the context parameter.

https://docs.python.org/3/library/http.client.html#http.client.HTTPSConnection

Changed in version 3.4.3: This class now performs all the necessary certificate and hostname checks by default. To revert to the previous, unverified, behavior ssl._create_unverified_context() can be passed to the context parameter.

Note that the new built-in verification is based on the system-provided certificate database. Opposed to that, the requests package ships its own certificate bundle. Pros and cons of both approaches are discussed in the Trust database section of PEP 476.

Java Currency Number format

  public static String formatPrice(double value) {
        DecimalFormat formatter;
        if (value<=99999)
          formatter = new DecimalFormat("###,###,##0.00");
        else
            formatter = new DecimalFormat("#,##,##,###.00");

        return formatter.format(value);
    }

"The system cannot find the file specified" when running C++ program

Since this thread is one of the top results for that error and has no fix yet, I'll post what I found to fix it, originally found in this thread: Build Failure? "Unable to start program... The system cannot find the file specificed" which lead me to this thread: Error 'LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt' after installing Visual Studio 2012 Release Preview

Basically all I did is this: Project Properties -> Configuration Properties -> Linker (General) -> Enable Incremental Linking -> "No (/INCREMENTAL:NO)"

Mergesort with Python

As already said, l.pop(0) is a O(len(l)) operation and must be avoided, the above msort function is O(n**2). If efficiency matter, indexing is better but have cost too. The for x in l is faster but not easy to implement for mergesort : iter can be used instead here. Finally, checking i < len(l) is made twice because tested again when accessing the element : the exception mechanism (try except) is better and give a last improvement of 30% .

def msort(l):
    if len(l)>1:
        t=len(l)//2
        it1=iter(msort(l[:t]));x1=next(it1)
        it2=iter(msort(l[t:]));x2=next(it2)
        l=[]
        try:
            while True:
                if x1<=x2: l.append(x1);x1=next(it1)
                else     : l.append(x2);x2=next(it2)
        except:
            if x1<=x2: l.append(x2);l.extend(it2)
            else:      l.append(x1);l.extend(it1)
    return l

How to write super-fast file-streaming code in C#?

Have you considered using the CCR since you are writing to separate files you can do everything in parallel (read and write) and the CCR makes it very easy to do this.

static void Main(string[] args)
    {
        Dispatcher dp = new Dispatcher();
        DispatcherQueue dq = new DispatcherQueue("DQ", dp);

        Port<long> offsetPort = new Port<long>();

        Arbiter.Activate(dq, Arbiter.Receive<long>(true, offsetPort,
            new Handler<long>(Split)));

        FileStream fs = File.Open(file_path, FileMode.Open);
        long size = fs.Length;
        fs.Dispose();

        for (long i = 0; i < size; i += split_size)
        {
            offsetPort.Post(i);
        }
    }

    private static void Split(long offset)
    {
        FileStream reader = new FileStream(file_path, FileMode.Open, 
            FileAccess.Read);
        reader.Seek(offset, SeekOrigin.Begin);
        long toRead = 0;
        if (offset + split_size <= reader.Length)
            toRead = split_size;
        else
            toRead = reader.Length - offset;

        byte[] buff = new byte[toRead];
        reader.Read(buff, 0, (int)toRead);
        reader.Dispose();
        File.WriteAllBytes("c:\\out" + offset + ".txt", buff);
    }

This code posts offsets to a CCR port which causes a Thread to be created to execute the code in the Split method. This causes you to open the file multiple times but gets rid of the need for synchronization. You can make it more memory efficient but you'll have to sacrifice speed.

Node.js Mongoose.js string to ObjectId function

You can do it like so:

var mongoose = require('mongoose');
var id = mongoose.Types.ObjectId('4edd40c86762e0fb12000003');

Keyboard shortcuts are not active in Visual Studio with Resharper installed

Just a comment on this issue. After I installed Visual Studio 2015 RTM all my resharper shortcuts were gone. (I had them working just fine with RC) A few of my colleagues were having the exact same issue with Visual Studio 2012.

I tried all the suggestions in here but none worked. The way I found to solve this was to: go to Tools -> Import and Export Settings , select the "Import selected environment settings" and in my case use the Settings I had from my RC installation (you can see that there are files with parts of a date as the filename like: CurrentSettings-2014-09-22). For my colleagues problem I basically sent them my .vssettings that I had that was working on my local VS2012 installation.

This effectively solved the shortcut problem. Further investigation in my case showed that although I applied the Resharper shortcuts they were never bound to the actual shortcut key thats why resetting stuff never worked.

Location of hibernate.cfg.xml in project?

For anyone interested: if you are using Intellj, just simply put hibernate.cfg.xml under src/main/resources.

Email Address Validation for ASP.NET

You should always do server side validaton as well.

public bool IsValidEmailAddress(string email)
{
    try
    {
        var emailChecked = new System.Net.Mail.MailAddress(email);
        return true;
    }
    catch
    {
        return false;
    }
}

UPDATE

You can also use the EmailAddressAttribute in System.ComponentModel.DataAnnotations. Then there is no need for a try-catch to it's a cleaner solution.

public bool IsValidEmailAddress(string email)
{
    if (!string.IsNullOrEmpty(email) && new EmailAddressAttribute().IsValid(email))
        return true;
    else
        return false;
}

Note that the IsNullOrEmpty check is also needed otherwise a null value will return true.

Static image src in Vue.js template

You need use just simple code <img alt="img" src="../assets/index.png" />

Do not forgot atribut alt in balise img

How do I ignore all files in a folder with a Git repository in Sourcetree?

  • Ignore all files in folder with Git in Sourcetree:

Ignore all files in folder with Git in Sourcetree

Removing a non empty directory programmatically in C or C++

C++17 has <experimental\filesystem> which is based on the boost version.

Use std::experimental::filesystem::remove_all to remove recursively.

If you need more control, try std::experimental::filesystem::recursive_directory_iterator.

You can also write your own recursion with the non-resursive version of the iterator.

namespace fs = std::experimental::filesystem;
void IterateRecursively(fs::path path)
{
  if (fs::is_directory(path))
  {
    for (auto & child : fs::directory_iterator(path))
      IterateRecursively(child.path());
  }

  std::cout << path << std::endl;
}

How to fill in proxy information in cntlm config file?

Once you generated the file, and changed your password, you can run as below,

cntlm -H

Username will be the same. it will ask for password, give it, then copy the PassNTLMv2, edit the cntlm.ini, then just run the following

cntlm -v

Fix GitLab error: "you are not allowed to push code to protected branches on this project"?

I have encountered this error on "an empty branch" on my local gitlab server. Some people mentioned that "you can not push for the first time on an empty branch". I tried to create a simple README file on the gitlab via my browser. Then everything fixed amazingly and the problem sorted out!! I mention that I was the master and the branch was not protected.

Change value of input onchange?

You can't access your fieldname as a global variable. Use document.getElementById:

function updateInput(ish){
    document.getElementById("fieldname").value = ish;
}

and

onchange="updateInput(this.value)"

How do I convert a float number to a whole number in JavaScript?

Bitwise OR operator

A bitwise or operator can be used to truncate floating point figures and it works for positives as well as negatives:

function float2int (value) {
    return value | 0;
}

Results

float2int(3.1) == 3
float2int(-3.1) == -3
float2int(3.9) == 3
float2int(-3.9) == -3

Performance comparison?

I've created a JSPerf test that compares performance between:

  • Math.floor(val)
  • val | 0 bitwise OR
  • ~~val bitwise NOT
  • parseInt(val)

that only works with positive numbers. In this case you're safe to use bitwise operations well as Math.floor function.

But if you need your code to work with positives as well as negatives, then a bitwise operation is the fastest (OR being the preferred one). This other JSPerf test compares the same where it's pretty obvious that because of the additional sign checking Math is now the slowest of the four.

Note

As stated in comments, BITWISE operators operate on signed 32bit integers, therefore large numbers will be converted, example:

1234567890  | 0 => 1234567890
12345678901 | 0 => -539222987

Storing Python dictionaries

To write to a file:

import json
myfile.write(json.dumps(mydict))

To read from a file:

import json
mydict = json.loads(myfile.read())

myfile is the file object for the file that you stored the dict in.

How to split an integer into an array of digits?

return array as string

>>> list(str(12345))
['1', '2', '3', '4', '5']

return array as integer

>>> map(int,str(12345))
[1, 2, 3, 4, 5]

MySQL/Writing file error (Errcode 28)

This error occurs when you don't have enough space in the partition. Usually MYSQL uses /tmp on linux servers. This may happen with some queries because the lookup was either returning a lot of data, or possibly even just sifting through a lot of data creating big temp files.

Edit your /etc/mysql/my.cnf

tmpdir = /your/new/dir

e.g

tmpdir = /var/tmp

Should be allocated with more space than /tmp that is usually in it's own partition.

Add new line in text file with Windows batch file

DISCLAIMER: The below solution does not preserve trailing tabs.


If you know the exact number of lines in the text file, try the following method:

@ECHO OFF
SET origfile=original file
SET tempfile=temporary file
SET insertbefore=4
SET totallines=200
<%origfile% (FOR /L %%i IN (1,1,%totallines%) DO (
  SETLOCAL EnableDelayedExpansion
  SET /P L=
  IF %%i==%insertbefore% ECHO(
  ECHO(!L!
  ENDLOCAL
)
) >%tempfile%
COPY /Y %tempfile% %origfile% >NUL
DEL %tempfile%

The loop reads lines from the original file one by one and outputs them. The output is redirected to a temporary file. When a certain line is reached, an empty line is output before it.

After finishing, the original file is deleted and the temporary one gets assigned the original name.


UPDATE

If the number of lines is unknown beforehand, you can use the following method to obtain it:

FOR /F %%C IN ('FIND /C /V "" ^<%origfile%') DO SET totallines=%%C

(This line simply replaces the SET totallines=200 line in the above script.)

The method has one tiny flaw: if the file ends with an empty line, the result will be the actual number of lines minus one. If you need a workaround (or just want to play safe), you can use the method described in this answer.

How do I view / replay a chrome network debugger har file saved with content?

There are a couple of online, offline tools how to do this:

But the one that I liked the most, is a browser extension (tried it in chrome, hopefully it works in other browsers). After installation, it appears in your apps as HAR viewer. Then you can upload you HAR file and see something like this:

enter image description here

Is it possible to find out the users who have checked out my project on GitHub?

Go to the traffic section inside graphs. Here you can find how many unique visitors you have. Other than this there is no other way to know who exactly viewed your account.

Conditionally ignoring tests in JUnit 4

The JUnit way is to do this at run-time is org.junit.Assume.

 @Before
 public void beforeMethod() {
     org.junit.Assume.assumeTrue(someCondition());
     // rest of setup.
 }

You can do it in a @Before method or in the test itself, but not in an @After method. If you do it in the test itself, your @Before method will get run. You can also do it within @BeforeClass to prevent class initialization.

An assumption failure causes the test to be ignored.

Edit: To compare with the @RunIf annotation from junit-ext, their sample code would look like this:

@Test
public void calculateTotalSalary() {
    assumeThat(Database.connect(), is(notNull()));
    //test code below.
}

Not to mention that it is much easier to capture and use the connection from the Database.connect() method this way.

Android emulator: How to monitor network traffic?

You can monitor network traffic from Android Studio. Go to Android Monitor and open Network tab.

http://developer.android.com/tools/debugging/ddms.html

UPDATE: ?? Android Device Monitor was deprecated in Android Studio 3.1. See more in https://developer.android.com/studio/profile/monitor

Python integer incrementing with ++

Simply put, the ++ and -- operators don't exist in Python because they wouldn't be operators, they would have to be statements. All namespace modification in Python is a statement, for simplicity and consistency. That's one of the design decisions. And because integers are immutable, the only way to 'change' a variable is by reassigning it.

Fortunately we have wonderful tools for the use-cases of ++ and -- in other languages, like enumerate() and itertools.count().

Get type of all variables

You need to use get to obtain the value rather than the character name of the object as returned by ls:

x <- 1L
typeof(ls())
[1] "character"
typeof(get(ls()))
[1] "integer"

Alternatively, for the problem as presented you might want to use eapply:

eapply(.GlobalEnv,typeof)
$x
[1] "integer"

$a
[1] "double"

$b
[1] "character"

$c
[1] "list"

Is it possible to make Font Awesome icons larger than 'fa-5x'?

Alternatively you can edit the source and create your own incrementations

FontAwesome 5

https://github.com/FortAwesome/Font-Awesome/blob/master/web-fonts-with-css/less/_larger.less

// Icon Sizes
// -------------------------

.larger(@factor) when (@factor > 0) {
  .larger((@factor - 1));

  .@{fa-css-prefix}-@{factor}x {
    font-size: (@factor * 1em);
  }
}

/* makes the font 33% larger relative to the icon container */
.@{fa-css-prefix}-lg {
  font-size: (4em / 3);
  line-height: (3em / 4);
  vertical-align: -.0667em;
}

.@{fa-css-prefix}-xs {
  font-size: .75em;
}

.@{fa-css-prefix}-sm {
  font-size: .875em;
}

// Change the number below to create your own incrementations
// This currently creates classes .fa-1x - .fa-10x
.larger(10);

FontAwesome 4

https://github.com/FortAwesome/Font-Awesome/blob/v4.7.0/less/larger.less

// Icon Sizes
// -------------------------

/* makes the font 33% larger relative to the icon container */
.@{fa-css-prefix}-lg {
    font-size: (4em / 3);
    line-height: (3em / 4);
    vertical-align: -15%;
}

.@{fa-css-prefix}-2x { font-size: 2em; }
.@{fa-css-prefix}-3x { font-size: 3em; }
.@{fa-css-prefix}-4x { font-size: 4em; }
.@{fa-css-prefix}-5x { font-size: 5em; }

// Your custom sizes
.@{fa-css-prefix}-6x { font-size: 6em; }
.@{fa-css-prefix}-7x { font-size: 7em; }
.@{fa-css-prefix}-8x { font-size: 8em; }

Webclient / HttpWebRequest with Basic Authentication returns 404 not found for valid URL

This part of code worked fine for me:

        WebRequest request = WebRequest.Create(url);
        request.Method = WebRequestMethods.Http.Get;
        NetworkCredential networkCredential = new NetworkCredential(logon, password); // logon in format "domain\username"
        CredentialCache myCredentialCache = new CredentialCache {{new Uri(url), "Basic", networkCredential}};
        request.PreAuthenticate = true;
        request.Credentials = myCredentialCache;
        using (WebResponse response = request.GetResponse())
        {
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);

            using (Stream dataStream = response.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(dataStream))
                {
                    string responseFromServer = reader.ReadToEnd();
                    Console.WriteLine(responseFromServer);
                }
            }
        }

ERROR in Cannot find module 'node-sass'

In my case I had to also had to perform:

npm install sass-loader

To fix the problem

Generate a unique id

Why can't we make a unique id as below.

We can use DateTime.Now.Ticks and Guid.NewGuid().ToString() to combine together and make a unique id.

As the DateTime.Now.Ticks is added, we can find out the Date and Time in seconds at which the unique id is created.

Please see the code.

var ticks = DateTime.Now.Ticks;
var guid = Guid.NewGuid().ToString();
var uniqueSessionId = ticks.ToString() +'-'+ guid; //guid created by combining ticks and guid

var datetime = new DateTime(ticks);//for checking purpose
var datetimenow = DateTime.Now;    //both these date times are different.

We can even take the part of ticks in unique id and check for the date and time later for future reference.

How to create a session using JavaScript?

<script type="text/javascript">
function myfunction()
{
    var IDSes= "10200";
    '<%Session["IDDiv"] = "' + $(this).attr('id') + '"; %>'
    '<%Session["IDSes"] = "' + IDSes+ '"; %>';
     alert('<%=Session["IDSes"] %>');
}
</script>

link

JOptionPane YES/No Options Confirm Dialog Box Issue

Try this,

int dialogButton = JOptionPane.YES_NO_OPTION;
int dialogResult = JOptionPane.showConfirmDialog(this, "Your Message", "Title on Box", dialogButton);
if(dialogResult == 0) {
  System.out.println("Yes option");
} else {
  System.out.println("No Option");
} 

How do I align a number like this in C?

#include<stdio.h>
int main()
{
 int i,j,n,b;
 printf("Enter no of rows ");
 scanf("%d",&n);
 b=n;
 for(i=1;i<=n;++i)
 {
    for(j=1;j<=i;j++)
    {
        printf("%*d",b,j);
        b=1;
    }
        b=n;
    b=b-i;
    printf("\n");


 }
 return 0;
}

Most recent previous business day in Python

 def getNthBusinessDay(startDate, businessDaysInBetween):
    currentDate = startDate
    daysToAdd = businessDaysInBetween
    while daysToAdd > 0:
        currentDate += relativedelta(days=1)
        day = currentDate.weekday()
        if day < 5:
            daysToAdd -= 1

    return currentDate 

Set NA to 0 in R

Why not try this

  na.zero <- function (x) {
        x[is.na(x)] <- 0
        return(x)
    }
    na.zero(df)

How to detect pressing Enter on keyboard using jQuery?

I wrote a small plugin to make it easier to bind the "on enter key pressed" a event:

$.fn.enterKey = function (fnc) {
    return this.each(function () {
        $(this).keypress(function (ev) {
            var keycode = (ev.keyCode ? ev.keyCode : ev.which);
            if (keycode == '13') {
                fnc.call(this, ev);
            }
        })
    })
}

Usage:

$("#input").enterKey(function () {
    alert('Enter!');
})

Max or Default?

Since DefaultIfEmpty isn't implemented in LINQ to SQL, I did a search on the error it returned and found a fascinating article that deals with null sets in aggregate functions. To summarize what I found, you can get around this limitation by casting to a nullable within your select. My VB is a little rusty, but I think it'd go something like this:

Dim x = (From y In context.MyTable _
         Where y.MyField = value _
         Select CType(y.MyCounter, Integer?)).Max

Or in C#:

var x = (from y in context.MyTable
         where y.MyField == value
         select (int?)y.MyCounter).Max();

How to maximize the browser window in Selenium WebDriver (Selenium 2) using C#?

Simply use Window.Maximize() command

WebDriver driver= new ChromeDriver()
driver.Manage().Window.Maximize();  

<!--[if !IE]> not working

For IE browser:

<!--[if IE]>
<meta http-equiv="Content-Type" content="text/html; charset=Unicode">
<![endif]-->

For all non-IE browsers:

<![if !IE]>
<meta http-equiv="Content-Type" content="text/html; charset=utf8">
<![endif]>

For all IE greater than 8 OR all non-IE browsers :

<!--[if (gt IE 8)|!(IE)]><!--><script src="/_JS/library/jquery-2.1.1.min.js"></script><!--<![endif]-->

String field value length in mongoDB

Queries with $where and $expr are slow if there are too many documents.

Using $regex is much faster than $where, $expr.

db.usercollection.find({ 
  "name": /^[\s\S]{40,}$/, // name.length >= 40
})

or 

db.usercollection.find({ 
  "name": { "$regex": "^[\s\S]{40,}$" }, // name.length >= 40
})

This query is the same meaning with

db.usercollection.find({ 
  "$where": "this.name && this.name.length >= 40",
})

or

db.usercollection.find({ 
    "name": { "$exists": true },
    "$expr": { "$gte": [ { "$strLenCP": "$name" }, 40 ] } 
})

I tested each queries for my collection.

# find
$where: 10529.359ms
$expr: 5305.801ms
$regex: 2516.124ms

# count
$where: 10872.006ms
$expr: 2630.155ms
$regex: 158.066ms

How to get database structure in MySQL via query

To get the whole database structure as a set of CREATE TABLE statements, use mysqldump:

mysqldump database_name --compact --no-data

For single tables, add the table name after db name in mysqldump. You get the same results with SQL and SHOW CREATE TABLE:

SHOW CREATE TABLE table;

Or DESCRIBE if you prefer a column listing:

DESCRIBE table;

Take screenshots in the iOS simulator

on iOS Simulator,

Press Command + control + c or from menu : Edit>Copy Screen

open "Preview" app, Press Command + n or from menu : File> New from clipboard , then you can save command+s

For Retina, activate iOS Simulator then on menu:HardWare>Device>iPhone (Retina) and follow above process

Command + S

is the way to save on Desktop, (on new iPhone simulators, this was introduced in later simulator)

How to set data attributes in HTML elements

HTML

<div id="mydiv" data-myval="10"></div>

JS

var a = $('#mydiv').data('myval'); //getter

$('#mydiv').data('myval',20); //setter

Demo

Reference

From the reference:

jQuery itself uses the .data() method to save information under the names 'events' and 'handle', and also reserves any data name starting with an underscore ('_') for internal use.

It should be noted that jQuery's data() doesn't change the data attribute in HTML.

So, if you need to change the data attribute in HTML, you should use .attr() instead.

HTML

<div id="outer">
    <div id="mydiv" data-myval="10"></div>
</div>

?JS:

alert($('#outer').html());   // alerts <div id="mydiv" data-myval="10"> </div>
var a = $('#mydiv').data('myval'); //getter
$('#mydiv').attr("data-myval","20"); //setter
alert($('#outer').html());   //alerts <div id="mydiv" data-myval="20"> </div>

See this demo

How to change proxy settings in Android (especially in Chrome)

Found one solution for WIFI (works for Android 4.3, 4.4):

  1. Connect to WIFI network (e.g. 'Alex')
  2. Settings->WIFI
  3. Long tap on connected network's name (e.g. on 'Alex')
  4. Modify network config-> Show advanced options
  5. Set proxy settings

DOS: find a string, if found then run another script

It's been awhile since I've done anything with batch files but I think that the following works:

find /c "string" file
if %errorlevel% equ 1 goto notfound
echo found
goto done
:notfound
echo notfound
goto done
:done

This is really a proof of concept; clean up as it suits your needs. The key is that find returns an errorlevel of 1 if string is not in file. We branch to notfound in this case otherwise we handle the found case.

How to select the first, second, or third element with a given class name?

Yes, you can do this. For example, to style the td tags that make up the different columns of a table you could do something like this:

table.myClass tr > td:first-child /* First column */
{
  /* some style here */
}
table.myClass tr > td:first-child+td /* Second column */
{
  /* some style here */
}
table.myClass tr > td:first-child+td+td /* Third column */
{
  /* some style here */
}

What does the colon (:) operator do?

In your specific case,

String cardString = "";
for (PlayingCard c : this.list)  // <--
{
    cardString = cardString + c + "\n";
}

this.list is a collection (list, set, or array), and that code assigns c to each element of the collection.

So, if this.list were a collection {"2S", "3H", "4S"} then the cardString on the end would be this string:

2S
3H
4S

undefined reference to 'std::cout'

Assuming code.cpp is the source code, the following will not throw errors:

make code
./code

Here the first command compiles the code and creates an executable with the same name, and the second command runs it. There is no need to specify g++ keyword in this case.

phpMyAdmin mbstring error

Another reason for this problem is Php version. When I changed the running PHP version to 7.0.0, problem has gone.

enter image description here

get dictionary key by value

I have created a double-lookup class:

/// <summary>
/// dictionary with double key lookup
/// </summary>
/// <typeparam name="T1">primary key</typeparam>
/// <typeparam name="T2">secondary key</typeparam>
/// <typeparam name="TValue">value type</typeparam>
public class cDoubleKeyDictionary<T1, T2, TValue> {
    private struct Key2ValuePair {
        internal T2 key2;
        internal TValue value;
    }
    private Dictionary<T1, Key2ValuePair> d1 = new Dictionary<T1, Key2ValuePair>();
    private Dictionary<T2, T1> d2 = new Dictionary<T2, T1>();

    /// <summary>
    /// add item
    /// not exacly like add, mote like Dictionary[] = overwriting existing values
    /// </summary>
    /// <param name="key1"></param>
    /// <param name="key2"></param>
    public void Add(T1 key1, T2 key2, TValue value) {
        lock (d1) {
            d1[key1] = new Key2ValuePair {
                key2 = key2,
                value = value,
            };
            d2[key2] = key1;
        }
    }

    /// <summary>
    /// get key2 by key1
    /// </summary>
    /// <param name="key1"></param>
    /// <param name="key2"></param>
    /// <returns></returns>
    public bool TryGetValue(T1 key1, out TValue value) {
        if (d1.TryGetValue(key1, out Key2ValuePair kvp)) {
            value = kvp.value;
            return true;
        } else {
            value = default;
            return false;
        }
    }

    /// <summary>
    /// get key1 by key2
    /// </summary>
    /// <param name="key2"></param>
    /// <param name="key1"></param>
    /// <remarks>
    /// 2x O(1) operation
    /// </remarks>
    /// <returns></returns>
    public bool TryGetValue2(T2 key2, out TValue value) {
        if (d2.TryGetValue(key2, out T1 key1)) {
            return TryGetValue(key1, out value);
        } else {
            value = default;
            return false;
        }
    }

    /// <summary>
    /// get key1 by key2
    /// </summary>
    /// <param name="key2"></param>
    /// <param name="key1"></param>
    /// <remarks>
    /// 2x O(1) operation
    /// </remarks>
    /// <returns></returns>
    public bool TryGetKey1(T2 key2, out T1 key1) {
        return d2.TryGetValue(key2, out key1);
    }

    /// <summary>
    /// get key1 by key2
    /// </summary>
    /// <param name="key2"></param>
    /// <param name="key1"></param>
    /// <remarks>
    /// 2x O(1) operation
    /// </remarks>
    /// <returns></returns>
    public bool TryGetKey2(T1 key1, out T2 key2) {
        if (d1.TryGetValue(key1, out Key2ValuePair kvp1)) {
            key2 = kvp1.key2;
            return true;
        } else {
            key2 = default;
            return false;
        }
    }

    /// <summary>
    /// remove item by key 1
    /// </summary>
    /// <param name="key1"></param>
    public void Remove(T1 key1) {
        lock (d1) {
            if (d1.TryGetValue(key1, out Key2ValuePair kvp)) {
                d1.Remove(key1);
                d2.Remove(kvp.key2);
            }
        }
    }

    /// <summary>
    /// remove item by key 2
    /// </summary>
    /// <param name="key2"></param>
    public void Remove2(T2 key2) {
        lock (d1) {
            if (d2.TryGetValue(key2, out T1 key1)) {
                d1.Remove(key1);
                d2.Remove(key2);
            }
        }
    }

    /// <summary>
    /// clear all items
    /// </summary>
    public void Clear() {
        lock (d1) {
            d1.Clear();
            d2.Clear();
        }
    }

    /// <summary>
    /// enumerator on key1, so we can replace Dictionary by cDoubleKeyDictionary
    /// </summary>
    /// <param name="key1"></param>
    /// <returns></returns>
    public TValue this[T1 key1] {
        get => d1[key1].value;
    }

    /// <summary>
    /// enumerator on key1, so we can replace Dictionary by cDoubleKeyDictionary
    /// </summary>
    /// <param name="key1"></param>
    /// <returns></returns>
    public TValue this[T1 key1, T2 key2] {
        set {
            lock (d1) {
                d1[key1] = new Key2ValuePair {
                    key2 = key2,
                    value = value,
                };
                d2[key2] = key1;
            }
        }
    }

How do you Programmatically Download a Webpage in Java

On a Unix/Linux box you could just run 'wget' but this is not really an option if you're writing a cross-platform client. Of course this assumes that you don't really want to do much with the data you download between the point of downloading it and it hitting the disk.

PHP to search within txt file and echo the whole line

Using file() and strpos():

<?php
// What to look for
$search = 'foo';
// Read from file
$lines = file('file.txt');
foreach($lines as $line)
{
  // Check if the line contains the string we're looking for, and print if it does
  if(strpos($line, $search) !== false)
    echo $line;
}

When tested on this file:

foozah
barzah
abczah

It outputs:

foozah


Update:
To show text if the text is not found, use something like this:

<?php
$search = 'foo';
$lines = file('file.txt');
// Store true when the text is found
$found = false;
foreach($lines as $line)
{
  if(strpos($line, $search) !== false)
  {
    $found = true;
    echo $line;
  }
}
// If the text was not found, show a message
if(!$found)
{
  echo 'No match found';
}

Here I'm using the $found variable to find out if a match was found.

Use string.Contains() with switch()

string message = "This is test1";
string[] switchStrings = { "TEST1", "TEST2" };
switch (switchStrings.FirstOrDefault<string>(s => message.ToUpper().Contains(s)))
{
    case "TEST1":
        //Do work
        break;
    case "TEST2":
        //Do work
        break;
    default:
        //Do work
        break; 
}

How do I get countifs to select all non-blank cells in Excel?

In Excel 2010, You have the countifS function.

I was having issues if I was trying to count the number of cells in a range that have a non0 value.

e.g. If you had a worksheet that in the range A1:A10 had values 1, 0, 2, 3, 0 and you wanted the answer 3.

The normal function =COUNTIF(A1:A10,"<>0") would give you 8 as it is counting the blank cells as 0s.

My solution to this is to use the COUNTIFS function with the same range but multiple criteria e.g.

=COUNTIFS(A1:A10,"<>0",A1:A10,"<>")

This effectively checks if the range is non 0 and is non blank.

What is the difference between a static and const variable?

Constants can't be changed, static variables have more to do with how they are allocated and where they are accessible.

Check out this site.

How to remove "Server name" items from history of SQL Server Management Studio

Over on this duplicate question @arcticdev posted some code that will get rid of individual entries (as opposed to all entries being delete the bin file). I have wrapped it in a very ugly UI and put it here: http://ssmsmru.codeplex.com/

SLF4J: Class path contains multiple SLF4J bindings

1.Finding the conflicting jar

If it's not possible to identify the dependency from the warning, then you can use the following command to identify the conflicting jar

mvn dependency:tree

This will display the dependency tree for the project and dependencies who have pulled in another binding with the slf4j-log4j12 JAR.

  1. Resolution

Now that we know the offending dependency, all that we need to do is exclude the slf4j-log4j12 JAR from that dependency.

Ex - if spring-security dependency has also pulled in another binding with the slf4j-log4j12 JAR, Then we need to exclude the slf4j-log4j12 JAR from the spring-security dependency.

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
           <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
    </dependency>

Note - In some cases multiple dependencies have pulled in binding with the slf4j-log4j12 JAR and you don't need to add exclude for each and every dependency who has pulled in. You just have to do that add exclude dependency with the dependency which has been placed at first.

Ex -

<dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

</dependencies>

HREF="" automatically adds to current page URL (in PHP). Can't figure it out

if you want to redirect it to some other url lets google.com then make your like as happy to help other says rikin <a href="//google.com">happy to help other says rikin</a> this will remove self site url form the href.

How to install a .ipa file into my iPhone?

You need to install the provisioning profile (drag and drop it into iTunes). Then drag and drop the .ipa. Ensure you device is set to sync apps, and try again.

How to open google chrome from terminal?

UPDATE:

  1. How do I open google chrome from the terminal?

Thank you for the quick response. open http://localhost/ opened that domain in my default browser on my Mac.

  1. What alias could I use to open the current git project in the browser?

I ended up writing this alias, did the trick:

# Opens git file's localhost; ${PWD##*/} is the current directory's name
alias lcl='open "http://localhost/${PWD##*/}/"'

Thank you again!

How to Enable ActiveX in Chrome?

anyone who says activex is less secure then NPAPI is crazy. They both allow the exact same access. Yes I've written both. The only reason people think activeX is insecure is because 10+ years ago IE had default settings that allowed a remote site to auto download the plugin.

How do you use the "WITH" clause in MySQL?

I liked @Brad's answer from this thread, but wanted a way to save the results for further processing (MySql 8):

-- May need to adjust the recursion depth first
SET @@cte_max_recursion_depth = 10000 ; -- permit deeper recursion

-- Some boundaries 
set @startDate = '2015-01-01'
    , @endDate = '2020-12-31' ; 

-- Save it to a table for later use
drop table if exists tmpDates ;
create temporary table tmpDates as      -- this has to go _before_ the "with", Duh-oh! 
    WITH RECURSIVE t as (
        select @startDate as dt
      UNION
        SELECT DATE_ADD(t.dt, INTERVAL 1 DAY) FROM t WHERE DATE_ADD(t.dt, INTERVAL 1 DAY) <= @endDate
    )
    select * FROM t     -- need this to get the "with"'s results as a "result set", into the "create"
;

-- Exists?
select * from tmpDates ;

Which produces:

dt        |
----------|
2015-01-01|
2015-01-02|
2015-01-03|
2015-01-04|
2015-01-05|
2015-01-06|

How can I merge two commits into one if I already started rebase?

Since I use git cherry-pick for just about everything, to me it comes natural to do so even here.

Given that I have branchX checked out and there are two commits at the tip of it, of which I want to create one commit combining their content, I do this:

git checkout HEAD^ // Checkout the privious commit
git cherry-pick --no-commit branchX // Cherry pick the content of the second commit
git commit --amend // Create a new commit with their combined content

If i want to update branchX as well (and I suppose this is the down side of this method) I also have to:

git checkout branchX
git reset --hard <the_new_commit>

How to modify existing, unpushed commit messages?

You can use git-rebase-reword

It is designed to edit any commit (not just last) same way as commit --amend

$ git rebase-reword <commit-or-refname>

It is named after the action on rebase interactive to amend a commit: "reword". See this post and man -section interactive mode-

Examples:

$ git rebase-reword b68f560
$ git rebase-reword HEAD^

Selenium and xpath: finding a div with a class/id and verifying text inside

For class and text xpath-

//div[contains(@class,'Caption') and (text(),'Model saved')]

and

For class and id xpath-

//div[contains(@class,'gwt-HTML') and @id="alertLabel"]

IllegalMonitorStateException on wait() call

Thread.wait() call make sense inside a code that synchronizes on Thread.class object. I don't think it's what you meant.
You ask

How can I make a thread wait until it will be notified?

You can make only your current thread wait. Any other thread can be only gently asked to wait, if it agree.
If you want to wait for some condition, you need a lock object - Thread.class object is a very bad choice - it is a singleton AFAIK so synchronizing on it (except for Thread static methods) is dangerous.
Details for synchronization and waiting are already explained by Tom Hawtin. java.lang.IllegalMonitorStateException means you are trying to wait on object on which you are not synchronized - it's illegal to do so.

Unable to Connect to GitHub.com For Cloning

Open port 9418 on your firewall - it's a custom port that Git uses to communicate on and it's often not open on a corporate or private firewall.

cordova run with ios error .. Error code 65 for command: xcodebuild with args:

Try to remove and add ios again

ionic cordova platform remove ios

ionic cordova platform add ios

Worked in my case

How to redirect to another page in node.js

You should return the line that redirects

return res.redirect('/UserHomePage');