Programs & Examples On #Hybridauthprovider

how to save and read array of array in NSUserdefaults in swift?

Here is an example of reading and writing a list of objects of type SNStock that implements NSCoding - we have an accessor for the entire list, watchlist, and two methods to add and remove objects, that is addStock(stock: SNStock) and removeStock(stock: SNStock).

import Foundation

class DWWatchlistController {

  private let kNSUserDefaultsWatchlistKey: String = "dw_watchlist_key"

  private let userDefaults: NSUserDefaults

  private(set) var watchlist:[SNStock] {

    get {
      if let watchlistData : AnyObject = userDefaults.objectForKey(kNSUserDefaultsWatchlistKey) {
        if let watchlist : AnyObject = NSKeyedUnarchiver.unarchiveObjectWithData(watchlistData as! NSData) {
          return watchlist as! [SNStock]
        }
      }
      return []
    }

    set(watchlist) {
      let watchlistData = NSKeyedArchiver.archivedDataWithRootObject(watchlist)
      userDefaults.setObject(watchlistData, forKey: kNSUserDefaultsWatchlistKey)
      userDefaults.synchronize()
    }
  }

  init() {
    userDefaults = NSUserDefaults.standardUserDefaults()
  }

  func addStock(stock: SNStock) {
    var watchlist = self.watchlist
    watchlist.append(stock)
    self.watchlist = watchlist
  }

  func removeStock(stock: SNStock) {
    var watchlist = self.watchlist
    if let index = find(watchlist, stock) {
      watchlist.removeAtIndex(index)
      self.watchlist = watchlist
    }
  }

}

Remember that your object needs to implement NSCoding or else the encoding won't work. Here is what SNStock looks like:

import Foundation

class SNStock: NSObject, NSCoding
{
  let ticker: NSString
  let name: NSString

  init(ticker: NSString, name: NSString)
  {
    self.ticker = ticker
    self.name = name
  }

  //MARK: NSCoding

  required init(coder aDecoder: NSCoder) {
    self.ticker = aDecoder.decodeObjectForKey("ticker") as! NSString
    self.name = aDecoder.decodeObjectForKey("name") as! NSString
  }

  func encodeWithCoder(aCoder: NSCoder) {
    aCoder.encodeObject(ticker, forKey: "ticker")
    aCoder.encodeObject(name, forKey: "name")
  }

  //MARK: NSObjectProtocol

  override func isEqual(object: AnyObject?) -> Bool {
    if let object = object as? SNStock {
      return self.ticker == object.ticker &&
        self.name == object.name
    } else {
      return false
    }
  }

  override var hash: Int {
    return ticker.hashValue
  }
}

Hope this helps!

Git pull - Please move or remove them before you can merge

If there are too many files to delete, which is actually a case for me. You can also try the following solution:

1) fetch

2) merge with a strategy. For instance this one works for me:

git.exe merge --strategy=ours master

How do you read a file into a list in Python?

with open('C:/path/numbers.txt') as f:
    lines = f.read().splitlines()

this will give you a list of values (strings) you had in your file, with newlines stripped.

also, watch your backslashes in windows path names, as those are also escape chars in strings. You can use forward slashes or double backslashes instead.

How do I implement interfaces in python?

I invite you to explore what Python 3.8 has to offer for the subject matter in form of Structural subtyping (static duck typing) (PEP 544)

See the short description https://docs.python.org/3/library/typing.html#typing.Protocol

For the simple example here it goes like this:

from typing import Protocol

class MyShowProto(Protocol):
    def show(self):
        ...


class MyClass:
    def show(self):
        print('Hello World!')


class MyOtherClass:
    pass


def foo(o: MyShowProto):
    return o.show()

foo(MyClass())  # ok
foo(MyOtherClass())  # fails

foo(MyOtherClass()) will fail static type checks:

$ mypy proto-experiment.py 
proto-experiment.py:21: error: Argument 1 to "foo" has incompatible type "MyOtherClass"; expected "MyShowProto"
Found 1 error in 1 file (checked 1 source file)

In addition, you can specify the base class explicitly, for instance:

class MyOtherClass(MyShowProto):

but note that this makes methods of the base class actually available on the subclass, and thus the static checker will not report that a method definition is missing on the MyOtherClass. So in this case, in order to get a useful type-checking, all the methods that we want to be explicitly implemented should be decorated with @abstractmethod:

from typing import Protocol
from abc import abstractmethod

class MyShowProto(Protocol):
    @abstractmethod
    def show(self): raise NotImplementedError


class MyOtherClass(MyShowProto):
    pass


MyOtherClass()  # error in type checker

How do I parse JSON into an int?

The question is kind of old, but I get a good result creating a function to convert an object in a Json string from a string variable to an integer

function getInt(arr, prop) {
    var int;
    for (var i=0 ; i<arr.length ; i++) {
        int = parseInt(arr[i][prop])
            arr[i][prop] = int;
    }
    return arr;
  }

the function just go thru the array and return all elements of the object of your selection as an integer

CSS table-cell equal width

HTML

<div class="table">
    <div class="table_cell">Cell-1</div>
    <div class="table_cell">Cell-2 Cell-2 Cell-2 Cell-2Cell-2 Cell-2</div>
    <div class="table_cell">Cell-3Cell-3 Cell-3Cell-3 Cell-3Cell-3</div>
    <div class="table_cell">Cell-4Cell-4Cell-4 Cell-4Cell-4Cell-4 Cell-4Cell-4Cell-4Cell-4</div>
</div>?

CSS

.table{
    display:table;
    width:100%;
    table-layout:fixed;
}
.table_cell{
    display:table-cell;
    width:100px;
    border:solid black 1px;
}

DEMO.

Reading from file using read() function

Read Byte by Byte and check that each byte against '\n' if it is not, then store it into buffer
if it is '\n' add '\0' to buffer and then use atoi()

You can read a single byte like this

char c;
read(fd,&c,1);

See read()

ab load testing

Steps to set up Apache Bench(AB) on windows (IMO - Recommended).

Step 1 - Install Xampp.
Step 2 - Open CMD.
Step 3 - Go to the apache bench destination (cd C:\xampp\apache\bin) from CMD
Step 4 - Paste the command (ab -n 100 -c 10 -k -H "Accept-Encoding: gzip, deflate" http://localhost:yourport/)
Step 5 - Wait for it. Your done

How do I launch a program from command line without opening a new cmd window?

1-Open you folder that contains your application in the File Explorer. 2-Press SHIFT and Right Click in White Space. 3-Click on "Open command window here". 4-Run your application. (you can type some of the first characters of application name and press Up Arrow Key OR Down Arrow Key)

MSVCP140.dll missing

Your friend's PC is missing the runtime support DLLs for your program:

C++ - how to find the length of an integer

Most efficient code to find length of a number.. counts zeros as well, note "n" is the number to be given.

#include <iostream>
using namespace std;
int main()
{
    int n,len= 0;
    cin>>n;
while(n!=0)
    {
       len++;
       n=n/10;
    }
    cout<<len<<endl;
    return 0;
}

Open a link in browser with java button?

Use the Desktop#browse(URI) method. It opens a URI in the user's default browser.

public static boolean openWebpage(URI uri) {
    Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
    if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
        try {
            desktop.browse(uri);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return false;
}

public static boolean openWebpage(URL url) {
    try {
        return openWebpage(url.toURI());
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
    return false;
}

Environment.GetFolderPath(...CommonApplicationData) is still returning "C:\Documents and Settings\" on Vista

Output on Windows 10

Fonts: C:\Windows\Fonts
CommonStartMenu: C:\ProgramData\Microsoft\Windows\Start Menu
CommonPrograms: C:\ProgramData\Microsoft\Windows\Start Menu\Programs
CommonStartup: C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup
CommonDesktopDirectory: C:\Users\Public\Desktop
CommonApplicationData: C:\ProgramData
Windows: C:\Windows
System: C:\Windows\system32
ProgramFiles: C:\Program Files (x86)
SystemX86: C:\Windows\SysWOW64
ProgramFilesX86: C:\Program Files (x86)
CommonProgramFiles: C:\Program Files (x86)\Common Files
CommonProgramFilesX86: C:\Program Files (x86)\Common Files
CommonTemplates: C:\ProgramData\Microsoft\Windows\Templates
CommonDocuments: C:\Users\Public\Documents
CommonAdminTools: C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Administrative Tools
CommonMusic: C:\Users\Public\Music
CommonPictures: C:\Users\Public\Pictures
CommonVideos: C:\Users\Public\Videos
Resources: C:\Windows\resources
LocalizedResources:
CommonOemLinks:

Code Snippet if you want to log your own

foreach(Environment.SpecialFolder f in Enum.GetValues(typeof(Environment.SpecialFolder)))
{
    string commonAppData = Environment.GetFolderPath(f);
    Console.WriteLine("{0}: {1}", f, commonAppData);
}
Console.ReadLine();

Scanner method to get a char

Scanner sc = new Scanner (System.in)
char c = sc.next().trim().charAt(0);

calculate the mean for each column of a matrix in R

For diversity: Another way is to converts a vector function to one that works with data frames by using plyr::colwise()

set.seed(1)
m <- data.frame(matrix(sample(100, 20, replace = TRUE), ncol = 4))

plyr::colwise(mean)(m)


#   X1   X2   X3   X4
# 1 47 64.4 44.8 67.8

browser.msie error after update to jQuery 1.9.1

Update! Complete answer overhaul for new plugin!

The following plugin has been tested in all major browsers. It makes traditional use of userAgent string to re-equip jQuery.browser only if you're using jQuery version 1.9 or Greater!

It has the traditional jQuery.browser.msie type properties as well as a few new ones, including a .mobile property to help decide if user is on a mobile device.

Note: This is not a suitable replacement for feature testing. If you expect to support a specific feature on a specific device, it's still best to use traditional feature testing

_x000D_
_x000D_
/** jQuery.browser_x000D_
 * @author J.D. McKinstry (2014)_x000D_
 * @description Made to replicate older jQuery.browser command in jQuery versions 1.9+_x000D_
 * @see http://jsfiddle.net/SpYk3/wsqfbe4s/_x000D_
 *_x000D_
 * @extends jQuery_x000D_
 * @namespace jQuery.browser_x000D_
 * @example jQuery.browser.browser == 'browserNameInLowerCase'_x000D_
 * @example jQuery.browser.version_x000D_
 * @example jQuery.browser.mobile @returns BOOLEAN_x000D_
 * @example jQuery.browser['browserNameInLowerCase']_x000D_
 * @example jQuery.browser.chrome @returns BOOLEAN_x000D_
 * @example jQuery.browser.safari @returns BOOLEAN_x000D_
 * @example jQuery.browser.opera @returns BOOLEAN_x000D_
 * @example jQuery.browser.msie @returns BOOLEAN_x000D_
 * @example jQuery.browser.mozilla @returns BOOLEAN_x000D_
 * @example jQuery.browser.webkit @returns BOOLEAN_x000D_
 * @example jQuery.browser.ua @returns navigator.userAgent String_x000D_
 */_x000D_
;;(function($){var a=$.fn.jquery.split("."),b;for(b in a)a[b]=parseInt(a[b]);if(!$.browser&&(1<a[0]||9<=a[1])){a={browser:void 0,version:void 0,mobile:!1};navigator&&navigator.userAgent&&(a.ua=navigator.userAgent,a.webkit=/WebKit/i.test(a.ua),a.browserArray="MSIE Chrome Opera Kindle Silk BlackBerry PlayBook Android Safari Mozilla Nokia".split(" "),/Sony[^ ]*/i.test(a.ua)?a.mobile="Sony":/RIM Tablet/i.test(a.ua)?a.mobile="RIM Tablet":/BlackBerry/i.test(a.ua)?a.mobile="BlackBerry":/iPhone/i.test(a.ua)?_x000D_
a.mobile="iPhone":/iPad/i.test(a.ua)?a.mobile="iPad":/iPod/i.test(a.ua)?a.mobile="iPod":/Opera Mini/i.test(a.ua)?a.mobile="Opera Mini":/IEMobile/i.test(a.ua)?a.mobile="IEMobile":/BB[0-9]{1,}; Touch/i.test(a.ua)?a.mobile="BlackBerry":/Nokia/i.test(a.ua)?a.mobile="Nokia":/Android/i.test(a.ua)&&(a.mobile="Android"),/MSIE|Trident/i.test(a.ua)?(a.browser="MSIE",a.version=/MSIE/i.test(navigator.userAgent)&&0<parseFloat(a.ua.split("MSIE")[1].match(/[0-9\.]{1,}/)[0])?parseFloat(a.ua.split("MSIE")[1].match(/[0-9\.]{1,}/)[0]):_x000D_
"Edge",/Trident/i.test(a.ua)&&/rv:([0-9]{1,}[\.0-9]{0,})/.test(a.ua)&&(a.version=parseFloat(a.ua.match(/rv:([0-9]{1,}[\.0-9]{0,})/)[1].match(/[0-9\.]{1,}/)[0]))):/Chrome/.test(a.ua)?(a.browser="Chrome",a.version=parseFloat(a.ua.split("Chrome/")[1].split("Safari")[0].match(/[0-9\.]{1,}/)[0])):/Opera/.test(a.ua)?(a.browser="Opera",a.version=parseFloat(a.ua.split("Version/")[1].match(/[0-9\.]{1,}/)[0])):/Kindle|Silk|KFTT|KFOT|KFJWA|KFJWI|KFSOWI|KFTHWA|KFTHWI|KFAPWA|KFAPWI/i.test(a.ua)?(a.mobile="Kindle",_x000D_
/Silk/i.test(a.ua)?(a.browser="Silk",a.version=parseFloat(a.ua.split("Silk/")[1].split("Safari")[0].match(/[0-9\.]{1,}/)[0])):/Kindle/i.test(a.ua)&&/Version/i.test(a.ua)&&(a.browser="Kindle",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].match(/[0-9\.]{1,}/)[0]))):/BlackBerry/.test(a.ua)?(a.browser="BlackBerry",a.version=parseFloat(a.ua.split("/")[1].match(/[0-9\.]{1,}/)[0])):/PlayBook/.test(a.ua)?(a.browser="PlayBook",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].match(/[0-9\.]{1,}/)[0])):_x000D_
/BB[0-9]{1,}; Touch/.test(a.ua)?(a.browser="Blackberry",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].match(/[0-9\.]{1,}/)[0])):/Android/.test(a.ua)?(a.browser="Android",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].match(/[0-9\.]{1,}/)[0])):/Safari/.test(a.ua)?(a.browser="Safari",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].match(/[0-9\.]{1,}/)[0])):/Firefox/.test(a.ua)?(a.browser="Mozilla",a.version=parseFloat(a.ua.split("Firefox/")[1].match(/[0-9\.]{1,}/)[0])):_x000D_
/Nokia/.test(a.ua)&&(a.browser="Nokia",a.version=parseFloat(a.ua.split("Browser")[1].match(/[0-9\.]{1,}/)[0])));if(a.browser)for(var c in a.browserArray)a[a.browserArray[c].toLowerCase()]=a.browser==a.browserArray[c];$.extend(!0,$.browser={},a)}})(jQuery);_x000D_
/* - - - - - - - - - - - - - - - - - - - */_x000D_
_x000D_
var b = $.browser;_x000D_
console.log($.browser);    //    see console, working example of jQuery Plugin_x000D_
console.log($.browser.chrome);_x000D_
_x000D_
for (var x in b) {_x000D_
    if (x != 'init')_x000D_
        $('<tr />').append(_x000D_
            $('<th />', { text: x }),_x000D_
            $('<td />', { text: b[x] })_x000D_
        ).appendTo($('table'));_x000D_
}
_x000D_
table { border-collapse: collapse; }_x000D_
th, td { border: 1px solid; padding: .25em .5em; vertical-align: top; }_x000D_
th { text-align: right; }_x000D_
_x000D_
textarea { height: 500px; width: 100%; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<table></table>
_x000D_
_x000D_
_x000D_

How to highlight text using javascript

We if you also want it to be highlighted on page load, there is a new way.

just add #:~:text=Highlight%20These

try accessing this link in a new tab

https://stackoverflow.com/questions/38588721#:~:text=Highlight%20a%20text

Python: Random numbers into a list

my_randoms = [randint(n1,n2) for x in range(listsize)]

What is the standard exception to throw in Java for not supported/implemented operations?

Differentiate between the two cases you named:

Selecting last element in JavaScript array

var last = function( obj, key ) { 
    var a = obj[key];
    return a[a.length - 1];
};

last(loc, 'f096012e-2497-485d-8adb-7ec0b9352c52');

SyntaxError: Unexpected Identifier in Chrome's Javascript console

copy this line and replace in your project

var myNewString = myOldString.replace ("username", visitorName);

there is a simple problem with coma (,)

Call another rest api from my server in Spring-Boot

Create Bean for Rest Template to auto wiring the Rest Template object.

@SpringBootApplication
public class ChatAppApplication {

    @Bean
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }

    public static void main(String[] args) {
        SpringApplication.run(ChatAppApplication.class, args);
    }

}

Consume the GET/POST API by using RestTemplate - exchange() method. Below is for the post api which is defined in the controller.

@RequestMapping(value = "/postdata",method = RequestMethod.POST)
    public String PostData(){

       return "{\n" +
               "   \"value\":\"4\",\n" +
               "   \"name\":\"David\"\n" +
               "}";
    }

    @RequestMapping(value = "/post")
    public String getPostResponse(){
        HttpHeaders headers=new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        HttpEntity<String> entity=new HttpEntity<String>(headers);
        return restTemplate.exchange("http://localhost:8080/postdata",HttpMethod.POST,entity,String.class).getBody();
    }

Refer this tutorial[1]

[1] https://www.tutorialspoint.com/spring_boot/spring_boot_rest_template.htm

Is there any way to call a function periodically in JavaScript?

The setInterval() method, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. It returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval().

var intervalId = setInterval(function() {
  alert("Interval reached every 5s")
}, 5000);

// You can clear a periodic function by uncommenting:
// clearInterval(intervalId);

See more @ setInterval() @ MDN Web Docs

Can't find @Nullable inside javax.annotation.*

If you are using Gradle, you could include the dependency like this:

repositories {
    mavenCentral()
}

dependencies {
    compile group: 'com.google.code.findbugs', name: 'jsr305', version: '3.0.0'
}

Selecting fields from JSON output

Assume you stored that dictionary in a variable called values. To get id in to a variable, do:

idValue = values['criteria'][0]['id']

If that json is in a file, do the following to load it:

import json
jsonFile = open('your_filename.json', 'r')
values = json.load(jsonFile)
jsonFile.close()

If that json is from a URL, do the following to load it:

import urllib, json
f = urllib.urlopen("http://domain/path/jsonPage")
values = json.load(f)
f.close()

To print ALL of the criteria, you could:

for criteria in values['criteria']:
    for key, value in criteria.iteritems():
        print key, 'is:', value
    print ''

how to set ASPNETCORE_ENVIRONMENT to be considered for publishing an asp.net core application?

You should follow the instructions provided in the documentation, using the web.config.

<aspNetCore processPath="dotnet"
        arguments=".\MyApp.dll"
        stdoutLogEnabled="false"
        stdoutLogFile="\\?\%home%\LogFiles\aspnetcore-stdout">
  <environmentVariables>
    <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Production" />
    <environmentVariable name="CONFIG_DIR" value="f:\application_config" />
  </environmentVariables>
</aspNetCore>

Note that you can also set other environment variables as well.

The ASP.NET Core Module allows you specify environment variables for the process specified in the processPath attribute by specifying them in one or more environmentVariable child elements of an environmentVariables collection element under the aspNetCore element. Environment variables set in this section take precedence over system environment variables for the process.

Netbeans installation doesn't find JDK

This is only due to javahome path missing.

Use the command line below:--

For Windows OS- Open your command prompt

netbeans-6.5.1-windows.exe --javahome "C:\\Program Files\Java\jdk1.5.0"

For Linux OS- Open your Terminal

netbeans-6.5.1-windows.sh --javahome /usr/jdk/jdk1.6.0_04

The problem solved.

How to return a value from pthread threads in C?

if you're uncomfortable with returning addresses and have just a single variable eg. an integer value to return, you can even typecast it into (void *) before passing it, and then when you collect it in the main, again typecast it into (int). You have the value without throwing up ugly warnings.

I want to delete all bin and obj folders to force all projects to rebuild everything

Here is the answer I gave to a similar question, Simple, easy, works pretty good and does not require anything else than what you already have with Visual Studio.

As others have responded already Clean will remove all artifacts that are generated by the build. But it will leave behind everything else.

If you have some customizations in your MSBuild project this could spell trouble and leave behind stuff you would think it should have deleted.

You can circumvent this problem with a simple change to your .*proj by adding this somewhere near the end :

<Target Name="SpicNSpan"
        AfterTargets="Clean">
    <RemoveDir Directories="$(OUTDIR)"/>
</Target>

Which will remove everything in your bin folder of the current platform/configuration.

Error in Python script "Expected 2D array, got 1D array instead:"?

I was facing the same issue earlier but I have somehow found the solution, You can try reg.predict([[3300]]).

The API used to allow scalar value but now you need to give a 2D array.

Get class name using jQuery

<div id="elem" class="className"></div>

With Javascript

document.getElementById('elem').className;

With jQuery

$('#elem').attr('class');

OR

$('#elem').get(0).className;

Should Jquery code go in header or footer?

All scripts should be loaded last

In just about every case, it's best to place all your script references at the end of the page, just before </body>.

If you are unable to do so due to templating issues and whatnot, decorate your script tags with the defer attribute so that the browser knows to download your scripts after the HTML has been downloaded:

<script src="my.js" type="text/javascript" defer="defer"></script>

Edge cases

There are some edge cases, however, where you may experience page flickering or other artifacts during page load which can usually be solved by simply placing your jQuery script references in the <head> tag without the defer attribute. These cases include jQuery UI and other addons such as jCarousel or Treeview which modify the DOM as part of their functionality.


Further caveats

There are some libraries that must be loaded before the DOM or CSS, such as polyfills. Modernizr is one such library that must be placed in the head tag.

Disable autocomplete via CSS

I solved the problem by adding an fake autocomplete name for all inputs.

$("input").attr("autocomplete", "fake-name-disable-autofill");

Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

You need to use bitwise operators | instead of or and & instead of and in pandas, you can't simply use the bool statements from python.

For much complex filtering create a mask and apply the mask on the dataframe.
Put all your query in the mask and apply it.
Suppose,

mask = (df["col1"]>=df["col2"]) & (stock["col1"]<=df["col2"])
df_new = df[mask]

Cron job every three days

Run it every three days...

0 0 */3 * *

How about that?

If you want it to run on specific days of the month, like the 1st, 4th, 7th, etc... then you can just have a conditional in your script that checks for the current day of the month.

if (((date('j') - 1) % 3))
   exit();

or, as @mario points out, you can use date('k') to get the day of the year instead of doing it based on the day of the month.

How to use Tomcat 8.5.x and TomEE 7.x with Eclipse?

For Tomcat 8.5.x users

You've to change the ServerInfo.properties file of Tomcat's /lib/catalina.jar file.

ServerInfo.properties file contains the following code

server.info=Apache Tomcat/8.5.4
server.number=8.5.4.0
server.built=Jul 6 2016 08:43:30 UTC

Just open the ServerInfo.properties file by opening the catalina.jar with winrar from your Tomcat's lib folder

ServerInfo.properties file location in catalina.jar is /org/apache/catalina/util/ServerInfo.properties

Notice : shutdown the Tomcat server(if it's already opened by cmd) before doing these things otherwise your file doesn't change and your winrar shows error.

Then change the following code in ServerInfo.properties

server.info=Apache Tomcat/8.0.8.5.4
server.number=8.5.4.0
server.built=Jul 6 2016 08:43:30 UTC

Restart your eclipse(if opened). Now it'll work...

ScreenShot of eclipse

CSS Background image not loading

I found the problem was you can't use short URL for image "img/image.jpg"

you should use the full URL "http://www.website.com/img/image.jpg", yet I don't know why !!

Difference between a View's Padding and Margin

Sometimes you can achieve the same result by playing only with padding OR margin. Example :

Say View X contains view Y (aka : View Y is inside View X).

-View Y with Margin=30 OR View X with Padding=30 will achieve the same result: View Y will have an offset of 30.

What is the significance of #pragma marks? Why do we need #pragma marks?

#pragma mark is used to tag the group of methods so you may easily find and detect methods from the Jump Bar. It may help you when your code files reach about 1000 lines and you want to find methods quickly through the category from Jump box.

In a long program it becomes difficult to remember and find a method name. So pragma mark allows you to categorize methods according to the work they do. For example, you tagged some tag for Table View Protocol Methods, AlertView Methods, Init Methods, Declaration etc.

#pragma mark is the facility for XCode but it has no impact on your code. It merely helps to make it easier to find methods while coding.

How to get WooCommerce order details

Accessing direct properties and related are explained

// Get an instance of the WC_Order object
            $order = wc_get_order($order_id);
            $order_data = array(
                    'order_id' => $order->get_id(),
                    'order_number' => $order->get_order_number(),
                    'order_date' => date('Y-m-d H:i:s', strtotime(get_post($order->get_id())->post_date)),
                    'status' => $order->get_status(),
                    'shipping_total' => $order->get_total_shipping(),
                    'shipping_tax_total' => wc_format_decimal($order->get_shipping_tax(), 2),
                    'fee_total' => wc_format_decimal($fee_total, 2),
                    'fee_tax_total' => wc_format_decimal($fee_tax_total, 2),
                    'tax_total' => wc_format_decimal($order->get_total_tax(), 2),
                    'cart_discount' => (defined('WC_VERSION') && (WC_VERSION >= 2.3)) ? wc_format_decimal($order->get_total_discount(), 2) : wc_format_decimal($order->get_cart_discount(), 2),
                    'order_discount' => (defined('WC_VERSION') && (WC_VERSION >= 2.3)) ? wc_format_decimal($order->get_total_discount(), 2) : wc_format_decimal($order->get_order_discount(), 2),
                    'discount_total' => wc_format_decimal($order->get_total_discount(), 2),
                    'order_total' => wc_format_decimal($order->get_total(), 2),
                    'order_currency' => $order->get_currency(),
                    'payment_method' => $order->get_payment_method(),
                    'shipping_method' => $order->get_shipping_method(),
                    'customer_id' => $order->get_user_id(),
                    'customer_user' => $order->get_user_id(),
                    'customer_email' => ($a = get_userdata($order->get_user_id() )) ? $a->user_email : '',
                    'billing_first_name' => $order->get_billing_first_name(),
                    'billing_last_name' => $order->get_billing_last_name(),
                    'billing_company' => $order->get_billing_company(),
                    'billing_email' => $order->get_billing_email(),
                    'billing_phone' => $order->get_billing_phone(),
                    'billing_address_1' => $order->get_billing_address_1(),
                    'billing_address_2' => $order->get_billing_address_2(),
                    'billing_postcode' => $order->get_billing_postcode(),
                    'billing_city' => $order->get_billing_city(),
                    'billing_state' => $order->get_billing_state(),
                    'billing_country' => $order->get_billing_country(),
                    'shipping_first_name' => $order->get_shipping_first_name(),
                    'shipping_last_name' => $order->get_shipping_last_name(),
                    'shipping_company' => $order->get_shipping_company(),
                    'shipping_address_1' => $order->get_shipping_address_1(),
                    'shipping_address_2' => $order->get_shipping_address_2(),
                    'shipping_postcode' => $order->get_shipping_postcode(),
                    'shipping_city' => $order->get_shipping_city(),
                    'shipping_state' => $order->get_shipping_state(),
                    'shipping_country' => $order->get_shipping_country(),
                    'customer_note' => $order->get_customer_note(),
                    'download_permissions' => $order->is_download_permitted() ? $order->is_download_permitted() : 0,
            );

Additional details

  $line_items_shipping = $order->get_items('shipping');
            foreach ($line_items_shipping as $item_id => $item) {
                if (is_object($item)) {
                    if ($meta_data = $item->get_formatted_meta_data('')) :
                        foreach ($meta_data as $meta_id => $meta) :
                            if (in_array($meta->key, $line_items_shipping)) {
                                continue;
                            }
                            // html entity decode is not working preoperly
                            $shipping_items[] = implode('|', array('item:' . wp_kses_post($meta->display_key), 'value:' . str_replace('&times;', 'X', strip_tags($meta->display_value))));
                        endforeach;
                    endif;
                }
            }

            //get fee and total
            $fee_total = 0;
            $fee_tax_total = 0;

            foreach ($order->get_fees() as $fee_id => $fee) {

                $fee_items[] = implode('|', array(
                        'name:' .  html_entity_decode($fee['name'], ENT_NOQUOTES, 'UTF-8'),
                        'total:' . wc_format_decimal($fee['line_total'], 2),
                        'tax:' . wc_format_decimal($fee['line_tax'], 2),
                ));

                $fee_total += $fee['line_total'];
                $fee_tax_total += $fee['line_tax'];
            }

            // get tax items
            foreach ($order->get_tax_totals() as $tax_code => $tax) {            
                $tax_items[] = implode('|', array(
                    'rate_id:'.$tax->id,
                    'code:' . $tax_code,
                    'total:' . wc_format_decimal($tax->amount, 2),
                    'label:'.$tax->label,                
                    'tax_rate_compound:'.$tax->is_compound,
                ));
            }

            // add coupons
            foreach ($order->get_items('coupon') as $_ => $coupon_item) {

                $coupon = new WC_Coupon($coupon_item['name']);

                $coupon_post = get_post((WC()->version < '2.7.0') ? $coupon->id : $coupon->get_id());
                $discount_amount = !empty($coupon_item['discount_amount']) ? $coupon_item['discount_amount'] : 0;
                $coupon_items[] = implode('|', array(
                        'code:' . $coupon_item['name'],
                        'description:' . ( is_object($coupon_post) ? $coupon_post->post_excerpt : '' ),
                        'amount:' . wc_format_decimal($discount_amount, 2),
                ));
            }

            foreach ($order->get_refunds() as $refunded_items){
                $refund_items[] = implode('|', array(
                    'amount:' . $refunded_items->get_amount(),
            'reason:' . $refunded_items->get_reason(),
                    'date:'. date('Y-m-d H-i-s',strtotime((WC()->version < '2.7.0') ? $refunded_items->date_created : $refunded_items->get_date_created())),
                ));
            }

PHP How to find the time elapsed since a date time?

Convert [saved_date] to timestamp. Get current timestamp.

current timestamp - [saved_date] timestamp.

Then you can format it with date();

You can normally convert most date formats to timestamps with the strtotime() function.

How to show progress bar while loading, using ajax

_x000D_
_x000D_
$(document).ready(function () { _x000D_
 $(document).ajaxStart(function () {_x000D_
        $('#wait').show();_x000D_
    });_x000D_
    $(document).ajaxStop(function () {_x000D_
        $('#wait').hide();_x000D_
    });_x000D_
    $(document).ajaxError(function () {_x000D_
        $('#wait').hide();_x000D_
    });   _x000D_
});
_x000D_
<div id="wait" style="display: none; width: 100%; height: 100%; top: 100px; left: 0px; position: fixed; z-index: 10000; text-align: center;">_x000D_
            <img src="../images/loading_blue2.gif" width="45" height="45" alt="Loading..." style="position: fixed; top: 50%; left: 50%;" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Postgres Error: More than one row returned by a subquery used as an expression

This error means that the SELECT store_key FROM store query has returned two or more rows in the SERVER1 database. If you would like to update all customers, use a join instead of a scalar = operator. You need a condition to "connect" customers to store items in order to do that.

If you wish to update all customer_ids to the same store_key, you need to supply a WHERE clause to the remotely executed SELECT so that the query returns a single row.

fatal error LNK1104: cannot open file 'libboost_system-vc110-mt-gd-1_51.lib'

2>LINK : fatal error LNK1104: cannot open file 'libboost_regex-vc120-mt-sgd-1_55.lib

In my case, bootstrap/bjam was not available (libraries were precompiled and committed to SCM) on old inherited project. Libraries did not have VC or BOOST versioning in their filenames eg: libboost_regex-mt-sgd.lib, however Processed /DEFAULTLIB:libboost_regex-vc120-mt-sgd-1_55.lib was somehow triggered automatically.

Fixed by manually adding the non-versioned filename to:

<AdditionalDependencies>$(DK_BOOST)\lib64\libboost_regex-mt-sgd.lib</AdditionalDependencies>

and blacklisting the ...vc120-mt-sgd-1_55.lib in

<IgnoreSpecificDefaultLibraries>libboost_regex-vc120-mt-sgd-1_55.lib</IgnoreSpecificDefaultLibraries>

How to extract URL parameters from a URL with Ruby or Rails?

I think you want to turn any given URL string into a HASH?

You can try http://www.ruby-doc.org/stdlib/libdoc/cgi/rdoc/classes/CGI.html#M000075

require 'cgi'

CGI::parse('param1=value1&param2=value2&param3=value3')

returns

{"param1"=>["value1"], "param2"=>["value2"], "param3"=>["value3"]}

Triggering change detection manually in Angular

I was able to update it with markForCheck()

Import ChangeDetectorRef

import { ChangeDetectorRef } from '@angular/core';

Inject and instantiate it

constructor(private ref: ChangeDetectorRef) { 
}

Finally mark change detection to take place

this.ref.markForCheck();

Here's an example where markForCheck() works and detectChanges() don't.

https://plnkr.co/edit/RfJwHqEVJcMU9ku9XNE7?p=preview

EDIT: This example doesn't portray the problem anymore :( I believe it might be running a newer Angular version where it's fixed.

(Press STOP/RUN to run it again)

Indent multiple lines quickly in vi

I use block-mode visual selection:

  • Go to the front of the block to move (at the top or bottom).
  • Press Ctrl + V to enter visual block mode.
  • Navigate to select a column in front of the lines.
  • Press I (Shift + I) to enter insert mode.
  • Type some spaces.
  • Press Esc. All lines will shift.

This is not a uni-tasker. It works:

  • In the middle of lines.
  • To insert any string on all lines.
  • To change a column (use c instead of I).
  • yank, delete, substitute, etc...

Android Service needs to run always (Never pause or stop)

I found a simple and clear way of keeping the Service running always.

This guy has explained it so clearly and have used a good algorithm. His approach is to send a Broadcast when the service is about to get killed and then use it to restart the service.

You should check it out: http://fabcirablog.weebly.com/blog/creating-a-never-ending-background-service-in-android

Struct Constructor in C++?

One more example but using this keyword when setting value in constructor:

#include <iostream>

using namespace std;

struct Node {
    int value;

    Node(int value) {
        this->value = value;
    }

    void print()
    {
        cout << this->value << endl;
    }
};

int main() {
    Node n = Node(10);
    n.print();

    return 0;
}

Compiled with GCC 8.1.0.

Euclidean distance of two vectors

If you want to use less code, you can also use the norm in the stats package (the 'F' stands for Forbenius, which is the Euclidean norm):

norm(matrix(x1-x2), 'F')

While this may look a bit neater, it's not faster. Indeed, a quick test on very large vectors shows little difference, though so12311's method is slightly faster. We first define:

set.seed(1234)
x1 <- rnorm(300000000)
x2 <- rnorm(300000000)

Then testing for time yields the following:

> system.time(a<-sqrt(sum((x1-x2)^2)))
user  system elapsed 
1.02    0.12    1.18 
> system.time(b<-norm(matrix(x1-x2), 'F'))
user  system elapsed 
0.97    0.33    1.31 

Measuring text height to be drawn on Canvas ( Android )

You could use the android.text.StaticLayout class to specify the bounds required and then call getHeight(). You can draw the text (contained in the layout) by calling its draw(Canvas) method.

Add one day to date in javascript

If you don't mind using a library, DateJS (https://github.com/abritinthebay/datejs/) would make this fairly easy. You would probably be better off with one of the answers using vanilla JavaScript however, unless you're going to take advantage of some other DateJS features like parsing of unusually-formatted dates.

If you're using DateJS a line like this should do the trick:

Date.parse(startdate).add(1).days();

You could also use MomentJS which has similar features (http://momentjs.com/), however I'm not as familiar with it.

optional parameters in SQL Server stored proc?

Yes, it is. Declare parameter as so:

@Sort varchar(50) = NULL

Now you don't even have to pass the parameter in. It will default to NULL (or whatever you choose to default to).

Adding values to Arraylist

in the first you don't define the type that will be held and linked within your arraylist construct

this is the preferred method to do so, you define the type of list and the ide will handle the rest

in the third one you will better just define List for shorter code

Deleting array elements in JavaScript - delete vs splice

Because delete only removes the object from the element in the array, the length of the array won't change. Splice removes the object and shortens the array.

The following code will display "a", "b", "undefined", "d"

myArray = ['a', 'b', 'c', 'd']; delete myArray[2];

for (var count = 0; count < myArray.length; count++) {
    alert(myArray[count]);
}

Whereas this will display "a", "b", "d"

myArray = ['a', 'b', 'c', 'd']; myArray.splice(2,1);

for (var count = 0; count < myArray.length; count++) {
    alert(myArray[count]);
}

Jquery If radio button is checked

$("input").bind('click', function(e){
   if ($(this).val() == 'Yes') {
        $("body").append('whatever');
   }
});

How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?

You can simply get it in the format you want.

String date = String.valueOf(android.text.format.DateFormat.format("dd-MM-yyyy", new java.util.Date()));

SQL Server 2008 R2 Express permissions -- cannot create database or modify users

I followed the steps in killthrush's answer and to my surprise it did not work. Logging in as sa I could see my Windows domain user and had made them a sysadmin, but when I tried logging in with Windows auth I couldn't see my login under logins, couldn't create databases, etc. Then it hit me. That login was probably tied to another domain account with the same name (with some sort of internal/hidden ID that wasn't right). I had left this organization a while back and then came back months later. Instead of re-activating my old account (which they might have deleted) they created a new account with the same domain\username and a new internal ID. Using sa I deleted my old login, re-added it with the same name and added sysadmin. I logged back in with Windows Auth and everything looks as it should. I can now see my logins (and others) and can do whatever I need to do as a sysadmin using my Windows auth login.

Java rounding up to an int using Math.ceil

int total = (int) Math.ceil( (double)157/ (double) 32);

How to get object length

So one does not have to find and replace the Object.keys method, another approach would be this code early in the execution of the script:

if(!Object.keys)
{
  Object.keys = function(obj)
  {
    return $.map(obj, function(v, k)
    {
      return k;
    });
  };
 }

Fastest way to convert string to integer in PHP

I personally feel casting is the prettiest.

$iSomeVar = (int) $sSomeOtherVar;

Should a string like 'Hello' be sent, it will be cast to integer 0. For a string such as '22 years old', it will be cast to integer 22. Anything it can't parse to a number becomes 0.

If you really do NEED the speed, I guess the other suggestions here are correct in assuming that coercion is the fastest.

How to remove a TFS Workspace Mapping?

I ran into the same problem, and was able to fix it by manually deleting all the files in the TFS cache, located here:

%LocalAppData%\Microsoft\Team Foundation\3.0\Cache

or 4.0, 5.0, etc.

How to expand 'select' option width after the user wants to select an option

I fixed my problem with the following code:

_x000D_
_x000D_
<div style="width: 180px; overflow: hidden;">_x000D_
   <select style="width: auto;" name="abc" id="10">_x000D_
     <option value="-1">AAAAAAAAAAA</option>_x000D_
     <option value="123">123</option>_x000D_
   </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Hope it helps!

How to use nan and inf in C?

I usually use

#define INFINITY (1e999)

or

const double INFINITY = 1e999

which works at least in IEEE 754 contexts because the highest representable double value is roughly 1e308. 1e309 would work just as well, as would 1e99999, but three nines is sufficient and memorable. Since this is either a double literal (in the #define case) or an actual Inf value, it will remain infinite even if you're using 128-bit (“long double”) floats.

Angular 4: no component factory found,did you add it to @NgModule.entryComponents?

  1. entryComponents is vital. Above answers on this are correct.

But...

  1. If you're providing a service that opens the modal (a common pattern) and your module that defines the dialog component is not loaded in AppModule, you need to change providedIn: 'root' to providedIn: MyModule. As general good practice you should just use the providedIn: SomeModule for all dialog services that are in modules.

How do I iterate over a JSON structure?

Copied and pasted from http://www.w3schools.com, there is no need for the JQuery overhead.

var person = {fname:"John", lname:"Doe", age:25};

var text = "";
var x;
for (x in person) {
    text += person[x];
}

RESULT: John Doe 25

Difference between `constexpr` and `const`

According to book of "The C++ Programming Language 4th Editon" by Bjarne Stroustrup
const: meaning roughly ‘‘I promise not to change this value’’ (§7.5). This is used primarily to specify interfaces, so that data can be passed to functions without fear of it being modified.
The compiler enforces the promise made by const.
constexpr: meaning roughly ‘‘to be evaluated at compile time’’ (§10.4). This is used primarily to specify constants, to allow
For example:

const int dmv = 17; // dmv is a named constant
int var = 17; // var is not a constant
constexpr double max1 = 1.4*square(dmv); // OK if square(17) is a constant expression
constexpr double max2 = 1.4*square(var); // error : var is not a constant expression
const double max3 = 1.4*square(var); //OK, may be evaluated at run time
double sum(const vector<double>&); // sum will not modify its argument (§2.2.5)
vector<double> v {1.2, 3.4, 4.5}; // v is not a constant
const double s1 = sum(v); // OK: evaluated at run time
constexpr double s2 = sum(v); // error : sum(v) not constant expression

For a function to be usable in a constant expression, that is, in an expression that will be evaluated by the compiler, it must be defined constexpr.
For example:

constexpr double square(double x) { return x*x; }


To be constexpr, a function must be rather simple: just a return-statement computing a value. A constexpr function can be used for non-constant arguments, but when that is done the result is not a constant expression. We allow a constexpr function to be called with non-constant-expression arguments in contexts that do not require constant expressions, so that we don’t hav e to define essentially the same function twice: once for constant expressions and once for variables.
In a few places, constant expressions are required by language rules (e.g., array bounds (§2.2.5, §7.3), case labels (§2.2.4, §9.4.2), some template arguments (§25.2), and constants declared using constexpr). In other cases, compile-time evaluation is important for performance. Independently of performance issues, the notion of immutability (of an object with an unchangeable state) is an important design concern (§10.4).

Spring Test & Security: How to mock authentication?

Add in pom.xml:

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-test</artifactId>
        <version>4.0.0.RC2</version>
    </dependency>

and use org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors for authorization request. See the sample usage at https://github.com/rwinch/spring-security-test-blog (https://jira.spring.io/browse/SEC-2592).

Update:

4.0.0.RC2 works for spring-security 3.x. For spring-security 4 spring-security-test become part of spring-security (http://docs.spring.io/spring-security/site/docs/4.0.x/reference/htmlsingle/#test, version is the same).

Setting Up is changed: http://docs.spring.io/spring-security/site/docs/4.0.x/reference/htmlsingle/#test-mockmvc

public void setup() {
    mvc = MockMvcBuilders
            .webAppContextSetup(context)
            .apply(springSecurity())  
            .build();
}

Sample for basic-authentication: http://docs.spring.io/spring-security/site/docs/4.0.x/reference/htmlsingle/#testing-http-basic-authentication.

What is the best way to create and populate a numbers table?

If you're just doing this in either SQL Server Management Studio or sqlcmd.exe, you can use the fact that the batch separator allows you to repeat the batch:

CREATE TABLE Number (N INT IDENTITY(1,1) PRIMARY KEY NOT NULL);
GO

INSERT INTO Number DEFAULT VALUES;
GO 100000

This will insert 100000 records into the Numbers table using the default value of the next identity.

It's slow. It compares to METHOD 1 in @KM.'s answer, which is the slowest of the examples. However, it's about as code light as it gets. You could speed it up somewhat by adding the primary key constraint after the insert batch.

CSS: image link, change on hover

If you give generally give a span the property display:block, it'll then behave like a div, i.e you can set width and height.

You can also skip the div or span and just set the a the to display: block and apply the backgound style to it.

<a href="" class="myImage"><!----></a>


    <style>
      .myImage {display: block; width: 160px; height: 20px; margin:0 0 10px 0; background: url(image.png) center top no-repeat;}
.myImage:hover{background-image(image_hover.png);}
    </style>

How to use onClick event on react Link component?

You should use this:

<Link to={this.props.myroute} onClick={hello}>Here</Link>

Or (if method hello lays at this class):

<Link to={this.props.myroute} onClick={this.hello}>Here</Link>

Update: For ES6 and latest if you want to bind some param with click method, you can use this:

    const someValue = 'some';  
....  
    <Link to={this.props.myroute} onClick={() => hello(someValue)}>Here</Link>

How do I display a MySQL error in PHP for a long query that depends on the user input?

Try something like this:

$link = @new mysqli($this->host, $this->user, $this->pass)
$statement = $link->prepare($sqlStatement);
                if(!$statement)
                {
                    $this->debug_mode('query', 'error', '#Query Failed<br/>' . $link->error);
                    return false;
                }

How to move Docker containers between different hosts?

What eventually worked for me, after lot's of confusing manuals and confusing tutorials, since Docker is obviously at time of my writing at peek of inflated expectations, is:

  1. Save the docker image into archive:
    docker save image_name > image_name.tar
  2. copy on another machine
  3. on that other docker machine, run docker load in a following way:
    cat image_name.tar | docker load

Export and import, as proposed in another answers does not export ports and variables, which might be required for your container to run. And you might end up with stuff like "No command specified" etc... When you try to load it on another machine.

So, difference between save and export is that save command saves whole image with history and metadata, while export command exports only files structure (without history or metadata).

Needless to say is that, if you already have those ports taken on the docker hyper-visor you are doing import, by some other docker container, you will end-up in conflict, and you will have to reconfigure exposed ports.

Note: In order to move data with docker, you might be having persistent storage somewhere, which should also be moved alongside with containers.

Remap values in pandas column with a dict

Given map is faster than replace (@JohnE's solution) you need to be careful with Non-Exhaustive mappings where you intend to map specific values to NaN. The proper method in this case requires that you mask the Series when you .fillna, else you undo the mapping to NaN.

import pandas as pd
import numpy as np

d = {'m': 'Male', 'f': 'Female', 'missing': np.NaN}
df = pd.DataFrame({'gender': ['m', 'f', 'missing', 'Male', 'U']})

keep_nan = [k for k,v in d.items() if pd.isnull(v)]
s = df['gender']

df['mapped'] = s.map(d).fillna(s.mask(s.isin(keep_nan)))

    gender  mapped
0        m    Male
1        f  Female
2  missing     NaN
3     Male    Male
4        U       U

use regular expression in if-condition in bash

Adding this solution with grep and basic sh builtins for those interested in a more portable solution (independent of bash version; also works with plain old sh, on non-Linux platforms etc.)

# GLOB matching
gg=svm-grid-ch    
case "$gg" in
   *grid*) echo $gg ;;
esac

# REGEXP    
if echo "$gg" | grep '^....grid*' >/dev/null ; then echo $gg ; fi    
if echo "$gg" | grep '....grid*' >/dev/null ; then echo $gg ; fi    
if echo "$gg" | grep 's...grid*' >/dev/null ; then echo $gg ; fi    

# Extended REGEXP
if echo "$gg" | egrep '(^....grid*|....grid*|s...grid*)' >/dev/null ; then
  echo $gg
fi    

Some grep incarnations also support the -q (quiet) option as an alternative to redirecting to /dev/null, but the redirect is again the most portable.

Failed to resolve: com.android.support:cardview-v7:26.0.0 android

Google's new Maven repo is required for the latest support library that is compatible with Android 8.0. Just update your Google's Maven repository like below:

To add them to your build, add maven.google.com to the Maven repositories in your module-level build.gradle file:

repositories {
    maven {
        url 'https://maven.google.com'
        // Alternative URL is 'https://dl.google.com/dl/android/maven2/'
    }
}

Alternative you can update build.gradle file like this:

    repositories {
        jcenter()
        google()
    }

Then add the desired library to your dependencies block. For example, the cardview library looks like this:

dependencies {
    compile 'com.android.support:cardview-v7:26.1.0'
}

Looping through the content of a file in Bash

A few more things not covered by other answers:

Reading from a delimited file

# ':' is the delimiter here, and there are three fields on each line in the file
# IFS set below is restricted to the context of `read`, it doesn't affect any other code
while IFS=: read -r field1 field2 field3; do
  # process the fields
  # if the line has less than three fields, the missing fields will be set to an empty string
  # if the line has more than three fields, `field3` will get all the values, including the third field plus the delimiter(s)
done < input.txt

Reading from the output of another command, using process substitution

while read -r line; do
  # process the line
done < <(command ...)

This approach is better than command ... | while read -r line; do ... because the while loop here runs in the current shell rather than a subshell as in the case of the latter. See the related post A variable modified inside a while loop is not remembered.

Reading from a null delimited input, for example find ... -print0

while read -r -d '' line; do
  # logic
  # use a second 'read ... <<< "$line"' if we need to tokenize the line
done < <(find /path/to/dir -print0)

Related read: BashFAQ/020 - How can I find and safely handle file names containing newlines, spaces or both?

Reading from more than one file at a time

while read -u 3 -r line1 && read -u 4 -r line2; do
  # process the lines
  # note that the loop will end when we reach EOF on either of the files, because of the `&&`
done 3< input1.txt 4< input2.txt

Based on @chepner's answer here:

-u is a bash extension. For POSIX compatibility, each call would look something like read -r X <&3.

Reading a whole file into an array (Bash versions earlier to 4)

while read -r line; do
    my_array+=("$line")
done < my_file

If the file ends with an incomplete line (newline missing at the end), then:

while read -r line || [[ $line ]]; do
    my_array+=("$line")
done < my_file

Reading a whole file into an array (Bash versions 4x and later)

readarray -t my_array < my_file

or

mapfile -t my_array < my_file

And then

for line in "${my_array[@]}"; do
  # process the lines
done

Related posts:

Jquery set radio button checked, using id and class selectors

"...by a class and a div."

I assume when you say "div" you mean "id"? Try this:

$('#test2.test1').prop('checked', true);

No need to muck about with your [attributename=value] style selectors because id has its own format as does class, and they're easily combined although given that id is supposed to be unique it should be enough on its own unless your meaning is "select that element only if it currently has the specified class".

Or more generally to select an input where you want to specify a multiple attribute selector:

$('input:radio[class=test1][id=test2]').prop('checked', true);

That is, list each attribute with its own square brackets.

Note that unless you have a pretty old version of jQuery you should use .prop() rather than .attr() for this purpose.

How do I set path while saving a cookie value in JavaScript?

See https://developer.mozilla.org/en/DOM/document.cookie for more documentation:

 setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {  
     if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/.test(sKey)) { return; }  
     var sExpires = "";  
     if (vEnd) {  
       switch (typeof vEnd) {  
         case "number": sExpires = "; max-age=" + vEnd; break;  
         case "string": sExpires = "; expires=" + vEnd; break;  
         case "object": if (vEnd.hasOwnProperty("toGMTString")) { sExpires = "; expires=" + vEnd.toGMTString(); } break;  
       }  
     }  
     document.cookie = escape(sKey) + "=" + escape(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");  
   }

Trying Gradle build - "Task 'build' not found in root project"

You didn't do what you're being asked to do.

What is asked:

I have to execute ../gradlew build

What you do

cd ..
gradlew build

That's not the same thing.

The first one will use the gradlew command found in the .. directory (mdeinum...), and look for the build file to execute in the current directory, which is (for example) chapter1-bookstore.

The second one will execute the gradlew command found in the current directory (mdeinum...), and look for the build file to execute in the current directory, which is mdeinum....

So the build file executed is not the same.

Html.DropdownListFor selected value not being set

Your code has some conceptual issues:

First,

@Html.DropDownListFor(n => n.OrderTemplates, new SelectList(Model.OrderTemplates, "OrderTemplateId", "OrderTemplateName", 1), "Please select an order template")

When using DropDownListFor, the first parameter is the property where your selected value is stored once you submit the form. So, in your case, you should have a SelectedOrderId as part of your model or something like that, in order to use it in this way:

@Html.DropDownListFor(n => n.SelectedOrderId, new SelectList(Model.OrderTemplates, "OrderTemplateId", "OrderTemplateName", 1), "Please select an order template")

Second,

Aside from using ViewBag, that is not wrong but there are better ways (put that information in the ViewModel instead), there is a "little bug" (or an unspected behavior) when your ViewBag property, where you are holding the SelectList, is the same name of the property where you put the selected value. To avoid this, just use another name when naming the property holding the list of items.

Some code I would use if I were you to avoid this issues and write better MVC code:

Viewmodel:

public class MyViewModel{
   public int SelectedOrderId {get; set;}
   public SelectList OrderTemplates {get; set;}

   // Other properties you need in your view
}

Controller:

public ActionResult MyAction(){
   var model = new MyViewModel();
   model.OrderTemplates = new SelectList(db.OrderTemplates, "OrderTemplateId", "OrderTemplateName", 1);
   //Other initialization code

   return View(model);
}

In your View:

@Html.DropDownListFor(n => n.SelectedOrderId, Model.OrderTemplates, "Please select an order template")

Resetting Select2 value in dropdown with reset button

to remove all option value

$("#id").empty();

DataTrigger where value is NOT null?

Compare with null (As Michael Noonan said):

<Style>
    <Style.Triggers>
       <DataTrigger Binding="{Binding SomeProperty}" Value="{x:Null}">
           <Setter Property="Visibility" Value="Collapsed" />
        </DataTrigger>
     </Style.Triggers>
</Style>

Compare with not null (without a converter):

<Style>
    <Setter Property="Visibility" Value="Collapsed" />
    <Style.Triggers>
       <DataTrigger Binding="{Binding SomeProperty}" Value="{x:Null}">
           <Setter Property="Visibility" Value="Visible" />
        </DataTrigger>
     </Style.Triggers>
</Style>

Number of days between two dates in Joda-Time

public static int getDifferenceIndays(long timestamp1, long timestamp2) {
    final int SECONDS = 60;
    final int MINUTES = 60;
    final int HOURS = 24;
    final int MILLIES = 1000;
    long temp;
    if (timestamp1 < timestamp2) {
        temp = timestamp1;
        timestamp1 = timestamp2;
        timestamp2 = temp;
    }
    Calendar startDate = Calendar.getInstance(TimeZone.getDefault());
    Calendar endDate = Calendar.getInstance(TimeZone.getDefault());
    endDate.setTimeInMillis(timestamp1);
    startDate.setTimeInMillis(timestamp2);
    if ((timestamp1 - timestamp2) < 1 * HOURS * MINUTES * SECONDS * MILLIES) {
        int day1 = endDate.get(Calendar.DAY_OF_MONTH);
        int day2 = startDate.get(Calendar.DAY_OF_MONTH);
        if (day1 == day2) {
            return 0;
        } else {
            return 1;
        }
    }
    int diffDays = 0;
    startDate.add(Calendar.DAY_OF_MONTH, diffDays);
    while (startDate.before(endDate)) {
        startDate.add(Calendar.DAY_OF_MONTH, 1);
        diffDays++;
    }
    return diffDays;
}

How do I install the yaml package for Python?

Type in pip3 install yaml or like Connor pip3 install strictyaml

How to view the assembly behind the code using Visual C++?

In Visual C++ the project options under, Output Files I believe has an option for outputing the ASM listing with source code. So you will see the C/C++ source code and the resulting ASM all in the same file.

How do I calculate percentiles with python/numpy?

check for scipy.stats module:

 scipy.stats.scoreatpercentile

Warning: date_format() expects parameter 1 to be DateTime

This may help

$formattedweddingdate =date('d-m-Y',strtotime($weddingdate));

Canvas width and height in HTML5

Thank you very much! Finally I solved the blurred pixels problem with this code:

<canvas id="graph" width=326 height=240 style='width:326px;height:240px'></canvas>

With the addition of the 'half-pixel' does the trick to unblur lines.

How to escape special characters of a string with single backslashes

Utilize the output of built-in repr to deal with \r\n\t and process the output of re.escape is what you want:

re.escape(repr(a)[1:-1]).replace('\\\\', '\\')

How to run regasm.exe from command line other than Visual Studio command prompt?

You don't need the directory on your path. You could put it on your path, but you don't NEED to do that.
If you are calling regasm rarely, or calling it from a batch file, you may find it is simpler to just invoke regasm via the fully-qualified pathname on the exe, eg:

c:\Windows\Microsoft.NET\Framework\v2.0.50727\regasm.exe   MyAssembly.dll

Memory address of an object in C#

When you free that handle, the garbage collector is free to move the memory that was pinned. If you have a pointer to memory that's supposed to be pinned, and you un-pin that memory, then all bets are off. That this worked at all in 3.5 was probably just by luck. The JIT compiler and the runtime for 4.0 probably do a better job of object lifetime analysis.

If you really want to do this, you can use a try/finally to prevent the object from being un-pinned until after you've used it:

public static string Get(object a)
{
    GCHandle handle = GCHandle.Alloc(a, GCHandleType.Pinned);
    try
    {
        IntPtr pointer = GCHandle.ToIntPtr(handle);
        return "0x" + pointer.ToString("X");
    }
    finally
    {
        handle.Free();
    }
}

insert data into database using servlet and jsp in eclipse

Same problem fetch main problem in PreparedStatement use simple statement then you successfully insert record same use below.

String  st2="insert into 
user(gender,name,address,telephone,fax,email,
     destination,sdate,edate,Participant,hcategory,
     Culture,Nature,People,Cities,Beaches,Festivals,username,password) 
values('"+gender+"','"+name+"','"+address+"','"+phone+"','"+fax+"',
       '"+email+"','"+desti+"','"+sdate+"','"+edate+"','"+parti+"',
       '"+hotel+"','"+chk1+"','"+chk2+"','"+chk3+"','"+chk4+"',
       '"+chk5+"','"+chk6+"','"+user+"','"+password+"')";


int i=stm.executeUpdate(st2);

Git: How to reset a remote Git repository to remove all commits?

First, follow the instructions in this question to squash everything to a single commit. Then make a forced push to the remote:

$ git push origin +master

And optionally delete all other branches both locally and remotely:

$ git push origin :<branch>
$ git branch -d <branch>

Abstraction vs Encapsulation in Java

Abstraction is about identifying commonalities and reducing features that you have to work with at different levels of your code.

e.g. I may have a Vehicle class. A Car would derive from a Vehicle, as would a Motorbike. I can ask each Vehicle for the number of wheels, passengers etc. and that info has been abstracted and identified as common from Cars and Motorbikes.

In my code I can often just deal with Vehicles via common methods go(), stop() etc. When I add a new Vehicle type later (e.g. Scooter) the majority of my code would remain oblivious to this fact, and the implementation of Scooter alone worries about Scooter particularities.

Can a shell script set environment variables of the calling shell?

This works — it isn't what I'd use, but it 'works'. Let's create a script teredo to set the environment variable TEREDO_WORMS:

#!/bin/ksh
export TEREDO_WORMS=ukelele
exec $SHELL -i

It will be interpreted by the Korn shell, exports the environment variable, and then replaces itself with a new interactive shell.

Before running this script, we have SHELL set in the environment to the C shell, and the environment variable TEREDO_WORMS is not set:

% env | grep SHELL
SHELL=/bin/csh
% env | grep TEREDO
%

When the script is run, you are in a new shell, another interactive C shell, but the environment variable is set:

% teredo
% env | grep TEREDO
TEREDO_WORMS=ukelele
%

When you exit from this shell, the original shell takes over:

% exit
% env | grep TEREDO
%

The environment variable is not set in the original shell's environment. If you use exec teredo to run the command, then the original interactive shell is replaced by the Korn shell that sets the environment, and then that in turn is replaced by a new interactive C shell:

% exec teredo
% env | grep TEREDO
TEREDO_WORMS=ukelele
%

If you type exit (or Control-D), then your shell exits, probably logging you out of that window, or taking you back to the previous level of shell from where the experiments started.

The same mechanism works for Bash or Korn shell. You may find that the prompt after the exit commands appears in funny places.


Note the discussion in the comments. This is not a solution I would recommend, but it does achieve the stated purpose of a single script to set the environment that works with all shells (that accept the -i option to make an interactive shell). You could also add "$@" after the option to relay any other arguments, which might then make the shell usable as a general 'set environment and execute command' tool. You might want to omit the -i if there are other arguments, leading to:

#!/bin/ksh
export TEREDO_WORMS=ukelele
exec $SHELL "${@-'-i'}"

The "${@-'-i'}" bit means 'if the argument list contains at least one argument, use the original argument list; otherwise, substitute -i for the non-existent arguments'.

How to run iPhone emulator WITHOUT starting Xcode?

I created an automator app based on @trojanfoe's answer so you can launch iOS Simulator directly from your Dock https://github.com/tsdexter/ios-simulator-expo-utilities/

How do I create a dictionary with keys from a list and values defaulting to (say) zero?

d = dict.fromkeys(a, 0)

a is the list, 0 is the default value. Pay attention not to set the default value to some mutable object (i.e. list or dict), because it will be one object used as value for every key in the dictionary (check here for a solution for this case). Numbers/strings are safe.

Error: Cannot find module 'gulp-sass'

Those who are getting this error, please downgrade the Node.js you are using.

  • Step 1 :

    Uninstall the one you are using and install the version you prefer. I installed v6.12.3. My previous Node.js version was v9.4.0.

  • Step 2 :

    Download Node.js.

Hope this will work.

How to decrease prod bundle size?

Firstly, vendor bundles are huge simply because Angular 2 relies on a lot of libraries. Minimum size for Angular 2 app is around 500KB (250KB in some cases, see bottom post).
Tree shaking is properly used by angular-cli.
Do not include .map files, because used only for debugging. Moreover, if you use hot replacement module, remove it to lighten vendor.

To pack for production, I personnaly use Webpack (and angular-cli relies on it too), because you can really configure everything for optimization or debugging.
If you want to use Webpack, I agree it is a bit tricky a first view, but see tutorials on the net, you won't be disappointed.
Else, use angular-cli, which get the job done really well.

Using Ahead-of-time compilation is mandatory to optimize apps, and shrink Angular 2 app to 250KB.

Here is a repo I created (github.com/JCornat/min-angular) to test minimal Angular bundle size, and I obtain 384kB. I am sure there is easy way to optimize it.

Talking about big apps, using the AngularClass/angular-starter configuration, the same as in the repo above, my bundle size for big apps (150+ components) went from 8MB (4MB without map files) to 580kB.

Pointer arithmetic for void pointer in C

cast it to a char pointer an increment your pointer forward x bytes ahead.

How to Execute a Python File in Notepad ++?

I wish people here would post steps instead of just overall concepts. I eventually got the cmd /k version to work.

The step-by-step instructions are:

  1. In NPP, click on the menu item: Run
  2. In the submenu, click on: Run
  3. In the Run... dialog box, in the field The Program to Run, delete any existing text and type in: cmd /K "$(FULL_CURRENT_PATH)" The /K is optional, it keeps open the window created when the script runs, if you want that.
  4. Hit the Save... button.
  5. The Shortcut dialogue box opens; fill it out if you want a keyboard shortcut (there's a note saying "This will disable the accelerator" whatever that is, so maybe you don't want to use the keyboard shortcut, though it probably doesn't hurt to assign one when you don't need an accelerator). Somewhere I think you have to tell NPP where the Python.exe file is (e.g., for me: C:\Python33\python.exe). I don't know where or how you do this, but in trying various things here, I was able to do that--I don't recall which attempt did the trick.

What is the difference between char s[] and char *s?

char *str = "Hello";

The above sets str to point to the literal value "Hello" which is hard-coded in the program's binary image, which is flagged as read-only in memory, means any change in this String literal is illegal and that would throw segmentation faults.

char str[] = "Hello";

copies the string to newly allocated memory on the stack. Thus making any change in it is allowed and legal.

means str[0] = 'M';

will change the str to "Mello".

For more details, please go through the similar question:

Why do I get a segmentation fault when writing to a string initialized with "char *s" but not "char s[]"?

How to remove all line breaks from a string

This will replace the line break by empty space.

someText = someText.replace(/(\r\n|\n|\r)/gm,"");

Read more on this article.

How to pass parameters to a partial view in ASP.NET MVC?

Just:

@Html.Partial("PartialName", Model);

Center image in table td in CSS

<table style="width:100%;">
<tbody ><tr><td align="center">
<img src="axe.JPG" />
</td>
</tr>
</tbody>
</table>

or

td
{
    text-align:center;
}

in the CSS file

How should I do integer division in Perl?

Eg 9 / 4 = 2.25

int(9) / int(4) = 2

9 / 4 - remainder / deniminator = 2

9 /4 - 9 % 4 / 4 = 2

Want to upgrade project from Angular v5 to Angular v6

simply run the following command:

ng update

note: this will not update globally.

What is the PostgreSQL equivalent for ISNULL()

How do I emulate the ISNULL() functionality ?

SELECT (Field IS NULL) FROM ...

If file exists then delete the file

IF both POS_History_bim_data_*.zip and POS_History_bim_data_*.zip.trg exists in  Y:\ExternalData\RSIDest\ Folder then Delete File Y:\ExternalData\RSIDest\Target_slpos_unzip_done.dat

Best way to encode text data for XML in Java?

Note: Your question is about escaping, not encoding. Escaping is using <, etc. to allow the parser to distinguish between "this is an XML command" and "this is some text". Encoding is the stuff you specify in the XML header (UTF-8, ISO-8859-1, etc).

First of all, like everyone else said, use an XML library. XML looks simple but the encoding+escaping stuff is dark voodoo (which you'll notice as soon as you encounter umlauts and Japanese and other weird stuff like "full width digits" (&#FF11; is 1)). Keeping XML human readable is a Sisyphus' task.

I suggest never to try to be clever about text encoding and escaping in XML. But don't let that stop you from trying; just remember when it bites you (and it will).

That said, if you use only UTF-8, to make things more readable you can consider this strategy:

  • If the text does contain '<', '>' or '&', wrap it in <![CDATA[ ... ]]>
  • If the text doesn't contain these three characters, don't warp it.

I'm using this in an SQL editor and it allows the developers to cut&paste SQL from a third party SQL tool into the XML without worrying about escaping. This works because the SQL can't contain umlauts in our case, so I'm safe.

Get selected value of a dropdown's item using jQuery

use either of these codes

$('#dropDownId :selected').text();

OR

$('#dropDownId').text();

Batch file to delete files older than N days

Have a look at my answer to a similar question:

REM del_old.bat
REM usage: del_old MM-DD-YYY
for /f "tokens=*" %%a IN ('xcopy *.* /d:%1 /L /I null') do if exist %%~nxa echo %%~nxa >> FILES_TO_KEEP.TXT
for /f "tokens=*" %%a IN ('xcopy *.* /L /I /EXCLUDE:FILES_TO_KEEP.TXT null') do if exist "%%~nxa" del "%%~nxa"

This deletes files older than a given date. I'm sure it can be modified to go back seven days from the current date.

update: I notice that HerbCSO has improved on the above script. I recommend using his version instead.

data type not understood

Try:

mmatrix = np.zeros((nrows, ncols))

Since the shape parameter has to be an int or sequence of ints

http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html

Otherwise you are passing ncols to np.zeros as the dtype.

Node.js Error: connect ECONNREFUSED

Sometimes it may occur, if there is any database connection in your code but you did not start the database server yet.

Im my case i have some piece of code to connect with mongodb

mongoose.connect("mongodb://localhost:27017/demoDb");

after i started the mongodb server with the command mongod this error is gone

Fixed header, footer with scrollable content

If you're targeting browsers supporting flexible boxes you could do the following.. http://jsfiddle.net/meyertee/AH3pE/

HTML

<div class="container">
    <header><h1>Header</h1></header>
    <div class="body">Body</div>
    <footer><h3>Footer</h3></footer>
</div>

CSS

.container {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    flex-wrap: nowrap;
}

header {
    flex-shrink: 0;
}
.body{
    flex-grow: 1;
    overflow: auto;
    min-height: 2em;
}
footer{
    flex-shrink: 0;
}

Update:
See "Can I use" for browser support of flexible boxes.

Where should I put the log4j.properties file?

There are many ways to do it:

Way1: If you are trying in maven project without Using PropertyConfigurator

First: check for resources directory at scr/main

  if available,
       then: create a .properties file and add all configuration details.
  else
       then: create a directory named resources and a file with .properties     
write your configuration code/details.

follows the screenshot:

![enter image description here

Way2: If you are trying with Properties file for java/maven project Use PropertyConfigurator

Place properties file anywhere in project and give the correct path. say: src/javaLog4jProperties/log4j.properties

static{

 PropertyConfigurator.configure("src/javaLog4jProperties/log4j.properties");

}

enter image description here

Way3: If you are trying with xml on java/maven project Use DOMConfigurator

Place properties file anywhere in project and give correct path. say: src/javaLog4jProperties/log4j.xml

static{

 DOMConfigurator.configure("src/javaLog4jProperties/log4j.xml");

}

enter image description here

Execution sequence of Group By, Having and Where clause in SQL Server?

This is the SQL Order of execution of a Query,

enter image description here

You can check order of execution with examples from this article.

For you question below lines might be helpful and directly got from this article.

  1. GROUP BY --> The remaining rows after the WHERE constraints are applied are then grouped based on common values in the column specified in the GROUP BY clause. As a result of the grouping, there will only be as many rows as there are unique values in that column. Implicitly, this means that you should only need to use this when you have aggregate functions in your query.
  1. HAVING --> If the query has a GROUP BY clause, then the constraints in the HAVING clause are then applied to the grouped rows, discard the grouped rows that don't satisfy the constraint. Like the WHERE clause, aliases are also not accessible from this step in most databases.

References:-

ALTER TABLE DROP COLUMN failed because one or more objects access this column

In addition to accepted answer, if you're using Entity Migrations for updating database, you should add this line at the beggining of the Up() function in your migration file:

Sql("alter table dbo.CompanyTransactions drop constraint [df__CompanyTr__Creat__0cdae408];");

You can find the constraint name in the error at nuget packet manager console which starts with FK_dbo.

Difference between links and depends_on in docker_compose.yml

The post needs an update after the links option is deprecated.

Basically, links is no longer needed because its main purpose, making container reachable by another by adding environment variable, is included implicitly with network. When containers are placed in the same network, they are reachable by each other using their container name and other alias as host.

For docker run, --link is also deprecated and should be replaced by a custom network.

docker network create mynet
docker run -d --net mynet --name container1 my_image
docker run -it --net mynet --name container1 another_image

depends_on expresses start order (and implicitly image pulling order), which was a good side effect of links.

Change icons of checked and unchecked for Checkbox for Android

This may be achieved by using AppCompatCheckBox. You can use app:buttonCompat="@drawable/selector_drawable" to change the selector.

It's working with PNGs, but I didn't find a way for it to work with Vector Drawables.

Javascript return number of days,hours,minutes,seconds between two dates

Short and flexible with support for negative values, although by using two comma expressions :)

function timeUnitsBetween(startDate, endDate) {
  let delta = Math.abs(endDate - startDate) / 1000;
  const isNegative = startDate > endDate ? -1 : 1;
  return [
    ['days', 24 * 60 * 60],
    ['hours', 60 * 60],
    ['minutes', 60],
    ['seconds', 1]
  ].reduce((acc, [key, value]) => (acc[key] = Math.floor(delta / value) * isNegative, delta -= acc[key] * isNegative * value, acc), {});
}

Example:

timeUnitsBetween(new Date("2019-02-11T02:12:03+00:00"), new Date("2019-02-11T01:00:00+00:00"));
// { days: -0, hours: -1, minutes: -12, seconds: -3 }

Inspired by RienNeVaPlu?s solution.

How can I capitalize the first letter of each word in a string?

Capitalize string with non-uniform spaces

I would like to add to @Amit Gupta's point of non-uniform spaces:

From the original question, we would like to capitalize every word in the string s = 'the brown fox'. What if the string was s = 'the brown fox' with non-uniform spaces.

def solve(s):
    # If you want to maintain the spaces in the string, s = 'the brown      fox'
    # Use s.split(' ') instead of s.split().
    # s.split() returns ['the', 'brown', 'fox']
    # while s.split(' ') returns ['the', 'brown', '', '', '', '', '', 'fox']
    capitalized_word_list = [word.capitalize() for word in s.split(' ')]
    return ' '.join(capitalized_word_list)

Where can I download Eclipse Android bundle?

Try www.eclipse.org/downloads/packages/eclipse-android-developers-includes-incubating-components/neonrc3

Javascript how to split newline

_x000D_
_x000D_
(function($) {_x000D_
  $(document).ready(function() {_x000D_
    $('#data').click(function(e) {_x000D_
      e.preventDefault();_x000D_
      $.each($("#keywords").val().split("\n"), function(e, element) {_x000D_
        alert(element);_x000D_
      });_x000D_
    });_x000D_
  });_x000D_
})(jQuery);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<textarea id="keywords">Hello_x000D_
World</textarea>_x000D_
<input id="data" type="button" value="submit">
_x000D_
_x000D_
_x000D_

HTML -- two tables side by side

Depending on your content and space, you can use floats or inline display:

<table style="display: inline-block;">

<table style="float: left;">

Check it out here: http://jsfiddle.net/SM769/

Documentation

Is it possible to specify the schema when connecting to postgres with JDBC?

As of version 9.4, you can use the currentSchema parameter in your connection string.

For example:

jdbc:postgresql://localhost:5432/mydatabase?currentSchema=myschema

Start systemd service after specific service?

After= dependency is only effective when service including After= and service included by After= are both scheduled to start as part of your boot up.

Ex:

a.service
[Unit]
After=b.service

This way, if both a.service and b.service are enabled, then systemd will order b.service after a.service.

If I am not misunderstanding, what you are asking is how to start b.service when a.service starts even though b.service is not enabled.

The directive for this is Wants= or Requires= under [Unit].

website.service
[Unit]
Wants=mongodb.service
After=mongodb.service

The difference between Wants= and Requires= is that with Requires=, a failure to start b.service will cause the startup of a.service to fail, whereas with Wants=, a.service will start even if b.service fails. This is explained in detail on the man page of .unit.

Java Compare Two List's object values?

Logic should be something like:

  1. First step: For class MyData implements Comparable interface, override the compareTo method as per the per object requirement.

  2. Second step: When it comes to list comparison (after checking for nulls), 2.1 Check the size of both lists, if equal returns true else return false, continue to object iteration 2.2 If step 2.1 returns true, iterate over elements from both lists and invoke something like,

    listA.get(i).compareTo(listB.get(i))

This will be as per the code mentioned in step-1.

In Typescript, what is the ! (exclamation mark / bang) operator when dereferencing a member?

That's the non-null assertion operator. It is a way to tell the compiler "this expression cannot be null or undefined here, so don't complain about the possibility of it being null or undefined." Sometimes the type checker is unable to make that determination itself.

It is explained here:

A new ! post-fix expression operator may be used to assert that its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact. Specifically, the operation x! produces a value of the type of x with null and undefined excluded. Similar to type assertions of the forms <T>x and x as T, the ! non-null assertion operator is simply removed in the emitted JavaScript code.

I find the use of the term "assert" a bit misleading in that explanation. It is "assert" in the sense that the developer is asserting it, not in the sense that a test is going to be performed. The last line indeed indicates that it results in no JavaScript code being emitted.

How to make the HTML link activated by clicking on the <li>?

a {
  display: block;
  position: relative;
}

I think that is all you need.

Understanding the map function

map doesn't relate to a Cartesian product at all, although I imagine someone well versed in functional programming could come up with some impossible to understand way of generating a one using map.

map in Python 3 is equivalent to this:

def map(func, iterable):
    for i in iterable:
        yield func(i)

and the only difference in Python 2 is that it will build up a full list of results to return all at once instead of yielding.

Although Python convention usually prefers list comprehensions (or generator expressions) to achieve the same result as a call to map, particularly if you're using a lambda expression as the first argument:

[func(i) for i in iterable]

As an example of what you asked for in the comments on the question - "turn a string into an array", by 'array' you probably want either a tuple or a list (both of them behave a little like arrays from other languages) -

 >>> a = "hello, world"
 >>> list(a)
['h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd']
>>> tuple(a)
('h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd')

A use of map here would be if you start with a list of strings instead of a single string - map can listify all of them individually:

>>> a = ["foo", "bar", "baz"]
>>> list(map(list, a))
[['f', 'o', 'o'], ['b', 'a', 'r'], ['b', 'a', 'z']]

Note that map(list, a) is equivalent in Python 2, but in Python 3 you need the list call if you want to do anything other than feed it into a for loop (or a processing function such as sum that only needs an iterable, and not a sequence). But also note again that a list comprehension is usually preferred:

>>> [list(b) for b in a]
[['f', 'o', 'o'], ['b', 'a', 'r'], ['b', 'a', 'z']]

How to clear textarea on click?

Your JavaScript:

function clearContents(element) {
  element.value = '';
}

And your HTML:

<textarea onfocus="clearContents(this);">Please describe why</textarea>

I assume you'll want to make this a little more robust, so as to not wipe user input when focusing a second time. Here are five related discussions & articles.

And here's the (much better) idea that David Dorward refers to in comments above:

<label for="explanation">Please describe why</label>
<textarea name="explanation" id="explanation"></textarea>

Clearing coverage highlighting in Eclipse

On 4.2 eclipse it seems to be impossible to remove the eCobertura highlights. Sadly eCobertura plugins seems to be not maintained anymore. However if you start writing into the class, its gone. So type a space, and then undo, and its gone.

Delete all data rows from an Excel table (apart from the first)

Your code can be narrowed down to

Sub DeleteTableRows(ByRef Table As ListObject)
    On Error Resume Next
    '~~> Clear Header Row `IF` it exists
    Table.DataBodyRange.Rows(1).ClearContents
    '~~> Delete all the other rows `IF `they exist
    Table.DataBodyRange.Offset(1, 0).Resize(Table.DataBodyRange.Rows.Count - 1, _
    Table.DataBodyRange.Columns.Count).Rows.Delete
    On Error GoTo 0
End Sub

Edit:

On a side note, I would add proper error handling if I need to intimate the user whether the first row or the other rows were deleted or not

Try-catch block in Jenkins pipeline script

This answer worked for me:

pipeline {
  agent any
  stages {
    stage("Run unit tests"){
      steps {
        script {
          try {
            sh  '''
              # Run unit tests without capturing stdout or logs, generates cobetura reports
              cd ./python
              nosetests3 --with-xcoverage --nocapture --with-xunit --nologcapture --cover-package=application
              cd ..
              '''
          } finally {
            junit 'nosetests.xml'
          }
        }
      }
    }
    stage ('Speak') {
      steps{
        echo "Hello, CONDITIONAL"
      }
    }
  }
}

PHP's array_map including keys

Based on eis's answer, here's what I eventually did in order to avoid messing the original array:

$test_array = array("first_key" => "first_value",
                    "second_key" => "second_value");

$result_array = array();
array_walk($test_array, 
           function($a, $b) use (&$result_array) 
           { $result_array[] = "$b loves $a"; }, 
           $result_array);
var_dump($result_array);

Java Constructor Inheritance

Because a (super)class must have complete control over how it is constructed. If the programmer decides that it doesn't make sense to provide a default (no args) constructor as part of the class's contract, then the compiler should not provide one.

Logcat not displaying my log calls

Easiest way:

Check in your logcat window - TOP RIGHT corner PAUSE button || (Pause receiving new logcat messages)

Few clicks + eventually restart eclipse (usually works in my case)

Adding IN clause List to a JPA Query

public List<DealInfo> getDealInfos(List<String> dealIds) {
        String queryStr = "SELECT NEW com.admin.entity.DealInfo(deal.url, deal.url, deal.url, deal.url, deal.price, deal.value) " + "FROM Deal AS deal where deal.id in :inclList";
        TypedQuery<DealInfo> query = em.createQuery(queryStr, DealInfo.class);
        query.setParameter("inclList", dealIds);
        return query.getResultList();
    }

Works for me with JPA 2, Jboss 7.0.2

Xcode "Build and Archive" from command line

try xctool, it is a replacement for Apple's xcodebuild that makes it easier to build and test iOS and Mac products. It's especially helpful for continuous integration. It has a few extra features:

  1. Runs the same tests as Xcode.app.
  2. Structured output of build and test results.
  3. Human-friendly, ANSI-colored output.

No.3 is extremely useful. I don't if anyone can read the console output of xcodebuild, I can't, usually it gave me one line with 5000+ characters. Even harder to read than a thesis paper.

xctool: https://github.com/facebook/xctool

Have a div cling to top of screen if scrolled down past it

Use position:fixed; and set the top:0;left:0;right:0;height:100px; and you should be able to have it "stick" to the top of the page.

<div style="position:fixed;top:0;left:0;right:0;height:100px;">Some buttons</div>

jQuery : select all element with custom attribute

As described by the link I've given in comment, this

$('p[MyTag]').each(function(index) {
  document.write(index + ': ' + $(this).text() + "<br>");});

works (playable example).

How do you overcome the svn 'out of date' error?

Are you sure you've checked out the head and not a lower revision? Also, have you done an update to make sure you've got the latest version?

There's a discussion about this on http://svn.haxx.se/users/archive-2007-01/0170.shtml.

Kotlin unresolved reference in IntelliJ

For me, it was due to the project missing Gradle Libraries in its project structure.

Just add in build.gradle: apply plugin: 'idea'

And then run: $ gradle idea

After that gradle rebuilds dependencies libraries and the references are recognized!

Of Countries and their Cities

This service returns Countries (name,code) and cities for any country as REST, SErvice. You can also download database and sample REST service

http://tecorange.com/content/world-countries-and-cities-restjson-service-12-months-subscription

How do I display the value of a Django form field in a template?

This was a feature request that got fixed in Django 1.3.

Here's the bug: https://code.djangoproject.com/ticket/10427

Basically, if you're running something after 1.3, in Django templates you can do:

{{ form.field.value|default_if_none:"" }}

Or in Jinja2:

{{ form.field.value()|default("") }}

Note that field.value() is a method, but in Django templates ()'s are omitted, while in Jinja2 method calls are explicit.

If you want to know what version of Django you're running, it will tell you when you do the runserver command.

If you are on something prior to 1.3, you can probably use the fix posted in the above bug: https://code.djangoproject.com/ticket/10427#comment:24

HTML/CSS--Creating a banner/header

For the image that is not showing up. Open the image in the Image editor and check the type you are probably name it as "gif" but its saved in a different format that's one reason that the browser is unable to render it and it is not showing.
For the image stretching issue please specify the actual width and height dimensions in #banner instead of width: 100%; height: 200px that you have specified.

Regular expression - starting and ending with a character string

Example: ajshdjashdjashdlasdlhdlSTARTasdasdsdaasdENDaknsdklansdlknaldknaaklsdn

1) START\w*END return: STARTasdasdsdaasdEND - will give you words between START and END

2) START\d*END return: START12121212END - will give you numbers between START and END

3) START\d*_\d*END return: START1212_1212END - will give you numbers between START and END having _

Java Multithreading concept and join() method

The JVM and the underlying OS have considerable freedom when scheduling things. The fact that you get all the way to "Waiting for threads to finish" before you see the output from individual threads may simply mean that thread start-up takes a bit longer (i.e. it takes some time between the moment when a thread becomes "alive" and when the run() method actually starts executing). You could conceivably see thread output sooner but it's not guaranteed either way.

As for join(), it only guarantees that whatever is after it will only happen once the thread you are joining is done. So when you have three join() calls in a row it doesn't mean the threads should end in a particular order. It simply means that you will wait for ob1 first. Once ob1 finishes, ob2 and ob3 may be still running or they may already be finished. If they are finished, your other join() calls will return immediately.

synchronized is used specifically when multiple threads access the same object and make changes to it. A synchronized block is guaranteed never to be executed by two threads simultaneously - i.e. the thread that executes it has the synchronized object all to itself.

How to kill a nodejs process in Linux?

In order to kill use: killall -9 /usr/bin/node

To reload use: killall -12 /usr/bin/node

Finding Variable Type in JavaScript

In JavaScript everything is an object

console.log(type of({}))  //Object
console.log(type of([]))  //Object

To get Real type , use this

console.log(Object.prototype.toString.call({}))   //[object Object]
console.log(Object.prototype.toString.call([]))   //[object Array]

Hope this helps

Multiple radio button groups in one form

Just do one thing, We need to set the name property for the same types. for eg.

Try below:

<form>
    <div id="group1">
        <input type="radio" value="val1" name="group1">
        <input type="radio" value="val2" name="group1">
    </div>
</form>

And also we can do it in angular1,angular 2 or in jquery also.

<div *ngFor="let option of question.options; index as j">
<input type="radio" name="option{{j}}" value="option{{j}}" (click)="checkAnswer(j+1)">{{option}}
</div>  

How to find my php-fpm.sock?

I faced this same issue on CentOS 7 years later

Posting hoping that it may help others...

Steps:

FIRST, configure the php-fpm settings:

-> systemctl stop php-fpm.service

-> cd /etc/php-fpm.d

-> ls -hal (should see a www.conf file)

-> cp www.conf www.conf.backup (back file up just in case)

-> vi www.conf

-> :/listen = (to get to the line we need to change)

-> i (to enter VI's text insertion mode)

-> change from listen = 127.0.0.1:9000 TO listen = /var/run/php-fpm/php-fpm.sock

-> Esc then :/listen.owner (to find it) then i (to change)

-> UNCOMMENT the listen.owner = nobody AND listen.group = nobody lines

-> Hit Esc then type :/user = then i

-> change user = apache TO user = nginx

-> AND change group = apache TO group = nginx

-> Hit Esc then :wq (to save and quit)

-> systemctl start php-fpm.service (now you will have a php-fpm.sock file)

SECOND, you configure your server {} block in your /etc/nginx/nginx.conf file. Then run:systemctl restart nginx.service

FINALLY, create a new .php file in your /usr/share/nginx/html directory for your Nginx server to serve up via the internet browser as a test.

-> vi /usr/share/nginx/html/mytest.php

-> type o

-> <?php echo date("Y/m/d-l"); ?> (PHP page will print date and day in browser)

-> Hit Esc

-> type :wq (to save and quite VI editor)

-> open up a browser and go to: http://yourDomainOrIPAddress/mytest.php (you should see the date and day printed)

In c# is there a method to find the max of 3 numbers?

You could try this code:

private float GetBrightestColor(float r, float g, float b) { 
    if (r > g && r > b) {
        return r;
    } else if (g > r && g > b) { 
        return g;
    } else if (b > r && b > g) { 
        return b;
    }
}

How do I check if an element is hidden in jQuery?

Example:

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  if ($("#checkme:hidden").length) {_x000D_
    console.log('Hidden');_x000D_
  }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="checkme" class="product" style="display:none">_x000D_
  <span class="itemlist"><!-- Shows Results for Fish --></span> Category:Fish_x000D_
  <br>Product: Salmon Atlantic_x000D_
  <br>Specie: Salmo salar_x000D_
  <br>Form: Steaks_x000D_
</div>
_x000D_
_x000D_
_x000D_

Undefined symbols for architecture i386

A bit late to the party but might be valuable to someone with this error..

I just straight copied a bunch of files into an Xcode project, if you forget to add them to your projects Build Phases you will get the error "Undefined symbols for architecture i386". So add your implementation files to Compile Sources, and Xib files to Copy Bundle Resources.

The error was telling me that there was no link to my classes simply because they weren't included in the Compile Sources, quite obvious really but may save someone a headache.

How to embed HTML into IPython output?

to do this in a loop, you can do:

display(HTML("".join([f"<a href='{url}'>{url}</a></br>" for url in urls])))

This essentially creates the html text in a loop, and then uses the display(HTML()) construct to display the whole string as HTML

How can I delete an item from an array in VB.NET?

Yes, you can delete an element from an array. Here is an extension method that moves the elements as needed, then resizes the array one shorter:

' Remove element at index "index". Result is one element shorter.
' Similar to List.RemoveAt, but for arrays.
<System.Runtime.CompilerServices.Extension()> _
Public Sub RemoveAt(Of T)(ByRef a() As T, ByVal index As Integer)
    ' Move elements after "index" down 1 position.
    Array.Copy(a, index + 1, a, index, UBound(a) - index)
    ' Shorten by 1 element.
    ReDim Preserve a(UBound(a) - 1)
End Sub

Usage examples (assuming array starting with index 0):

Dim a() As String = {"Albert", "Betty", "Carlos", "David"}
a.RemoveAt(0)    ' Remove first element => {"Betty", "Carlos", "David"}
a.RemoveAt(1)    ' Remove second element => {"Betty", "David"}
a.RemoveAt(UBound(a))    ' Remove last element => {"Betty"}

Removing First or Last element is common, so here are convenience routines for doing so (I like code that expresses my intent more readably):

<System.Runtime.CompilerServices.Extension()> _
Public Sub DropFirstElement(Of T)(ByRef a() As T)
    a.RemoveAt(0)
End Sub

<System.Runtime.CompilerServices.Extension()> _
Public Sub DropLastElement(Of T)(ByRef a() As T)
    a.RemoveAt(UBound(a))
End Sub

Usage:

a.DropFirstElement()
a.DropLastElement()

And as Heinzi said, if you find yourself doing this, instead use List(Of T), if possible. List already has "RemoveAt" subroutine, and other routines useful for inserting/deleting elements.

Delete all documents from index/type without deleting type

(Reputation not high enough to comment) The second part of John Petrone's answer works - no query needed. It will delete the type and all documents contained in that type, but that can just be re-created whenever you index a new document to that type.

Just to clarify: $ curl -XDELETE 'http://localhost:9200/twitter/tweet'

Note: this does delete the mapping! But as mentioned before, it can be easily re-mapped by creating a new document.

INSERT INTO ... SELECT FROM ... ON DUPLICATE KEY UPDATE

MySQL will assume the part before the equals references the columns named in the INSERT INTO clause, and the second part references the SELECT columns.

INSERT INTO lee(exp_id, created_by, location, animal, starttime, endtime, entct, 
                inact, inadur, inadist, 
                smlct, smldur, smldist, 
                larct, lardur, lardist, 
                emptyct, emptydur)
SELECT id, uid, t.location, t.animal, t.starttime, t.endtime, t.entct, 
       t.inact, t.inadur, t.inadist, 
       t.smlct, t.smldur, t.smldist, 
       t.larct, t.lardur, t.lardist, 
       t.emptyct, t.emptydur 
FROM tmp t WHERE uid=x
ON DUPLICATE KEY UPDATE entct=t.entct, inact=t.inact, ...

SimpleXml to string

You can use the SimpleXMLElement::asXML() method to accomplish this:

$string = "<element><child>Hello World</child></element>";
$xml = new SimpleXMLElement($string);

// The entire XML tree as a string:
// "<element><child>Hello World</child></element>"
$xml->asXML();

// Just the child node as a string:
// "<child>Hello World</child>"
$xml->child->asXML();

How do you receive a url parameter with a spring controller mapping

You have a lot of variants for using @RequestParam with additional optional elements, e.g.

@RequestParam(required = false, defaultValue = "someValue", value="someAttr") String someAttr

If you don't put required = false - param will be required by default.

defaultValue = "someValue" - the default value to use as a fallback when the request parameter is not provided or has an empty value.

If request and method param are the same - you don't need value = "someAttr"

What is "git remote add ..." and "git push origin master"?

Git remote add origin:

It centralises your source code to the other projects.It is developed based on Linux, complete open source and make your code useful to the other git users.we call it as reference

Pushes your code into git repository using remote url of the git hub.

HTML5 Canvas background image

Canvas does not using .png file as background image. changing to other file extensions like gif or jpg works fine.

jQuery UI autocomplete with item and id

Auto Complete Text box binding using Jquery

  ## HTML Code For Text Box and For Handling UserID use Hidden value ##
  <div class="ui-widget">
@Html.TextBox("userName")  
    @Html.Hidden("userId")
    </div>

Below Library's is Required

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

Jquery Script

$("#userName").autocomplete(
{

    source: function (request,responce)
    {
        debugger
        var Name = $("#userName").val();

        $.ajax({
            url: "/Dashboard/UserNames",
            method: "POST",
            contentType: "application/json",
            data: JSON.stringify({
                Name: Name

            }),
            dataType: 'json',
            success: function (data) {
                debugger
                responce(data);
            },
            error: function (err) {
                alert(err);
            }
        });
    },
    select: function (event, ui) {

        $("#userName").val(ui.item.label); // display the selected text
        $("#userId").val(ui.item.value); // save selected id to hidden input
        return false;
    }
})

Return data Should be below format


 label = u.person_full_name,
 value = u.user_id

Git list of staged files

The best way to do this is by running the command:

git diff --name-only --cached

When you check the manual you will likely find the following:

--name-only
    Show only names of changed files.

And on the example part of the manual:

git diff --cached
    Changes between the index and your current HEAD.

Combined together you get the changes between the index and your current HEAD and Show only names of changed files.

Update: --staged is also available as an alias for --cached above in more recent git versions.

Vertical line using XML drawable

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

    <item
        android:bottom="-3dp"
        android:left="-3dp"
        android:top="-3dp">

        <shape android:shape="rectangle">
            <solid android:color="@color/colorPrimary" />
            <stroke
                android:width="2dp"
                android:color="#1fc78c" />
        </shape>

    </item>

</layer-list>

Check if value exists in column in VBA

try this:

If Application.WorksheetFunction.CountIf(RangeToSearchIn, ValueToSearchFor) = 0 Then
Debug.Print "none"
End If

Use CASE statement to check if column exists in table - SQL Server

SELECT *
FROM ...
WHERE EXISTS(SELECT 1 
        FROM sys.columns c
        WHERE c.[object_id] = OBJECT_ID('dbo.Tags')
            AND c.name = 'ModifiedByUser'
    )

Node.js - How to send data from html to express

Using http.createServer is very low-level and really not useful for creating web applications as-is.

A good framework to use on top of it is Express, and I would seriously suggest using it. You can install it using npm install express.

When you have, you can create a basic application to handle your form:

var express = require('express');
var bodyParser = require('body-parser');
var app     = express();

//Note that in version 4 of express, express.bodyParser() was
//deprecated in favor of a separate 'body-parser' module.
app.use(bodyParser.urlencoded({ extended: true })); 

//app.use(express.bodyParser());

app.post('/myaction', function(req, res) {
  res.send('You sent the name "' + req.body.name + '".');
});

app.listen(8080, function() {
  console.log('Server running at http://127.0.0.1:8080/');
});

You can make your form point to it using:

<form action="http://127.0.0.1:8080/myaction" method="post">

The reason you can't run Node on port 80 is because there's already a process running on that port (which is serving your index.html). You could use Express to also serve static content, like index.html, using the express.static middleware.

Using PowerShell to remove lines from a text file if it contains a string

Suppose you want to write that in the same file, you can do as follows:

Set-Content -Path "C:\temp\Newtext.txt" -Value (get-content -Path "c:\Temp\Newtext.txt" | Select-String -Pattern 'H\|159' -NotMatch)

See line breaks and carriage returns in editor

You can view break lines using gedit editor.

First, if you don't have installed:

sudo apt-get install gedit

Now, install gedit plugins:

sudo apt-get install gedit-plugins

and select Draw Spaces plugin, enter on Preferences, and chose Draw new lines

enter image description here

enter image description here

Using VSCode you can install Line endings extension.

Sublime Text 3 has a plugin called RawLineEdit that will display line endings and allow the insertion of arbitrary line-ending type

shift + ctrl + p and start type the name of the plugin, and toggle to show line ending.

How to atomically delete keys matching a pattern using Redis

For those who were having trouble parsing other answers:

eval "for _,k in ipairs(redis.call('keys','key:*:pattern')) do redis.call('del',k) end" 0

Replace key:*:pattern with your own pattern and enter this into redis-cli and you are good to go.

Credit lisco from: http://redis.io/commands/del

How do MySQL indexes work?

Basically an index is a map of all your keys that is sorted in order. With a list in order, then instead of checking every key, it can do something like this:

1: Go to middle of list - is higher or lower than what I'm looking for?

2: If higher, go to halfway point between middle and bottom, if lower, middle and top

3: Is higher or lower? Jump to middle point again, etc.

Using that logic, you can find an element in a sorted list in about 7 steps, instead of checking every item.

Obviously there are complexities, but that gives you the basic idea.

Django {% with %} tags within {% if %} {% else %} tags?

if you want to stay DRY, use an include.

{% if foo %}
  {% with a as b %}
    {% include "snipet.html" %}
  {% endwith %} 
{% else %}
  {% with bar as b %}
    {% include "snipet.html" %}
  {% endwith %} 
{% endif %}

or, even better would be to write a method on the model that encapsulates the core logic:

def Patient(models.Model):
    ....
    def get_legally_responsible_party(self):
       if self.age > 18:
          return self
       else:
          return self.parent

Then in the template:

{% with patient.get_legally_responsible_party as p %}
  Do html stuff
{% endwith %} 

Then in the future, if the logic for who is legally responsible changes you have a single place to change the logic -- far more DRY than having to change if statements in a dozen templates.

How to Right-align flex item?

margin-left: auto works well. But clean flex box solution would be space-between in the main class. Space between works well if there is two or more elements. I have added a solution for single element as well.

_x000D_
_x000D_
.main { display: flex; justify-content: space-between; }
.a, .b, .c { background: #efefef; border: 1px solid #999; padding: 0.25rem; margin: 0.25rem;}
.b { flex: 1; text-align: center; }

.c-wrapper {
  display: flex;
  flex: 1;
  justify-content: flex-end;
}

.c-wrapper2 {
  display: flex;
  flex: 1;
  flex-flow: row-reverse;
}
_x000D_
<div class="main">
    <div class="a"><a href="#">Home</a></div>
    <div class="b"><a href="#">Some title centered</a></div>
    <div class="c"><a href="#">Contact</a></div>
</div>

<div class="main">
    <div class="a"><a href="#">Home</a></div>
    <div class="c"><a href="#">Contact</a></div>
</div>

<div class="main">
    <div class="c-wrapper">
      <a class="c" href="#">Contact</a>
      <a class="c" href="#">Contact2</a>
    </div>
</div>
<div class="main">
    <div class="c-wrapper2">
      <span class="c">Contact</span>
      <span class="c">Contact2</span>
    </div>
</div>
_x000D_
_x000D_
_x000D_

How can I create a unique constraint on my column (SQL Server 2008 R2)?

One thing not clearly covered is that microsoft sql is creating in the background an unique index for the added constraint

create table Customer ( id int primary key identity (1,1) , name nvarchar(128) ) 

--Commands completed successfully.

sp_help Customer

---> index
--index_name    index_description   index_keys
--PK__Customer__3213E83FCC4A1DFA    clustered, unique, primary key located on PRIMARY   id

---> constraint
--constraint_type   constraint_name delete_action   update_action   status_enabled  status_for_replication  constraint_keys
--PRIMARY KEY (clustered)   PK__Customer__3213E83FCC4A1DFA  (n/a)   (n/a)   (n/a)   (n/a)   id


---- now adding the unique constraint

ALTER TABLE Customer ADD CONSTRAINT U_Name UNIQUE(Name)

-- Commands completed successfully.

sp_help Customer

---> index
---index_name   index_description   index_keys
---PK__Customer__3213E83FCC4A1DFA   clustered, unique, primary key located on PRIMARY   id
---U_Name   nonclustered, unique, unique key located on PRIMARY name

---> constraint
---constraint_type  constraint_name delete_action   update_action   status_enabled  status_for_replication  constraint_keys
---PRIMARY KEY (clustered)  PK__Customer__3213E83FCC4A1DFA  (n/a)   (n/a)   (n/a)   (n/a)   id
---UNIQUE (non-clustered)   U_Name  (n/a)   (n/a)   (n/a)   (n/a)   name

as you can see , there is a new constraint and a new index U_Name

ReactJS call parent method

You can use any parent methods. For this you should to send this methods from you parent to you child like any simple value. And you can use many methods from the parent at one time. For example:

var Parent = React.createClass({
    someMethod: function(value) {
        console.log("value from child", value)
    },
    someMethod2: function(value) {
        console.log("second method used", value)
    },
    render: function() {
      return (<Child someMethod={this.someMethod} someMethod2={this.someMethod2} />);
    }
});

And use it into the Child like this (for any actions or into any child methods):

var Child = React.createClass({
    getInitialState: function() {
      return {
        value: 'bar'
      }
    },
    render: function() {
      return (<input type="text" value={this.state.value} onClick={this.props.someMethod} onChange={this.props.someMethod2} />);
    }
});

Trigger function when date is selected with jQuery UI datepicker

If the datepicker is in a row of a grid, try something like

editoptions : {
    dataInit : function (e) {
        $(e).datepicker({
            onSelect : function (ev) {
                // here your code
            }
        });
    }
}

How can I remove file extension from a website address?

same as Igor but should work without line 2:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

Spring MVC @PathVariable with dot (.) is getting truncated

If you are using Spring 3.2.x and <mvc:annotation-driven />, create this little BeanPostProcessor:

package spring;

public final class DoNotTruncateMyUrls implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof RequestMappingHandlerMapping) {
            ((RequestMappingHandlerMapping)bean).setUseSuffixPatternMatch(false);
        }
        return bean;
    }
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
}

Then put this in your MVC config xml:

<bean class="spring.DoNotTruncateMyUrls" />

Adding HTML entities using CSS content

Use the hex code for a non-breaking space. Something like this:

.breadcrumbs a:before {
    content: '>\00a0';
}

What is the reason for the error message "System cannot find the path specified"?

The following worked for me:

  1. Open the Registry Editor (press windows key, type regedit and hit Enter) .
  2. Navigate to HKEY_CURRENT_USER\Software\Microsoft\Command Processor\AutoRun and clear the values.
  3. Also check HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\AutoRun.

Save ArrayList to SharedPreferences

You can use serialization or Gson library to convert list to string and vice versa and then save string in preferences.

Using google's Gson library:

//Converting list to string
new Gson().toJson(list);

//Converting string to list
new Gson().fromJson(listString, CustomObjectsList.class);

Using Java serialization:

//Converting list to string
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(list);
oos.flush();
String string = Base64.encodeToString(bos.toByteArray(), Base64.DEFAULT);
oos.close();
bos.close();
return string;

//Converting string to list
byte[] bytesArray = Base64.decode(familiarVisitsString, Base64.DEFAULT);
ByteArrayInputStream bis = new ByteArrayInputStream(bytesArray);
ObjectInputStream ois = new ObjectInputStream(bis);
Object clone = ois.readObject();
ois.close();
bis.close();
return (CustomObjectsList) clone;

What is a "web service" in plain English?

Yes that is a simple web service.

Web services are really nothing more than a request/ response mechanism that allows a client to remotely access/ modify data. There are formal standards for web services (SOAP, SOA etc), but your simple page is a service too.

The main downside to printing it to a page is that your service would return HTML. Preferable data formats are JSON and XML, because most client frameworks (and server frameworks) are designed around using JSON and XML.

So if you modified your service to return:

<RANDOM>some random number</RANDOM>

rather than:

<HEAD>...</HEAD>  
<BODY>some random number</BODY>

then it would be more useful to most clients

How do you check current view controller class in Swift?

Check that way that worked better for me What is .self

if ((self.window.rootViewController?.isKind(of: WebViewController.self))!)
{
  //code
}

Git merge error "commit is not possible because you have unmerged files"

So from the error above. All you have to do to fix this issue is to revert your code. (git revert HEAD) then git pull and then redo your changes, then git pull again and was able to commit or merge with no errors.

Android Animation Alpha

Might be a little late, but found a lovely solution in the android docs.

//In transition: (alpha from 0 to 0.5)
view.setAlpha(0f);
view.setVisibility(View.VISIBLE);
view.animate()
   .alpha(0.5f)
   .setDuration(400)
   .setListener(null);

//Out transition: (alpha from 0.5 to 0)
view.setAlpha(0.5f)
view.animate()
   .alpha(0f)
   .setDuration(400)
   .setListener(new AnimatorListenerAdapter() {
           @Override
           public void onAnimationEnd(Animator animation) {
           view.setVisibility(View.GONE);
         }
    });

What is the difference between "::" "." and "->" in c++

You have a pointer to an object. Therefore, you need to access a field of an object that's pointed to by the pointer. To dereference the pointer you use *, and to access a field, you use ., so you can use:

cout << (*kwadrat).val1;

Note that the parentheses are necessary. This operation is common enough that long ago (when C was young) they decided to create a "shorthand" method of doing it:

cout << kwadrat->val1;

These are defined to be identical. As you can see, the -> basically just combines a * and a . into a single operation. If you were dealing directly with an object or a reference to an object, you'd be able to use the . without dereferencing a pointer first:

Kwadrat kwadrat2(2,3,4);

cout << kwadrat2.val1;

The :: is the scope resolution operator. It is used when you only need to qualify the name, but you're not dealing with an individual object at all. This would be primarily to access a static data member:

struct something { 
    static int x; // this only declares `something::x`. Often found in a header
};

int something::x;  // this defines `something::x`. Usually in .cpp/.cc/.C file.

In this case, since x is static, it's not associated with any particular instance of something. In fact, it will exist even if no instance of that type of object has been created. In this case, we can access it with the scope resolution operator:

something::x = 10;

std::cout << something::x;

Note, however, that it's also permitted to access a static member as if it was a member of a particular object:

something s;

s.x = 1;

At least if memory serves, early in the history of C++ this wasn't allowed, but the meaning is unambiguous, so they decided to allow it.

Oracle: If Table Exists

The best and most efficient way is to catch the "table not found" exception: this avoids the overhead of checking if the table exists twice; and doesn't suffer from the problem that if the DROP fails for some other reason (that might be important) the exception is still raised to the caller:

BEGIN
   EXECUTE IMMEDIATE 'DROP TABLE ' || table_name;
EXCEPTION
   WHEN OTHERS THEN
      IF SQLCODE != -942 THEN
         RAISE;
      END IF;
END;

ADDENDUM For reference, here are the equivalent blocks for other object types:

Sequence

BEGIN
  EXECUTE IMMEDIATE 'DROP SEQUENCE ' || sequence_name;
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -2289 THEN
      RAISE;
    END IF;
END;

View

BEGIN
  EXECUTE IMMEDIATE 'DROP VIEW ' || view_name;
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -942 THEN
      RAISE;
    END IF;
END;

Trigger

BEGIN
  EXECUTE IMMEDIATE 'DROP TRIGGER ' || trigger_name;
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -4080 THEN
      RAISE;
    END IF;
END;

Index

BEGIN
  EXECUTE IMMEDIATE 'DROP INDEX ' || index_name;
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -1418 THEN
      RAISE;
    END IF;
END;

Column

BEGIN
  EXECUTE IMMEDIATE 'ALTER TABLE ' || table_name
                || ' DROP COLUMN ' || column_name;
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -904 AND SQLCODE != -942 THEN
      RAISE;
    END IF;
END;

Database Link

BEGIN
  EXECUTE IMMEDIATE 'DROP DATABASE LINK ' || dblink_name;
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -2024 THEN
      RAISE;
    END IF;
END;

Materialized View

BEGIN
  EXECUTE IMMEDIATE 'DROP MATERIALIZED VIEW ' || mview_name;
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -12003 THEN
      RAISE;
    END IF;
END;

Type

BEGIN
  EXECUTE IMMEDIATE 'DROP TYPE ' || type_name;
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -4043 THEN
      RAISE;
    END IF;
END;

Constraint

BEGIN
  EXECUTE IMMEDIATE 'ALTER TABLE ' || table_name
            || ' DROP CONSTRAINT ' || constraint_name;
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -2443 AND SQLCODE != -942 THEN
      RAISE;
    END IF;
END;

Scheduler Job

BEGIN
  DBMS_SCHEDULER.drop_job(job_name);
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -27475 THEN
      RAISE;
    END IF;
END;

User / Schema

BEGIN
  EXECUTE IMMEDIATE 'DROP USER ' || user_name;
  /* you may or may not want to add CASCADE */
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -1918 THEN
      RAISE;
    END IF;
END;

Package

BEGIN
  EXECUTE IMMEDIATE 'DROP PACKAGE ' || package_name;
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -4043 THEN
      RAISE;
    END IF;
END;

Procedure

BEGIN
  EXECUTE IMMEDIATE 'DROP PROCEDURE ' || procedure_name;
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -4043 THEN
      RAISE;
    END IF;
END;

Function

BEGIN
  EXECUTE IMMEDIATE 'DROP FUNCTION ' || function_name;
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -4043 THEN
      RAISE;
    END IF;
END;

Tablespace

BEGIN
  EXECUTE IMMEDIATE 'DROP TABLESPACE' || tablespace_name;
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -959 THEN
      RAISE;
    END IF;
END;

Synonym

BEGIN
  EXECUTE IMMEDIATE 'DROP SYNONYM ' || synonym_name;
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -1434 THEN
      RAISE;
    END IF;
END;

How to implement if-else statement in XSLT?

If statement is used for checking just one condition quickly. When you have multiple options, use <xsl:choose> as illustrated below:

   <xsl:choose>
     <xsl:when test="$CreatedDate > $IDAppendedDate">
       <h2>mooooooooooooo</h2>
     </xsl:when>
     <xsl:otherwise>
      <h2>dooooooooooooo</h2>
     </xsl:otherwise>
   </xsl:choose>

Also, you can use multiple <xsl:when> tags to express If .. Else If or Switch patterns as illustrated below:

   <xsl:choose>
     <xsl:when test="$CreatedDate > $IDAppendedDate">
       <h2>mooooooooooooo</h2>
     </xsl:when>
     <xsl:when test="$CreatedDate = $IDAppendedDate">
       <h2>booooooooooooo</h2>
     </xsl:when>
     <xsl:otherwise>
      <h2>dooooooooooooo</h2>
     </xsl:otherwise>
   </xsl:choose>

The previous example would be equivalent to the pseudocode below:

   if ($CreatedDate > $IDAppendedDate)
   {
       output: <h2>mooooooooooooo</h2>
   }
   else if ($CreatedDate = $IDAppendedDate)
   {
       output: <h2>booooooooooooo</h2>
   }
   else
   {
       output: <h2>dooooooooooooo</h2>
   }

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

And also ng update @angular/material will update your code and fix all imports

How does java do modulus calculations with negative numbers?

Since "mathematically" both are correct:

-13 % 64 = -13 (on modulus 64)  
-13 % 64 = 51 (on modulus 64)

One of the options had to be chosen by Java language developers and they chose:

the sign of the result equals the sign of the dividend.

Says it in Java specs:

https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.17.3

Enter key pressed event handler

You can also use PreviewKeyDown in WPF:

<TextBox PreviewKeyDown="EnterClicked" />

or in C#:

myTextBox.PreviewKeyDown += EnterClicked;

And then in the attached class:

void EnterClicked(object sender, KeyEventArgs e) {
    if(e.Key == Key.Return) {
        DoSomething();
        e.Handled = true;
    }
}

Convert command line arguments into an array in Bash

The importance of the double quotes is worth emphasizing. Suppose an argument contains whitespace.

Code:

#!/bin/bash
printf 'arguments:%s\n' "$@"
declare -a arrayGOOD=( "$@" )
declare -a arrayBAAD=(  $@  )

printf '\n%s:\n' arrayGOOD
declare -p arrayGOOD
arrayGOODlength=${#arrayGOOD[@]}
for (( i=1; i<${arrayGOODlength}+1; i++ ));
do
   echo "${arrayGOOD[$i-1]}"
done

printf '\n%s:\n' arrayBAAD
declare -p arrayBAAD
arrayBAADlength=${#arrayBAAD[@]}
for (( i=1; i<${arrayBAADlength}+1; i++ ));
do
   echo "${arrayBAAD[$i-1]}"
done

Output:

> ./bash-array-practice.sh 'The dog ate the "flea" -- and ' the mouse.
arguments:The dog ate the "flea" -- and 
arguments:the
arguments:mouse.

arrayGOOD:
declare -a arrayGOOD='([0]="The dog ate the \"flea\" -- and " [1]="the" [2]="mouse.")'
The dog ate the "flea" -- and 
the
mouse.

arrayBAAD:
declare -a arrayBAAD='([0]="The" [1]="dog" [2]="ate" [3]="the" [4]="\"flea\"" [5]="--" [6]="and" [7]="the" [8]="mouse.")'
The
dog
ate
the
"flea"
--
and
the
mouse.
> 

OpenCV in Android Studio

For everyone who felt they want to run away with all the steps and screen shots on the (great!) above answers, this worked for me with android studio 2.2.1:

  1. Create a new project, name it as you want and take the default (minSdkVersion 15 is fine).

  2. Download the zip file from here: https://sourceforge.net/projects/opencvlibrary/files/opencv-android/ (I downloaded 3.2.0 version, but there may be a newer versions).

  3. Unzip the zip file, the best place is in your workspace folder, but it not really matter.

  4. Inside Android Studio, click File->New-> Import Module and navigate to \path_to_your_unzipped_file\OpenCV-android-sdk\sdk\java and hit Ok, then accept all default dialogs.

  5. In the gradle file of your app module, add this to the dependencies block:

     dependencies {
         compile project(':openCVLibraryXYZ')
         //rest of code
     }
    

Where XYZ is the exact version you downloaded, for example in my case:

    dependencies {
        compile project(':openCVLibrary320')
        //rest of code
    }