Programs & Examples On #Nsurlconnection

An NSURLConnection is the Apple Foundation Framework class that provides support to perform the loading of a URL request. It is deprecated and should be replaced by NSURLSession.

The resource could not be loaded because the App Transport Security policy requires the use of a secure connection

If you use firebase, it will add NSAllowsArbitraryLoadsInWebContent = true in the NSAppTransportSecurity section, and NSAllowsArbitraryLoads = true will not work

NSURLConnection Using iOS Swift

An abbreviated version of your code worked for me,

class Remote: NSObject {

    var data = NSMutableData()

    func connect(query:NSString) {
        var url =  NSURL.URLWithString("http://www.google.com")
        var request = NSURLRequest(URL: url)
        var conn = NSURLConnection(request: request, delegate: self, startImmediately: true)
    }


     func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
        println("didReceiveResponse")
    }

    func connection(connection: NSURLConnection!, didReceiveData conData: NSData!) {
        self.data.appendData(conData)
    }

    func connectionDidFinishLoading(connection: NSURLConnection!) {
        println(self.data)
    }


    deinit {
        println("deiniting")
    }
}

This is the code I used in the calling class,

class ViewController: UIViewController {

    var remote = Remote()


    @IBAction func downloadTest(sender : UIButton) {
        remote.connect("/apis")
    }

}

You didn't specify in your question where you had this code,

var remote = Remote()
remote.connect("/apis")

If var is a local variable, then the Remote class will be deallocated right after the connect(query:NSString) method finishes, but before the data returns. As you can see by my code, I usually implement reinit (or dealloc up to now) just to make sure when my instances go away. You should add that to your Remote class to see if that's your problem.

Easiest way to detect Internet connection on iOS?

I am writing the swift version of the accepted answer here, incase if someone finds it usefull, the code is written swift 2,

You can download the required files from SampleCode

Add Reachability.h and Reachability.m file to your project,

Now one will need to create Bridging-Header.h file if none exists for your project,

Inside your Bridging-Header.h file add this line :

#import "Reachability.h"

Now in order to check for Internet Connection

static func isInternetAvailable() -> Bool {
    let networkReachability : Reachability = Reachability.reachabilityForInternetConnection()
    let networkStatus : NetworkStatus = networkReachability.currentReachabilityStatus()

    if networkStatus == NotReachable {
        print("No Internet")
        return false
    } else {
        print("Internet Available")
        return true
    }

}

CFNetwork SSLHandshake failed iOS 9

In iOS 10+, the TLS string MUST be of the form "TLSv1.0". It can't just be "1.0". (Sigh)


The following combination of the other Answers works.

Let's say you are trying to connect to a host (YOUR_HOST.COM) that only has TLS 1.0.

Add these to your app's Info.plist

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>YOUR_HOST.COM</key>
        <dict>
            <key>NSIncludesSubdomains</key>
            <true/>
            <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSTemporaryExceptionMinimumTLSVersion</key>
            <string>TLSv1.0</string>
            <key>NSTemporaryExceptionRequiresForwardSecrecy</key>
            <false/>
        </dict>
    </dict>
</dict>

Sending an HTTP POST request on iOS

Objective C

Post API with parameters and validate with url to navigate if json
response key with status:"success"

NSString *string= [NSString stringWithFormat:@"url?uname=%@&pass=%@&uname_submit=Login",self.txtUsername.text,self.txtPassword.text];
    NSLog(@"%@",string);
    NSURL *url = [NSURL URLWithString:string];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSURLResponse *response;
    NSError *err;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
    NSLog(@"responseData: %@", responseData);
    NSString *str = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    NSLog(@"responseData: %@", str);
        NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData
                                                         options:kNilOptions
                                                           error:nil];
    NSDictionary* latestLoans = [json objectForKey:@"status"];
    NSString *str2=[NSString stringWithFormat:@"%@", latestLoans];
    NSString *str3=@"success";
    if ([str3 isEqualToString:str2 ])
    {
        [self performSegueWithIdentifier:@"move" sender:nil];
        NSLog(@"successfully.");
    }
    else
    {
        UIAlertController *alert= [UIAlertController
                                 alertControllerWithTitle:@"Try Again"
                                 message:@"Username or Password is Incorrect."
                                 preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction* ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                   handler:^(UIAlertAction * action){
                                                       [self.view endEditing:YES];
                                                   }
                             ];
        [alert addAction:ok];
        [[UIView appearanceWhenContainedIn:[UIAlertController class], nil] setTintColor:[UIColor redColor]];
        [self presentViewController:alert animated:YES completion:nil];
        [self.view endEditing:YES];
      }

JSON Response : {"status":"success","user_id":"58","user_name":"dilip","result":"You have been logged in successfully"} Working code

**

How to scroll page in flutter

you can scroll any part of content in two ways ...

  1. you can use the list view directly
  2. or SingleChildScrollView

most of the time i use List view directly when ever there is a keybord intraction in that specific screen so that the content dont get overlap by the keyboard and more over scrolls to top ....

this trick will be helpful many a times....

'System.Reflection.TargetInvocationException' occurred in PresentationFramework.dll

The event is probably raised before the elements are fully loaded or the references are still unset, hence the exceptions. Try only setting properties if the reference is not null and IsLoaded is true.

Is < faster than <=?

For floating point code, the <= comparison may indeed be slower (by one instruction) even on modern architectures. Here's the first function:

int compare_strict(double a, double b) { return a < b; }

On PowerPC, first this performs a floating point comparison (which updates cr, the condition register), then moves the condition register to a GPR, shifts the "compared less than" bit into place, and then returns. It takes four instructions.

Now consider this function instead:

int compare_loose(double a, double b) { return a <= b; }

This requires the same work as compare_strict above, but now there's two bits of interest: "was less than" and "was equal to." This requires an extra instruction (cror - condition register bitwise OR) to combine these two bits into one. So compare_loose requires five instructions, while compare_strict requires four.

You might think that the compiler could optimize the second function like so:

int compare_loose(double a, double b) { return ! (a > b); }

However this will incorrectly handle NaNs. NaN1 <= NaN2 and NaN1 > NaN2 need to both evaluate to false.

Is there a JavaScript strcmp()?

localeCompare() is slow, so if you don't care about the "correct" ordering of non-English-character strings, try your original method or the cleaner-looking:

str1 < str2 ? -1 : +(str1 > str2)

This is an order of magnitude faster than localeCompare() on my machine.

The + ensures that the answer is always numeric rather than boolean.

Cannot hide status bar in iOS7

I tried all these options posted here on my project and they would not work. I thought it could be to do with the fact I had updated my Xcode and then the app to iOS 7 and some settings had got messed up somewhere. I decided To build a completely new project for it and after simple just setting: "Status bar is initially hidden = YES" and "View controller-based status bar appearance = NO" as stated by many others it worked correctly (i.e. no status bar).

So my advice if you are working on a project which has been updated to iOS 7 from an old version and have tried all other options is to build a new project.

UIBarButtonItem in navigation bar programmatically?

Setting LeftBarButton with Original Image.

let menuButton = UIBarButtonItem(image: UIImage(named: "imagename").withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(classname.functionname))
self.navigationItem.leftBarButtonItem  = menuButton

IE throws JavaScript Error: The value of the property 'googleMapsQuery' is null or undefined, not a Function object (works in other browsers)

I was having a similar issue with a property being null or undefined.

This ended up being that IE's document mode was being defaulted to IE7 Standards. This was due to the compatibility mode being automatically set to be used for all intranet sites (Tools > Compatibility View Setting > Display Intranet Sites in Compatibility View).

Given the lat/long coordinates, how can we find out the city/country?

Loc2country is a Golang based tool that returns the ISO alpha-3 country code for given location coordinates (lat/lon). It responds in microseconds. It uses a geohash to country map.

The geohash data is generated using georaptor.

We use geohash at level 6 for this tool, i.e., boxes of size 1.2km x 600m.

VS 2017 Metadata file '.dll could not be found

Check all the projects are loaded. In my case one of the project was unloaded and reloading the project clears the errors.

Is it possible to set an object to null?

An object of a class cannot be set to NULL; however, you can set a pointer (which contains a memory address of an object) to NULL.

Example of what you can't do which you are asking:

Cat c;
c = NULL;//Compiling error

Example of what you can do:

Cat c;
//Set p to hold the memory address of the object c
Cat *p = &c;
//Set p to hold NULL
p = NULL;

Creating a pandas DataFrame from columns of other DataFrames with similar indexes

You can use concat:

In [11]: pd.concat([df1['c'], df2['c']], axis=1, keys=['df1', 'df2'])
Out[11]: 
                 df1       df2
2014-01-01       NaN -0.978535
2014-01-02 -0.106510 -0.519239
2014-01-03 -0.846100 -0.313153
2014-01-04 -0.014253 -1.040702
2014-01-05  0.315156 -0.329967
2014-01-06 -0.510577 -0.940901
2014-01-07       NaN -0.024608
2014-01-08       NaN -1.791899

[8 rows x 2 columns]

The axis argument determines the way the DataFrames are stacked:

df1 = pd.DataFrame([1, 2, 3])
df2 = pd.DataFrame(['a', 'b', 'c'])

pd.concat([df1, df2], axis=0)
   0
0  1
1  2
2  3
0  a
1  b
2  c

pd.concat([df1, df2], axis=1)

   0  0
0  1  a
1  2  b
2  3  c

How do I include a pipe | in my linux find -exec command?

If you are looking for a simple alternative, this can be done using a loop:

for i in $(find -name 'file_*' -follow -type f); do
  zcat $i | agrep -dEOE 'grep'
done

or, more general and easy to understand form:

for i in $(YOUR_FIND_COMMAND); do
  YOUR_EXEC_COMMAND_AND_PIPES
done

and replace any {} by $i in YOUR_EXEC_COMMAND_AND_PIPES

Auto detect mobile browser (via user-agent?)

You can detect mobile clients simply through navigator.userAgent , and load alternate scripts based on the detected client type as:

 $(document).ready(function(e) {

        if(navigator.userAgent.match(/Android/i)
          || navigator.userAgent.match(/webOS/i)
          || navigator.userAgent.match(/iPhone/i)
          || navigator.userAgent.match(/iPad/i)
          || navigator.userAgent.match(/iPod/i)
          || navigator.userAgent.match(/BlackBerry/i)
          || navigator.userAgent.match(/Windows Phone/i)) {

         //write code for your mobile clients here.

          var jsScript = document.createElement("script");
          jsScript.setAttribute("type", "text/javascript");
          jsScript.setAttribute("src", "js/alternate_js_file.js");
          document.getElementsByTagName("head")[0].appendChild(jsScript );

          var cssScript = document.createElement("link");
          cssScript.setAttribute("rel", "stylesheet");
          cssScript.setAttribute("type", "text/css");
          cssScript.setAttribute("href", "css/alternate_css_file.css");
          document.getElementsByTagName("head")[0].appendChild(cssScript); 

    }
    else{
         // write code for your desktop clients here
    }

    });

Wait for a void async method

do a AutoResetEvent, call the function then wait on AutoResetEvent and then set it inside async void when you know it is done.

You can also wait on a Task that returns from your void async

C# how to wait for a webpage to finish loading before continuing

Check out the WatiN project:

Inspired by Watir development of WatiN started in December 2005 to make a similar kind of Web Application Testing possible for the .Net languages. Since then WatiN has grown into an easy to use, feature rich and stable framework. WatiN is developed in C# and aims to bring you an easy way to automate your tests with Internet Explorer and FireFox using .Net...

How to get Linux console window width in Python

@reannual's answer works well, but there's an issue with it: os.popen is now deprecated. The subprocess module should be used instead, so here's a version of @reannual's code that uses subprocess and directly answers the question (by giving the column width directly as an int:

import subprocess

columns = int(subprocess.check_output(['stty', 'size']).split()[1])

Tested on OS X 10.9

In bootstrap how to add borders to rows without adding up?

You can simply use the border class from bootstrap:

<div class="row border border-dark">
...
</div>

For more details visit the following link: Borders

copy db file with adb pull results in 'permission denied' error

I had just the same problem, here's how to deal with it:

  1. adb shell to the device
  2. su
  3. ls -l and check current access rights on the file you need. You'll need that later.
  4. go to the file needed and: chmod 777 file.ext. Note: now you have a temporary security issue. You've just allowed all the rights to everyone! Consider adding just R for users.
  5. open another console and: adb pull /path/to/file.ext c:\pc\path\to\file.exe
  6. Important: after you're done, revert the access rights back to the previous value (point 3)

Someone mentioned something similar earlier.

Thanks for the comments below.

What is pipe() function in Angular

Don't get confused with the concepts of Angular and RxJS

We have pipes concept in Angular and pipe() function in RxJS.

1) Pipes in Angular: A pipe takes in data as input and transforms it to the desired output
https://angular.io/guide/pipes

2) pipe() function in RxJS: You can use pipes to link operators together. Pipes let you combine multiple functions into a single function.

The pipe() function takes as its arguments the functions you want to combine, and returns a new function that, when executed, runs the composed functions in sequence.
https://angular.io/guide/rx-library (search for pipes in this URL, you can find the same)

So according to your question, you are referring pipe() function in RxJS

What is the difference between an abstract function and a virtual function?

Virtual Method:

  • Virtual means we CAN override it.

  • Virtual Function has an implementation. When we inherit the class we can override the virtual function and provide our own logic.

  • We can change the return type of Virtual function while implementing the
    function in the child class(which can be said as a concept of
    Shadowing).

Abstract Method

  • Abstract means we MUST override it.

  • An abstract function has no implementation and must be in an abstract class.

  • It can only be declared. This forces the derived class to provide the implementation of it.

  • An abstract member is implicitly virtual. The abstract can be called as pure virtual in some of the languages.

    public abstract class BaseClass
    { 
        protected abstract void xAbstractMethod();
    
        public virtual void xVirtualMethod()
        {
            var x = 3 + 4;
        }
    } 
    

CSS background image to fit width, height should auto-scale in proportion

Background image is not Set Perfect then his css is problem create so his css file change to below code

_x000D_
_x000D_
html {  _x000D_
  background-image: url("example.png");  _x000D_
  background-repeat: no-repeat;  _x000D_
  background-position: 0% 0%;_x000D_
  background-size: 100% 100%;_x000D_
}
_x000D_
_x000D_
_x000D_

%; background-size: 100% 100%;"

How can I do an UPDATE statement with JOIN in SQL Server?

For SQLite use the RowID property to make the update:

update Table set column = 'NewValue'
where RowID = 
(select t1.RowID from Table t1
join Table2 t2 on t1.JoinField = t2.JoinField
where t2.SelectValue = 'FooMyBarPlease');

NSRange to Range<String.Index>

Here's my best effort. But this cannot check or detect wrong input argument.

extension String {
    /// :r: Must correctly select proper UTF-16 code-unit range. Wrong range will produce wrong result.
    public func convertRangeFromNSRange(r:NSRange) -> Range<String.Index> {
        let a   =   (self as NSString).substringToIndex(r.location)
        let b   =   (self as NSString).substringWithRange(r)

        let n1  =   distance(a.startIndex, a.endIndex)
        let n2  =   distance(b.startIndex, b.endIndex)

        let i1  =   advance(startIndex, n1)
        let i2  =   advance(i1, n2)

        return  Range<String.Index>(start: i1, end: i2)
    }
}

let s   =   ""
println(s[s.convertRangeFromNSRange(NSRange(location: 4, length: 2))])      //  Proper range. Produces correct result.
println(s[s.convertRangeFromNSRange(NSRange(location: 0, length: 4))])      //  Proper range. Produces correct result.
println(s[s.convertRangeFromNSRange(NSRange(location: 0, length: 2))])      //  Improper range. Produces wrong result.
println(s[s.convertRangeFromNSRange(NSRange(location: 0, length: 1))])      //  Improper range. Produces wrong result.

Result.





Details

NSRange from NSString counts UTF-16 code-units. And Range<String.Index> from Swift String is an opaque relative type which provides only equality and navigation operations. This is intentionally hidden design.

Though the Range<String.Index> seem to be mapped to UTF-16 code-unit offset, that is just an implementation detail, and I couldn't find any mention about any guarantee. That means the implementation details can be changed at any time. Internal representation of Swift String is not pretty defined, and I cannot rely on it.

NSRange values can be directly mapped to String.UTF16View indexes. But there's no method to convert it into String.Index.

Swift String.Index is index to iterate Swift Character which is an Unicode grapheme cluster. Then, you must provide proper NSRange which selects correct grapheme clusters. If you provide wrong range like the above example, it will produce wrong result because proper grapheme cluster range couldn't be figured out.

If there's a guarantee that the String.Index is UTF-16 code-unit offset, then problem becomes simple. But it is unlikely to happen.

Inverse conversion

Anyway the inverse conversion can be done precisely.

extension String {
    /// O(1) if `self` is optimised to use UTF-16.
    /// O(n) otherwise.
    public func convertRangeToNSRange(r:Range<String.Index>) -> NSRange {
        let a   =   substringToIndex(r.startIndex)
        let b   =   substringWithRange(r)

        return  NSRange(location: a.utf16Count, length: b.utf16Count)
    }
}
println(convertRangeToNSRange(s.startIndex..<s.endIndex))
println(convertRangeToNSRange(s.startIndex.successor()..<s.endIndex))

Result.

(0,6)
(4,2)

How to query as GROUP BY in django?

Django does not support free group by queries. I learned it in the very bad way. ORM is not designed to support stuff like what you want to do, without using custom SQL. You are limited to:

  • RAW sql (i.e. MyModel.objects.raw())
  • cr.execute sentences (and a hand-made parsing of the result).
  • .annotate() (the group by sentences are performed in the child model for .annotate(), in examples like aggregating lines_count=Count('lines'))).

Over a queryset qs you can call qs.query.group_by = ['field1', 'field2', ...] but it is risky if you don't know what query are you editing and have no guarantee that it will work and not break internals of the QuerySet object. Besides, it is an internal (undocumented) API you should not access directly without risking the code not being anymore compatible with future Django versions.

How to detect browser using angularjs?

I modified the above technique which was close to what I wanted for angular and turned it into a service :-). I included ie9 because I was having some issues in my angularjs app, but could be something I'm doing, so feel free to take it out.

angular.module('myModule').service('browserDetectionService', function() {

 return {
isCompatible: function () {

  var browserInfo = navigator.userAgent;
  var browserFlags =  {};

  browserFlags.ISFF = browserInfo.indexOf('Firefox') != -1;
  browserFlags.ISOPERA = browserInfo.indexOf('Opera') != -1;
  browserFlags.ISCHROME = browserInfo.indexOf('Chrome') != -1;
  browserFlags.ISSAFARI = browserInfo.indexOf('Safari') != -1 && !browserFlags.ISCHROME;
  browserFlags.ISWEBKIT = browserInfo.indexOf('WebKit') != -1;

  browserFlags.ISIE = browserInfo.indexOf('Trident') > 0 || navigator.userAgent.indexOf('MSIE') > 0;
  browserFlags.ISIE6 = browserInfo.indexOf('MSIE 6') > 0;
  browserFlags.ISIE7 = browserInfo.indexOf('MSIE 7') > 0;
  browserFlags.ISIE8 = browserInfo.indexOf('MSIE 8') > 0;
  browserFlags.ISIE9 = browserInfo.indexOf('MSIE 9') > 0;
  browserFlags.ISIE10 = browserInfo.indexOf('MSIE 10') > 0;
  browserFlags.ISOLD = browserFlags.ISIE6 || browserFlags.ISIE7 || browserFlags.ISIE8 || browserFlags.ISIE9; // MUST be here

  browserFlags.ISIE11UP = browserInfo.indexOf('MSIE') == -1 && browserInfo.indexOf('Trident') > 0;
  browserFlags.ISIE10UP = browserFlags.ISIE10 || browserFlags.ISIE11UP;
  browserFlags.ISIE9UP = browserFlags.ISIE9 || browserFlags.ISIE10UP;

  return !browserFlags.ISOLD;
  }
};

});

How to run a maven created jar file using just the command line

Just use the exec-maven-plugin.

<build>
    <plugins>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.2.1</version>
            <configuration>
                <mainClass>com.example.Main</mainClass>
            </configuration>
        </plugin>
    </plugins>
</build>

Then you run you program:

mvn exec:java

Cannot bulk load because the file could not be opened. Operating System Error Code 3

I have solved this issue,

login to server computer where SQL Server is installed get you csv file on server computer and execute your query it will insert the records.

If you will give datatype compatibility issue change the datatype for that column

How to manually set REFERER header in Javascript?

You can use Object.defineProperty on the document object for the referrer property:

Object.defineProperty(document, "referrer", {get : function(){ return "my new referrer"; }});

Unfortunately this will not work on any version of safari <=5, Firefox < 4, Chrome < 5 and Internet Explorer < 9 as it doesn't allow defineProperty to be used on dom objects.

Error Code: 2013. Lost connection to MySQL server during query

Try please to uncheck limit rows in in Edit ? Preferences ?SQL Queries

because You should set the 'interactive_timeout' and 'wait_timeout' properties in the mysql config file to the values you need.

How can I add the new "Floating Action Button" between two widgets/layouts

Try this library (javadoc is here), min API level is 7:

dependencies {
    compile 'com.shamanland:fab:0.0.8'
}

It provides single widget with ability to customize it via Theme, xml or java-code.

light between

It's very simple to use. There are available normal and mini implementation according to Promoted Actions pattern.

<com.shamanland.fab.FloatingActionButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_action_my"
    app:floatingActionButtonColor="@color/my_fab_color"
    app:floatingActionButtonSize="mini"
    />

Try to compile the demo app. There is exhaustive example: light and dark themes, using with ListView, align between two Views.

Google Play app description formatting

Currently (July 2015), HTML escape sequences (&bull; &#8226;) do not work in browser version of Play Store, they're displayed as text. Though, Play Store app handles them as expected.

So, if you're after the unicode bullet point in your app/update description [that's what's got you here, most likely], just copy-paste the bullet character

PS You can also use unicode input combo to get the character

Linux: CtrlShiftu 2022 Enter or Space

Mac: Hold ? 2022 release ?

Windows: Hold Alt 2022 release Alt

Mac and Windows require some setup, read on Wikipedia

PPS If you're feeling creative, here's a good link with more copypastable symbols, but don't go too crazy, nobody likes clutter in what they read.

How to create a shortcut using PowerShell

Beginning PowerShell 5.0 New-Item, Remove-Item, and Get-ChildItem have been enhanced to support creating and managing symbolic links. The ItemType parameter for New-Item accepts a new value, SymbolicLink. Now you can create symbolic links in a single line by running the New-Item cmdlet.

New-Item -ItemType SymbolicLink -Path "C:\temp" -Name "calc.lnk" -Value "c:\windows\system32\calc.exe"

Be Carefull a SymbolicLink is different from a Shortcut, shortcuts are just a file. They have a size (A small one, that just references where they point) and they require an application to support that filetype in order to be used. A symbolic link is filesystem level, and everything sees it as the original file. An application needs no special support to use a symbolic link.

Anyway if you want to create a Run As Administrator shortcut using Powershell you can use

$file="c:\temp\calc.lnk"
$bytes = [System.IO.File]::ReadAllBytes($file)
$bytes[0x15] = $bytes[0x15] -bor 0x20 #set byte 21 (0x15) bit 6 (0x20) ON (Use –bor to set RunAsAdministrator option and –bxor to unset)
[System.IO.File]::WriteAllBytes($file, $bytes)

If anybody want to change something else in a .LNK file you can refer to official Microsoft documentation.

Spark DataFrame groupBy and sort in the descending order (pyspark)

In pyspark 2.4.4

1) group_by_dataframe.count().filter("`count` >= 10").orderBy('count', ascending=False)

2) from pyspark.sql.functions import desc
   group_by_dataframe.count().filter("`count` >= 10").orderBy('count').sort(desc('count'))

No need to import in 1) and 1) is short & easy to read,
So I prefer 1) over 2)

How do I activate C++ 11 in CMake?

Modern cmake offers simpler ways to configure compilers to use a specific version of C++. The only thing anyone needs to do is set the relevant target properties. Among the properties supported by cmake, the ones that are used to determine how to configure compilers to support a specific version of C++ are the following:

  • CXX_STANDARD sets the C++ standard whose features are requested to build the target. Set this as 11 to target C++11.

  • CXX_EXTENSIONS, a boolean specifying whether compiler specific extensions are requested. Setting this as Off disables support for any compiler-specific extension.

To demonstrate, here is a minimal working example of a CMakeLists.txt.

cmake_minimum_required(VERSION 3.1)

project(testproject LANGUAGES CXX )

set(testproject_SOURCES
    main.c++
    )

add_executable(testproject ${testproject_SOURCES})

set_target_properties(testproject
    PROPERTIES
    CXX_STANDARD 11
    CXX_EXTENSIONS off
    )

Angularjs $http post file and form data

here is my solution:

_x000D_
_x000D_
// Controller_x000D_
$scope.uploadImg = function( files ) {_x000D_
  $scope.data.avatar = files[0];_x000D_
}_x000D_
_x000D_
$scope.update = function() {_x000D_
  var formData = new FormData();_x000D_
  formData.append('desc', data.desc);_x000D_
  formData.append('avatar', data.avatar);_x000D_
  SomeService.upload( formData );_x000D_
}_x000D_
_x000D_
_x000D_
// Service_x000D_
upload: function( formData ) {_x000D_
  var deferred = $q.defer();_x000D_
  var url = "/upload" ;_x000D_
  _x000D_
  var request = {_x000D_
    "url": url,_x000D_
    "method": "POST",_x000D_
    "data": formData,_x000D_
    "headers": {_x000D_
      'Content-Type' : undefined // important_x000D_
    }_x000D_
  };_x000D_
_x000D_
  console.log(request);_x000D_
_x000D_
  $http(request).success(function(data){_x000D_
    deferred.resolve(data);_x000D_
  }).error(function(error){_x000D_
    deferred.reject(error);_x000D_
  });_x000D_
  return deferred.promise;_x000D_
}_x000D_
_x000D_
_x000D_
// backend use express and multer_x000D_
// a part of the code_x000D_
var multer = require('multer');_x000D_
var storage = multer.diskStorage({_x000D_
  destination: function (req, file, cb) {_x000D_
    cb(null, '../public/img')_x000D_
  },_x000D_
  filename: function (req, file, cb) {_x000D_
    cb(null, file.fieldname + '-' + Date.now() + '.jpg');_x000D_
  }_x000D_
})_x000D_
_x000D_
var upload = multer({ storage: storage })_x000D_
app.post('/upload', upload.single('avatar'), function(req, res, next) {_x000D_
  // do something_x000D_
  console.log(req.body);_x000D_
  res.send(req.body);_x000D_
});
_x000D_
<div>_x000D_
  <input type="file" accept="image/*" onchange="angular.element( this ).scope().uploadImg( this.files )">_x000D_
  <textarea ng-model="data.desc" />_x000D_
  <button type="button" ng-click="update()">Update</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Java - How to access an ArrayList of another class?

You can do the following:

  public class Numbers {
    private int number1 = 50;
    private int number2 = 100;
    private List<Integer> list;

    public Numbers() {
      list = new ArrayList<Integer>();
      list.add(number1);
      list.add(number2);
    }

    int getNumber(int pos)
    {
      return list.get(pos);
    }
  }

  public class Test {
    private Numbers numbers;

    public Test(){
      numbers = new Numbers();
      int number1 = numbers.getNumber(0);
      int number2 = numbers.getNumber(1);
    }
  }

What are the differences between the urllib, urllib2, urllib3 and requests module?

urllib2 provides some extra functionality, namely the urlopen() function can allow you to specify headers (normally you'd have had to use httplib in the past, which is far more verbose.) More importantly though, urllib2 provides the Request class, which allows for a more declarative approach to doing a request:

r = Request(url='http://www.mysite.com')
r.add_header('User-Agent', 'awesome fetcher')
r.add_data(urllib.urlencode({'foo': 'bar'})
response = urlopen(r)

Note that urlencode() is only in urllib, not urllib2.

There are also handlers for implementing more advanced URL support in urllib2. The short answer is, unless you're working with legacy code, you probably want to use the URL opener from urllib2, but you still need to import into urllib for some of the utility functions.

Bonus answer With Google App Engine, you can use any of httplib, urllib or urllib2, but all of them are just wrappers for Google's URL Fetch API. That is, you are still subject to the same limitations such as ports, protocols, and the length of the response allowed. You can use the core of the libraries as you would expect for retrieving HTTP URLs, though.

Spark Kill Running Application

First use:

yarn application -list

Note down the application id Then to kill use:

yarn application -kill application_id

Difference between two lists

        List<int> list1 = new List<int>();
        List<int> list2 = new List<int>();
        List<int> listDifference = new List<int>();

        foreach (var item1 in list1)
        {
            foreach (var item2 in list2)
            {
                if (item1 != item2)
                    listDifference.Add(item1);
            }
        }

Initializing C# auto-properties

This will be possible in C# 6.0:

public int Y { get; } = 2;

ComboBox: Adding Text and Value to an Item (no Binding Source)

Don't know if this will work for the situation given in the original post (never mind the fact that this is two years later), but this example works for me:

Hashtable htImageTypes = new Hashtable();
htImageTypes.Add("JPEG", "*.jpg");
htImageTypes.Add("GIF", "*.gif");
htImageTypes.Add("BMP", "*.bmp");

foreach (DictionaryEntry ImageType in htImageTypes)
{
    cmbImageType.Items.Add(ImageType);
}
cmbImageType.DisplayMember = "key";
cmbImageType.ValueMember = "value";

To read your value back out, you'll have to cast the SelectedItem property to a DictionaryEntry object, and you can then evaluate the Key and Value properties of that. For instance:

DictionaryEntry deImgType = (DictionaryEntry)cmbImageType.SelectedItem;
MessageBox.Show(deImgType.Key + ": " + deImgType.Value);

How to check if the docker engine and a docker container are running?

Run:

docker version

If docker is running you will see:

Client: Docker Engine - Community
 Version:           ...
 [omitted]

Server: Docker Engine - Community
 Engine:
  Version:          ...
 [omitted]

If docker is not running you will see:

Client: Docker Engine - Community
 Version:           ...
 [omitted]

Error response from daemon: Bad response from Docker engine

Compare objects in Angular

Bit late on this thread. angular.equals does deep check, however does anyone know that why its behave differently if one of the member contain "$" in prefix ?

You can try this Demo with following input

var obj3 = {}
obj3.a=  "b";
obj3.b={};
obj3.b.$c =true;

var obj4 = {}
obj4.a=  "b";
obj4.b={};
obj4.b.$c =true;

angular.equals(obj3,obj4);

New lines inside paragraph in README.md

Interpreting newlines as <br /> used to be a feature of Github-flavored markdown, but the most recent help document no longer lists this feature.

Fortunately, you can do it manually. The easiest way is to ensure that each line ends with two spaces. So, change

a
b
c

into

a__
b__
c

(where _ is a blank space).

Or, you can add explicit <br /> tags.

a <br />
b <br />
c

Subtract minute from DateTime in SQL Server 2005

Use DATEPART to pull apart your interval, and DATEADD to subtract the parts:

select dateadd(
     hh,
    -1 * datepart(hh, cast('1:15' as datetime)),
    dateadd(
        mi,
        -1 * datepart(mi, cast('1:15' as datetime)),
        '2000-01-01 08:30:00'))

or, we can convert to minutes first (though OP would prefer not to):

declare @mins int
select @mins = datepart(mi, cast('1:15' as datetime)) + 60 * datepart(hh, cast('1:15' as datetime)) 
select dateadd(mi, -1 * @mins, '2000-01-01 08:30:00')

How to add multiple values to a dictionary key in python?

How about

a["abc"] = [1, 2]

This will result in:

>>> a
{'abc': [1, 2]}

Is that what you were looking for?

How to create an Oracle sequence starting with max value from a table?

Based on Ivan Laharnar with less code and simplier:

declare
    lastSeq number;
begin
    SELECT MAX(ID) + 1 INTO lastSeq FROM <TABLE_NAME>;
    if lastSeq IS NULL then lastSeq := 1; end if;
    execute immediate 'CREATE SEQUENCE <SEQUENCE_NAME> INCREMENT BY 1 START WITH ' || lastSeq || ' MAXVALUE 999999999 MINVALUE 1 NOCACHE';
end;

Android ListView with Checkbox and all clickable

Set the CheckBox as focusable="false" in your XML layout. Otherwise it will steal click events from the list view.

Of course, if you do this, you need to manually handle marking the CheckBox as checked/unchecked if the list item is clicked instead of the CheckBox, but you probably want that anyway.

"The semaphore timeout period has expired" error for USB connection

Too many big files all in one go. Windows barfs. Essentially the copying took too long because you asked too much of the computer and the file locking was locked too long and set a flag off, the flag is a semaphore error.

The computer stuffed itself and choked on it. I saw the RAM memory here get progressively filled with a Cache in RAM. Then when filled the subsystem ground to a halt with a semaphore error.

I have a workaround; copy or transfer fewer files not one humongous block. Break it down into sets of blocks and send across the files one at a time, maybe a few at a time, but not never the lot.

References:

https://appuals.com/how-to-fix-the-semaphore-timeout-period-has-expired-0x80070079/

https://www-01.ibm.com/support/docview.wss?uid=swg21094630

More than 1 row in <Input type="textarea" />

The "input" tag doesn't support rows and cols attributes. This is why the best alternative is to use a textarea with rows and cols attributes. You can still add a "name" attribute and also there is a useful "wrap" attribute which can serve pretty well in various situations.

How can git be installed on CENTOS 5.5?

If you are using CentOS the built in yum repositories don't seem to have git included and as such, you will need to add an additional repository to the system. For my servers I found that the Webtatic repository seems to be reasonably up to date and the installation for git will then be as follows:

# Add the repository
rpm -Uvh http://repo.webtatic.com/yum/centos/5/latest.rpm

# Install the latest version of git
yum install --enablerepo=webtatic git-all

To work around Missing Dependency: perl(Git) errors:

yum install --enablerepo=webtatic --disableexcludes=main  git-all

Variable number of arguments in C++?

Using variadic templates, example to reproduce console.log as seen in JavaScript:

Console console;
console.log("bunch", "of", "arguments");
console.warn("or some numbers:", 1, 2, 3);
console.error("just a prank", "bro");

Filename e.g. js_console.h:

#include <iostream>
#include <utility>

class Console {
protected:
    template <typename T>
    void log_argument(T t) {
        std::cout << t << " ";
    }
public:
    template <typename... Args>
    void log(Args&&... args) {
        int dummy[] = { 0, ((void) log_argument(std::forward<Args>(args)),0)... };
        cout << endl;
    }

    template <typename... Args>
    void warn(Args&&... args) {
        cout << "WARNING: ";
        int dummy[] = { 0, ((void) log_argument(std::forward<Args>(args)),0)... };
        cout << endl;
    }

    template <typename... Args>
    void error(Args&&... args) {
        cout << "ERROR: ";
        int dummy[] = { 0, ((void) log_argument(std::forward<Args>(args)),0)... };
        cout << endl;
    }
};

What is the difference between a URI, a URL and a URN?

From RFC 3986:

A URI can be further classified as a locator, a name, or both. The term "Uniform Resource Locator" (URL) refers to the subset of URIs that, in addition to identifying a resource, provide a means of locating the resource by describing its primary access mechanism (e.g., its network "location"). The term "Uniform Resource Name" (URN) has been used historically to refer to both URIs under the "urn" scheme [RFC2141], which are required to remain globally unique and persistent even when the resource ceases to exist or becomes unavailable, and to any other URI with the properties of a name.

So all URLs are URIs, and all URNs are URIs - but URNs and URLs are different, so you can't say that all URIs are URLs.

If you haven't already read Roger Pate's answer, I'd advise doing so as well.

check if jquery has been loaded, then load it if false

var f = ()=>{
    if (!window.jQuery) {
        var e = document.createElement('script');
        e.src = "https://code.jquery.com/jquery-3.2.1.min.js";
        e.onload = function () {
            jQuery.noConflict();
            console.log('jQuery ' + jQuery.fn.jquery + ' injected.');
        };
        document.head.appendChild(e);
    } else {
        console.log('jQuery ' + jQuery.fn.jquery + '');
    }
};
f();

Is it possible to apply CSS to half of a character?

Edit (oct 2017): background-clip or rather background-image options are now supported by every major browser: CanIUse

Yes, you can do this with only one character and only CSS.

Webkit (and Chrome) only, though:

http://jsbin.com/rexoyice/1/

_x000D_
_x000D_
h1 {_x000D_
  display: inline-block;_x000D_
  margin: 0; /* for demo snippet */_x000D_
  line-height: 1em; /* for demo snippet */_x000D_
  font-family: helvetica, arial, sans-serif;_x000D_
  font-weight: bold;_x000D_
  font-size: 300px;_x000D_
  background: linear-gradient(to right, #7db9e8 50%,#1e5799 50%);_x000D_
  -webkit-background-clip: text;_x000D_
  -webkit-text-fill-color: transparent;_x000D_
}
_x000D_
<h1>X</h1>
_x000D_
_x000D_
_x000D_

Visually, all the examples that use two characters (be it via JS, CSS pseudo elements, or just HTML) look fine, but note that that all adds content to the DOM which may cause accessibility--as well as text selection/cut/paste issues.

How do I implement basic "Long Polling"?

Thanks for the code, dbr. Just a small typo in long_poller.htm around the line

1000 /* ..after 1 seconds */

I think it should be

"1000"); /* ..after 1 seconds */

for it to work.

For those interested, I tried a Django equivalent. Start a new Django project, say lp for long polling:

django-admin.py startproject lp

Call the app msgsrv for message server:

python manage.py startapp msgsrv

Add the following lines to settings.py to have a templates directory:

import os.path
PROJECT_DIR = os.path.dirname(__file__)
TEMPLATE_DIRS = (
    os.path.join(PROJECT_DIR, 'templates'),
)

Define your URL patterns in urls.py as such:

from django.views.generic.simple import direct_to_template
from lp.msgsrv.views import retmsg

urlpatterns = patterns('',
    (r'^msgsrv\.php$', retmsg),
    (r'^long_poller\.htm$', direct_to_template, {'template': 'long_poller.htm'}),
)

And msgsrv/views.py should look like:

from random import randint
from time import sleep
from django.http import HttpResponse, HttpResponseNotFound

def retmsg(request):
    if randint(1,3) == 1:
        return HttpResponseNotFound('<h1>Page not found</h1>')
    else:
        sleep(randint(2,10))
        return HttpResponse('Hi! Have a random number: %s' % str(randint(1,10)))

Lastly, templates/long_poller.htm should be the same as above with typo corrected. Hope this helps.

What does int argc, char *argv[] mean?

argc is the number of arguments being passed into your program from the command line and argv is the array of arguments.

You can loop through the arguments knowing the number of them like:

for(int i = 0; i < argc; i++)
{
    // argv[i] is the argument at index i
}

ASP.NET custom error page - Server.GetLastError() is null

Looking more closely at my web.config set up, one of the comments in this post is very helpful

in asp.net 3.5 sp1 there is a new parameter redirectMode

So we can amend customErrors to add this parameter:

<customErrors mode="RemoteOnly" defaultRedirect="~/errors/GeneralError.aspx" redirectMode="ResponseRewrite" />

the ResponseRewrite mode allows us to load the «Error Page» without redirecting the browser, so the URL stays the same, and importantly for me, exception information is not lost.

Why is the jquery script not working?

This worked for me:

<script>
     jQuery.noConflict();
     // Use jQuery via jQuery() instead of via $()
     jQuery(document).ready(function(){
       jQuery("div").hide();
     });  
</script>

Reason: "Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery's case, $ is just an alias for jQuery, so all functionality is available without using $".

Read full reason here: https://api.jquery.com/jquery.noconflict/

If this solves your issue, it's likely another library is also using $.

What is the difference between "px", "dip", "dp" and "sp"?

From the Android Developer Documentation:

  1. px
    > Pixels - corresponds to actual pixels on the screen.

  2. in
    > Inches - based on the physical size of the screen.
    > 1 Inch = 2.54 centimeters

  3. mm
    > Millimeters - based on the physical size of the screen.

  4. pt
    > Points - 1/72 of an inch based on the physical size of the screen.

  5. dp or dip
    > Density-independent Pixels - an abstract unit that is based on the physical density of the screen. These units are relative to a 160 dpi screen, so one dp is one pixel on a 160 dpi screen. The ratio of dp-to-pixel will change with the screen density, but not necessarily in direct proportion. Note: The compiler accepts both "dip" and "dp", though "dp" is more consistent with "sp".

  6. sp
    > Scaleable Pixels OR scale-independent pixels - this is like the dp unit, but it is also scaled by the user's font size preference. It is recommended you use this unit when specifying font sizes, so they will be adjusted for both the screen density and user's preference. Note, the Android documentation is inconsistent on what sp actually stands for, one doc says "scale-independent pixels", the other says "scaleable pixels".

From Understanding Density Independence In Android:

Density Bucket Screen Density Physical Size Pixel Size
ldpi 120 dpi 0.5 x 0.5 in 0.5 in * 120 dpi = 60x60 px
mdpi 160 dpi 0.5 x 0.5 in 0.5 in * 160 dpi = 80x80 px
hdpi 240 dpi 0.5 x 0.5 in 0.5 in * 240 dpi = 120x120 px
xhdpi 320 dpi 0.5 x 0.5 in 0.5 in * 320 dpi = 160x160 px
xxhdpi 480 dpi 0.5 x 0.5 in 0.5 in * 480 dpi = 240x240 px
xxxhdpi 640 dpi 0.5 x 0.5 in 0.5 in * 640 dpi = 320x320 px
Unit Description Units Per Physical Inch Density Independent? Same Physical Size On Every Screen?
px Pixels Varies No No
in Inches 1 Yes Yes
mm Millimeters 25.4 Yes Yes
pt Points 72 Yes Yes
dp Density Independent Pixels ~160 Yes No
sp Scale Independent Pixels ~160 Yes No

More info can be also be found in the Google Design Documentation.

[Ljava.lang.Object; cannot be cast to

In case entire entity is being return, better solution in spring JPA is use @Query(value = "from entity where Id in :ids")

This return entity type rather than object type

Error: select command denied to user '<userid>'@'<ip-address>' for table '<table-name>'

The problem is most probably between a . and a _. Say in my query I put

SELECT ..... FROM LOCATION.PT

instead of

SELECT ..... FROM LOCATION_PT

So I think MySQL would think LOCATION as a database name and was giving access privilege error.

Getting JSONObject from JSONArray

Here is your json:

{
    "syncresponse": {
       "synckey": "2011-09-30 14:52:00",
        "createdtrs": [

        ],
        "modtrs": [

        ],
        "deletedtrs": [
          {
           "companyid": "UTB17",
           "username": "DA",
           "date": "2011-09-26",
           "reportid": "31341"
      }
       ]
   }
}

and it's parsing:

JSONObject object = new JSONObject(result);
String syncresponse = object.getString("syncresponse");
JSONObject object2 = new JSONObject(syncresponse);
String synckey = object2.getString("synckey");
JSONArray jArray1 = object2.getJSONArray("createdtrs");
JSONArray jArray2 = object2.getJSONArray("modtrs");
JSONArray jArray3 = object2.getJSONArray("deletedtrs");
for(int i = 0; i < jArray3 .length(); i++)
{
   JSONObject object3 = jArray3.getJSONObject(i);
   String comp_id = object3.getString("companyid");
   String username = object3.getString("username");
   String date = object3.getString("date");
   String report_id = object3.getString("reportid");
}

Return True, False and None in Python

It's impossible to say without seeing your actual code. Likely the reason is a code path through your function that doesn't execute a return statement. When the code goes down that path, the function ends with no value returned, and so returns None.

Updated: It sounds like your code looks like this:

def b(self, p, data): 
    current = p 
    if current.data == data: 
        return True 
    elif current.data == 1:
        return False 
    else: 
        self.b(current.next, data)

That else clause is your None path. You need to return the value that the recursive call returns:

    else:
        return self.b(current.next, data)

BTW: using recursion for iterative programs like this is not a good idea in Python. Use iteration instead. Also, you have no clear termination condition.

How do you round a number to two decimal places in C#?

Wikipedia has a nice page on rounding in general.

All .NET (managed) languages can use any of the common language run time's (the CLR) rounding mechanisms. For example, the Math.Round() (as mentioned above) method allows the developer to specify the type of rounding (Round-to-even or Away-from-zero). The Convert.ToInt32() method and its variations use round-to-even. The Ceiling() and Floor() methods are related.

You can round with custom numeric formatting as well.

Note that Decimal.Round() uses a different method than Math.Round();

Here is a useful post on the banker's rounding algorithm. See one of Raymond's humorous posts here about rounding...

How to fill OpenCV image with one solid color?

Use numpy.full. Here's a Python that creates a gray, blue, green and red image and shows in a 2x2 grid.

import cv2
import numpy as np

gray_img = np.full((100, 100, 3), 127, np.uint8)

blue_img = np.full((100, 100, 3), 0, np.uint8)
green_img = np.full((100, 100, 3), 0, np.uint8)
red_img = np.full((100, 100, 3), 0, np.uint8)

full_layer = np.full((100, 100), 255, np.uint8)

# OpenCV goes in blue, green, red order
blue_img[:, :, 0] = full_layer
green_img[:, :, 1] = full_layer
red_img[:, :, 2] = full_layer

cv2.imshow('2x2_grid', np.vstack([
    np.hstack([gray_img, blue_img]), 
    np.hstack([green_img, red_img])
]))
cv2.waitKey(0)
cv2.destroyWindow('2x2_grid')

How to run .jar file by double click on Windows 7 64-bit?

http://www.wikihow.com/Run-a-.Jar-Java-File

  1. Assuming you've loaded the Java JRE and/or Java SDK, then
  2. To do associations, go to "My Computer", click on one of your drives (C: for instance).
  3. When it is shown, choose "Tools" »» "Folder options" (or Properties... it's in different places depending on the Windows version).
  4. Open Windows Explorer (just open any folder) to get the "Tools" -> "Folder options" window.
  5. When you get the "Folder options" window, click on the tab "File types". You should be able to either edit or add JAR files (.jar extension)
  6. Change the program used to open JAR files. In the file select window, go to the folder where the JRE is installed (should be C:/Program Files/Java/..., mark "Always open with", and select the javaw.exe file.

Loop through array of values with Arrow Function

In short:

someValues.forEach((element) => {
    console.log(element);
});

If you care about index, then second parameter can be passed to receive the index of current element:

someValues.forEach((element, index) => {
    console.log(`Current index: ${index}`);
    console.log(element);
});

Refer here to know more about Array of ES6: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

Close/kill the session when the browser or tab is closed

It is not possible to kill the session variable, when the machine unexpectly shutdown due to power failure. It is only possible when the user is idle for a long time or it is properly logout.

how to print json data in console.log

{"success":true,"input_data":{"quantity-row_122":"1","price-row_122":" 35.1 "}}

console.dir() will do what you need. It will give you a hierarchical structure of the data.

success:function(data){
     console.dir(data);
}

like so

> Object
  > input_data: Object
      price-row_122: " 35.1 "
      quantity-row_122: "1"
    success: true

I don't think you need console.log(JSON.stringify(data)).

To get the data you can do this without stringify:

console.log(data.success); // true
console.log(data.input_data['quantity-row_122']) // "1"
console.log(data.input_data['price-row_122']) // " 35.1 "

Note

The value from input_data Object will be typeof "1": String, but you can convert to number(Int or Float) using ParseInt or ParseFloat, like so:

 typeof parseFloat(data.input_data['price-row_122'], 10) // "number"
 parseFloat(data.input_data['price-row_122'], 10) // 35.1

php exec() is not executing the command

You might also try giving the full path to the binary you're trying to run. That solved my problem when trying to use ImageMagick.

What is the cleanest way to ssh and run multiple commands in Bash?

The posted answers using multiline strings and multiple bash scripts did not work for me.

  • Long multiline strings are hard to maintain.
  • Separate bash scripts do not maintain local variables.

Here is a functional way to ssh and run multiple commands while keeping local context.

LOCAL_VARIABLE=test

run_remote() {
    echo "$LOCAL_VARIABLE"
    ls some_folder; 
    ./someaction.sh 'some params'
    ./some_other_action 'other params'
}

ssh otherhost "$(set); run_remote"

ld: framework not found Pods

This is usually caused by having the .xcodeproj file open instead of .xcworkspace.

When you run 'pod install' for the first time, it will create an .xcworkspace file, which includes your original .xcodeproj and a Pods project. You'll need to close your .xcodeproj and open the .xcworkspace instead.

This is a common issue when creating a project through Xcode's new project wizard - I often forget that I'm not in a workspace, which is required to get Cocoapods to link correctly.

How are SSL certificate server names resolved/Can I add alternative names using keytool?

How host name verification should be done is defined in RFC 6125, which is quite recent and generalises the practice to all protocols, and replaces RFC 2818, which was specific to HTTPS. (I'm not even sure Java 7 uses RFC 6125, which might be too recent for this.)

From RFC 2818 (Section 3.1):

If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead.

[...]

In some cases, the URI is specified as an IP address rather than a hostname. In this case, the iPAddress subjectAltName must be present in the certificate and must exactly match the IP in the URI.

Essentially, the specific problem you have comes from the fact that you're using IP addresses in your CN and not a host name. Some browsers might work because not all tools follow this specification strictly, in particular because "most specific" in RFC 2818 isn't clearly defined (see discussions in RFC 6215).

If you're using keytool, as of Java 7, keytool has an option to include a Subject Alternative Name (see the table in the documentation for -ext): you could use -ext san=dns:www.example.com or -ext san=ip:10.0.0.1.

EDIT:

You can request a SAN in OpenSSL by changing openssl.cnf (it will pick the copy in the current directory if you don't want to edit the global configuration, as far as I remember, or you can choose an explicit location using the OPENSSL_CONF environment variable).

Set the following options (find the appropriate sections within brackets first):

[req]
req_extensions = v3_req

[ v3_req ]
subjectAltName=IP:10.0.0.1
# or subjectAltName=DNS:www.example.com

There's also a nice trick to use an environment variable for this (rather in than fixing it in a configuration file) here: http://www.crsr.net/Notes/SSL.html

transform object to array with lodash

If you want some custom mapping (like original Array.prototype.map) of Object into an Array, you can just use _.forEach:

let myObject = {
  key1: "value1",
  key2: "value2",
  // ...
};

let myNewArray = [];

_.forEach(myObject, (value, key) => {
  myNewArray.push({
    someNewKey: key,
    someNewValue: value.toUpperCase() // just an example of new value based on original value
  });
});

// myNewArray => [{ someNewKey: key1, someNewValue: 'VALUE1' }, ... ];

See lodash doc of _.forEach https://lodash.com/docs/#forEach

Long press on UITableView

First add the long press gesture recognizer to the table view:

UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc] 
  initWithTarget:self action:@selector(handleLongPress:)];
lpgr.minimumPressDuration = 2.0; //seconds
lpgr.delegate = self;
[self.myTableView addGestureRecognizer:lpgr];
[lpgr release];

Then in the gesture handler:

-(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer
{
    CGPoint p = [gestureRecognizer locationInView:self.myTableView];

    NSIndexPath *indexPath = [self.myTableView indexPathForRowAtPoint:p];
    if (indexPath == nil) {
        NSLog(@"long press on table view but not on a row");
    } else if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
        NSLog(@"long press on table view at row %ld", indexPath.row);
    } else {
        NSLog(@"gestureRecognizer.state = %ld", gestureRecognizer.state);
    }
}

You have to be careful with this so that it doesn't interfere with the user's normal tapping of the cell and also note that handleLongPress may fire multiple times (this will be due to the gesture recognizer state changes).

HTML Drag And Drop On Mobile Devices

The Sortable JS library is compatible with touch screens and does not require jQuery.

The way it handles touch screens it that you need to touch the screen for about 1 second to start dragging an item.

Also, they present a video test showing that this library is running faster than JQuery UI Sortable.

What exactly does Perl's "bless" do?

For example, if you can be confident that any Bug object is going to be a blessed hash, you can (finally!) fill in the missing code in the Bug::print_me method:

 package Bug;
 sub print_me
 {
     my ($self) = @_;
     print "ID: $self->{id}\n";
     print "$self->{descr}\n";
     print "(Note: problem is fatal)\n" if $self->{type} eq "fatal";
 }

Now, whenever the print_me method is called via a reference to any hash that's been blessed into the Bug class, the $self variable extracts the reference that was passed as the first argument and then the print statements access the various entries of the blessed hash.

javascript unexpected identifier

Yes, you have a } too many. Anyway, compressing yourself tends to result in errors.

function () {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        document.getElementById("content").innerHTML = xmlhttp.responseText;
    }
} // <-- end function?
xmlhttp.open("GET", "data/" + id + ".html", true);
xmlhttp.send();
}

Use Closure Compiler instead.

What's the difference between the atomic and nonatomic attributes?

Atomic means only one thread accesses the variable (static type). Atomic is thread-safe, but it is slow.

Nonatomic means multiple threads access the variable (dynamic type). Nonatomic is thread-unsafe, but it is fast.

How to safely call an async method in C# without await

I end up with this solution :

public async Task MyAsyncMethod()
{
    // do some stuff async, don't return any data
}

public string GetStringData()
{
    // Run async, no warning, exception are catched
    RunAsync(MyAsyncMethod()); 
    return "hello world";
}

private void RunAsync(Task task)
{
    task.ContinueWith(t =>
    {
        ILog log = ServiceLocator.Current.GetInstance<ILog>();
        log.Error("Unexpected Error", t.Exception);

    }, TaskContinuationOptions.OnlyOnFaulted);
}

How can I check if string contains characters & whitespace, not just whitespace?

if (/^\s+$/.test(myString))
{
      //string contains only whitespace
}

this checks for 1 or more whitespace characters, if you it to also match an empty string then replace + with *.

How do you push a Git tag to a branch using a refspec?

For pushing a single tag: git push <reponame> <tagname>

For instance, git push production 1.0.0. Tags are not bound to branches, they are bound to commits.

When you want to have the tag's content in the master branch, do that locally on your machine. I would assume that you continued developing in your local master branch. Then just a git push origin master should suffice.

creating triggers for After Insert, After Update and After Delete in SQL

(Update: overlooked a fault in the matter, I have corrected)

(Update2: I wrote from memory the code screwed up, repaired it)

(Update3: check on SQLFiddle)

create table Derived_Values
  (
    BusinessUnit nvarchar(100) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

create table Derived_Values_Test
  (
    BusinessUnit nvarchar(150)
    ,Questions nvarchar(100)
    ,Answer nvarchar(100)
    )

go

CREATE TRIGGER trgAfterUpdate ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Updated Record -- After Update Trigger.'

    insert into 
        [Derived_Values_Test]
        --(BusinessUnit,Questions, Answer) 
    SELECT 
        @BusinessUnit + i.BusinessUnit, i.Questions, i.Answer
    FROM 
        inserted i
        inner join deleted d on i.BusinessUnit = d.BusinessUnit
end

go

CREATE TRIGGER trgAfterDelete ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Deleted Record -- After Delete Trigger.'

    insert into 
        [Derived_Values_Test]
        --(BusinessUnit,Questions, Answer) 
    SELECT 
        @BusinessUnit + d.BusinessUnit, d.Questions, d.Answer
    FROM 
        deleted d
end

go

insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')

UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');

delete Derived_Values;

and then:

SELECT * FROM Derived_Values;
go

select * from Derived_Values_Test;


Record Count: 0;

BUSINESSUNIT    QUESTIONS   ANSWER
Updated Record -- After Update Trigger.BU1  Q11 Updated Answers A11
Deleted Record -- After Delete Trigger.BU1  Q11 A11
Updated Record -- After Update Trigger.BU1  Q12 Updated Answers A12
Deleted Record -- After Delete Trigger.BU1  Q12 A12
Updated Record -- After Update Trigger.BU2  Q21 Updated Answers A21
Deleted Record -- After Delete Trigger.BU2  Q21 A21
Updated Record -- After Update Trigger.BU2  Q22 Updated Answers A22
Deleted Record -- After Delete Trigger.BU2  Q22 A22

(Update4: If you want to sync: SQLFiddle)

create table Derived_Values
  (
    BusinessUnit nvarchar(100) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

create table Derived_Values_Test
  (
    BusinessUnit nvarchar(150) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values_Test ADD CONSTRAINT PK_Derived_Values_Test
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

CREATE TRIGGER trgAfterInsert ON  [Derived_Values]
FOR INSERT
AS  
begin
    insert
        [Derived_Values_Test]
        (BusinessUnit,Questions,Answer)
    SELECT 
        i.BusinessUnit, i.Questions, i.Answer
    FROM 
        inserted i
end

go


CREATE TRIGGER trgAfterUpdate ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Updated Record -- After Update Trigger.'

    update
        [Derived_Values_Test]
    set
        --BusinessUnit = i.BusinessUnit
        --,Questions = i.Questions
        Answer = i.Answer
    from
        [Derived_Values]
        inner join inserted i 
    on
        [Derived_Values].BusinessUnit = i.BusinessUnit
        and
        [Derived_Values].Questions = i.Questions
end

go

CREATE TRIGGER trgAfterDelete ON  [Derived_Values]
FOR DELETE
AS  
begin
    delete 
        [Derived_Values_Test]
    from
        [Derived_Values_Test]
        inner join deleted d 
    on
        [Derived_Values_Test].BusinessUnit = d.BusinessUnit
        and
        [Derived_Values_Test].Questions = d.Questions
end

go

insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')

UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');

--delete Derived_Values;

And then:

SELECT * FROM Derived_Values;
go

select * from Derived_Values_Test;


BUSINESSUNIT    QUESTIONS   ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22

BUSINESSUNIT    QUESTIONS   ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22

CSS: Control space between bullet and <li>

Old question, but the :before pseudo element works well here.

<style>
    li:before {
        content: "";
        display: inline-block;
        height: 1rem;  // or px or em or whatever
        width: .5rem;  // or whatever space you want
    }
</style>

It works really well and doesn't require many extra rules or html.

<ul>
    <li>Some content</li>
    <li>Some other content</li>
</ul>

Cheers!

What is the correct SQL type to store a .Net Timespan with values > 24:00:00?

Thanks for the advice. As there is no equivalent in SQL server. I simply created a 2nd field which converted the TimeSpan to ticks and stored that in the DB. I then prevented storing the TimeSpan

public Int64 ValidityPeriodTicks { get; set; }

[NotMapped]
public TimeSpan ValidityPeriod
{
    get { return TimeSpan.FromTicks(ValidityPeriodTicks); }
    set { ValidityPeriodTicks = value.Ticks; }
}

TypeError: method() takes 1 positional argument but 2 were given

In simple words.

In Python you should add self argument as the first argument to all defined methods in classes:

class MyClass:
  def method(self, arg):
    print(arg)

Then you can use your method according to your intuition:

>>> my_object = MyClass()
>>> my_object.method("foo")
foo

This should solve your problem :)

For a better understanding, you can also read the answers to this question: What is the purpose of self?

How to write MySQL query where A contains ( "a" or "b" )

I user for searching the size of motorcycle :

For example : Data = "Tire cycle size 70 / 90 - 16"

i can search with "70 90 16"

$searchTerms = preg_split("/[\s,-\/?!]+/", $itemName);

foreach ($searchTerms as $term) {
        $term = trim($term);
            if (!empty($term)) {
            $searchTermBits[] = "name LIKE '%$term%'";
            }
        }

$query = "SELECT * FROM item WHERE " .implode(' AND ', $searchTermBits);

Can I add background color only for padding?

the answers said all the possible solutions

I have another one with BOX-SHADOW

here it is JSFIDDLE

and the code

nav {
    margin:0px auto;
    width:100%;
    height:50px;
    background-color:grey;
    float:left;
    padding:10px;
    border:2px solid red;
    box-shadow: 0 0 0 10px blue inset;
}

it also support in IE9, so It's better than gradient solution, add proper prefixes for more support

IE8 dont support it, what a shame !

Apache giving 403 forbidden errors

restorecon command works as below :

restorecon -v -R /var/www/html/

Reusing output from last command in Bash

If you are on mac, and don't mind storing your output in the clipboard instead of writing to a variable, you can use pbcopy and pbpaste as a workaround.

For example, instead of doing this to find a file and diff its contents with another file:

$ find app -name 'one.php' 
/var/bar/app/one.php

$ diff /var/bar/app/one.php /var/bar/two.php

You could do this:

$ find app -name 'one.php' | pbcopy
$ diff $(pbpaste) /var/bar/two.php

The string /var/bar/app/one.php is in the clipboard when you run the first command.

By the way, pb in pbcopy and pbpaste stand for pasteboard, a synonym for clipboard.

Using success/error/finally/catch with Promises in AngularJS

Promises are an abstraction over statements that allow us to express ourselves synchronously with asynchronous code. They represent a execution of a one time task.

They also provide exception handling, just like normal code, you can return from a promise or you can throw.

What you'd want in synchronous code is:

try{
  try{
      var res = $http.getSync("url");
      res = someProcessingOf(res);
  } catch (e) {
      console.log("Got an error!",e);
      throw e; // rethrow to not marked as handled
  }
  // do more stuff with res
} catch (e){
     // handle errors in processing or in error.
}

The promisified version is very similar:

$http.get("url").
then(someProcessingOf).
catch(function(e){
   console.log("got an error in initial processing",e);
   throw e; // rethrow to not marked as handled, 
            // in $q it's better to `return $q.reject(e)` here
}).then(function(res){
    // do more stuff
}).catch(function(e){
    // handle errors in processing or in error.
});

Convert a Map<String, String> to a POJO

Well, you can achieve that with Jackson, too. (and it seems to be more comfortable since you were considering using jackson).

Use ObjectMapper's convertValue method:

final ObjectMapper mapper = new ObjectMapper(); // jackson's objectmapper
final MyPojo pojo = mapper.convertValue(map, MyPojo.class);

No need to convert into JSON string or something else; direct conversion does much faster.

Change default global installation directory for node.js modules in Windows?

Using a Windows symbolic link from the C:\Users{username}\AppData\Roaming\npm and C:\Users{username}\AppData\Roaming\npm-cache paths to the destination worked great for me.

How to add a symbolic link

enter image description here

Wait until page is loaded with Selenium WebDriver for Python

Solution for ajax pages that continuously load data. The previews methods stated do not work. What we can do instead is grab the page dom and hash it and compare old and new hash values together over a delta time.

import time
from selenium import webdriver

def page_has_loaded(driver, sleep_time = 2):
    '''
    Waits for page to completely load by comparing current page hash values.
    '''

    def get_page_hash(driver):
        '''
        Returns html dom hash
        '''
        # can find element by either 'html' tag or by the html 'root' id
        dom = driver.find_element_by_tag_name('html').get_attribute('innerHTML')
        # dom = driver.find_element_by_id('root').get_attribute('innerHTML')
        dom_hash = hash(dom.encode('utf-8'))
        return dom_hash

    page_hash = 'empty'
    page_hash_new = ''
    
    # comparing old and new page DOM hash together to verify the page is fully loaded
    while page_hash != page_hash_new: 
        page_hash = get_page_hash(driver)
        time.sleep(sleep_time)
        page_hash_new = get_page_hash(driver)
        print('<page_has_loaded> - page not loaded')

    print('<page_has_loaded> - page loaded: {}'.format(driver.current_url))

Add a new line to the end of a JtextArea

Instead of using JTextArea.setText(String text), use JTextArea.append(String text).

Appends the given text to the end of the document. Does nothing if the model is null or the string is null or empty.

This will add text on to the end of your JTextArea.

Another option would be to use getText() to get the text from the JTextArea, then manipulate the String (add or remove or change the String), then use setText(String text) to set the text of the JTextArea to be the new String.

Catch multiple exceptions at once?

Catch System.Exception and switch on the types

catch (Exception ex)            
{                
    if (ex is FormatException || ex is OverflowException)
    {
        WebId = Guid.Empty;
        return;
    }

    throw;
}

AngularJS Dropdown required validation

You need to add a name attribute to your dropdown list, then you need to add a required attribute, and then you can reference the error using myForm.[input name].$error.required:

HTML:

        <form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
        <input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
          <select name="service_id" class="Sitedropdown" style="width: 220px;"          
                  ng-model="ServiceID" 
                  ng-options="service.ServiceID as service.ServiceName for service in services"
                  required> 
            <option value="">Select Service</option> 
          </select> 
          <span ng-show="myForm.service_id.$error.required">Select service</span>

        </form>

    Controller:

        function Ctrl($scope) {
          $scope.services = [
            {ServiceID: 1, ServiceName: 'Service1'},
            {ServiceID: 2, ServiceName: 'Service2'},
            {ServiceID: 3, ServiceName: 'Service3'}
          ];

    $scope.save = function(myForm) {
    console.log('Selected Value: '+ myForm.service_id.$modelValue);
    alert('Data Saved! without validate');
    };
        }

Here's a working plunker.

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

Try this one -

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

php date validation

Use it:

function validate_Date($mydate,$format = 'DD-MM-YYYY') {

    if ($format == 'YYYY-MM-DD') list($year, $month, $day) = explode('-', $mydate);
    if ($format == 'YYYY/MM/DD') list($year, $month, $day) = explode('/', $mydate);
    if ($format == 'YYYY.MM.DD') list($year, $month, $day) = explode('.', $mydate);

    if ($format == 'DD-MM-YYYY') list($day, $month, $year) = explode('-', $mydate);
    if ($format == 'DD/MM/YYYY') list($day, $month, $year) = explode('/', $mydate);
    if ($format == 'DD.MM.YYYY') list($day, $month, $year) = explode('.', $mydate);

    if ($format == 'MM-DD-YYYY') list($month, $day, $year) = explode('-', $mydate);
    if ($format == 'MM/DD/YYYY') list($month, $day, $year) = explode('/', $mydate);
    if ($format == 'MM.DD.YYYY') list($month, $day, $year) = explode('.', $mydate);       

    if (is_numeric($year) && is_numeric($month) && is_numeric($day))
        return checkdate($month,$day,$year);
    return false;           
}         

session handling in jquery

Assuming you're referring to this plugin, your code should be:

// To Store
$(function() {
    $.session.set("myVar", "value");
});


// To Read
$(function() {
    alert($.session.get("myVar"));
});

Before using a plugin, remember to read its documentation in order to learn how to use it. In this case, an usage example can be found in the README.markdown file, which is displayed on the project page.

SELECT * WHERE NOT EXISTS

You didn't join the table in your query.

Your original query will always return nothing unless there are no records at all in eotm_dyn, in which case it will return everything.

Assuming these tables should be joined on employeeID, use the following:

SELECT  *
FROM    employees e
WHERE   NOT EXISTS
        (
        SELECT  null 
        FROM    eotm_dyn d
        WHERE   d.employeeID = e.id
        )

You can join these tables with a LEFT JOIN keyword and filter out the NULL's, but this will likely be less efficient than using NOT EXISTS.

How to enumerate an enum

I made some extensions for easy enum usage. Maybe someone can use it...

public static class EnumExtensions
{
    /// <summary>
    /// Gets all items for an enum value.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="value">The value.</param>
    /// <returns></returns>
    public static IEnumerable<T> GetAllItems<T>(this Enum value)
    {
        foreach (object item in Enum.GetValues(typeof(T)))
        {
            yield return (T)item;
        }
    }

    /// <summary>
    /// Gets all items for an enum type.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="value">The value.</param>
    /// <returns></returns>
    public static IEnumerable<T> GetAllItems<T>() where T : struct
    {
        foreach (object item in Enum.GetValues(typeof(T)))
        {
            yield return (T)item;
        }
    }

    /// <summary>
    /// Gets all combined items from an enum value.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="value">The value.</param>
    /// <returns></returns>
    /// <example>
    /// Displays ValueA and ValueB.
    /// <code>
    /// EnumExample dummy = EnumExample.Combi;
    /// foreach (var item in dummy.GetAllSelectedItems<EnumExample>())
    /// {
    ///    Console.WriteLine(item);
    /// }
    /// </code>
    /// </example>
    public static IEnumerable<T> GetAllSelectedItems<T>(this Enum value)
    {
        int valueAsInt = Convert.ToInt32(value, CultureInfo.InvariantCulture);

        foreach (object item in Enum.GetValues(typeof(T)))
        {
            int itemAsInt = Convert.ToInt32(item, CultureInfo.InvariantCulture);

            if (itemAsInt == (valueAsInt & itemAsInt))
            {
                yield return (T)item;
            }
        }
    }

    /// <summary>
    /// Determines whether the enum value contains a specific value.
    /// </summary>
    /// <param name="value">The value.</param>
    /// <param name="request">The request.</param>
    /// <returns>
    ///     <c>true</c> if value contains the specified value; otherwise, <c>false</c>.
    /// </returns>
    /// <example>
    /// <code>
    /// EnumExample dummy = EnumExample.Combi;
    /// if (dummy.Contains<EnumExample>(EnumExample.ValueA))
    /// {
    ///     Console.WriteLine("dummy contains EnumExample.ValueA");
    /// }
    /// </code>
    /// </example>
    public static bool Contains<T>(this Enum value, T request)
    {
        int valueAsInt = Convert.ToInt32(value, CultureInfo.InvariantCulture);
        int requestAsInt = Convert.ToInt32(request, CultureInfo.InvariantCulture);

        if (requestAsInt == (valueAsInt & requestAsInt))
        {
            return true;
        }

        return false;
    }
}

The enum itself must be decorated with the FlagsAttribute:

[Flags]
public enum EnumExample
{
    ValueA = 1,
    ValueB = 2,
    ValueC = 4,
    ValueD = 8,
    Combi = ValueA | ValueB
}

Check if input is integer type in C

num will always contain an integer because it's an int. The real problem with your code is that you don't check the scanf return value. scanf returns the number of successfully read items, so in this case it must return 1 for valid values. If not, an invalid integer value was entered and the num variable did probably not get changed (i.e. still has an arbitrary value because you didn't initialize it).

As of your comment, you only want to allow the user to enter an integer followed by the enter key. Unfortunately, this can't be simply achieved by scanf("%d\n"), but here's a trick to do it:

int num;
char term;
if(scanf("%d%c", &num, &term) != 2 || term != '\n')
    printf("failure\n");
else
    printf("valid integer followed by enter key\n");

SQLite: How do I save the result of a query as a CSV file?

From here and d5e5's comment:

You'll have to switch the output to csv-mode and switch to file output.

sqlite> .mode csv
sqlite> .output test.csv
sqlite> select * from tbl1;
sqlite> .output stdout

Can we install Android OS on any Windows Phone and vice versa, and same with iPhone and vice versa?

Android needs to be compiled for every hardware plattform / every device model seperatly with the specific drivers etc. If you manage to do that you need also break the security arrangements every manufacturer implements to prevent the installation of other software - these are also different between each model / manufacturer. So it is possible at in theory, but only there :-)

How to add java plugin for Firefox on Linux?

Do you want the JDK or the JRE? Anyways, I had this problem too, a few weeks ago. I followed the instructions here and it worked:

http://www.backtrack-linux.org/wiki/index.php/Java_Install

NOTE: Before installing Java make sure you kill Firefox.

root@bt:~# killall -9 /opt/firefox/firefox-bin

You can download java from the official website. (Download tar.gz version)

We first create the directory and place java there:

root@bt:~# mkdir /opt/java

root@bt:~# mv -f jre1.7.0_05/ /opt/java/

Final changes.

root@bt:~# update-alternatives --install /usr/bin/java java /opt/java/jre1.7.0_05/bin/java 1

root@bt:~# update-alternatives --set java /opt/java/jre1.7.0_05/bin/java

root@bt:~# export JAVA_HOME="/opt/java/jre1.7.0_05"

Adding the plugin to Firefox.

For Java 7 (32 bit)

root@bt:~# ln -sf $JAVA_HOME/lib/i386/libnpjp2.so /usr/lib/mozilla/plugins/

For Java 8 (64 bit)

root@bt:~# ln -sf $JAVA_HOME/jre/lib/amd64/libnpjp2.so /usr/lib/mozilla/plugins/

Testing the plugin.

root@bt:~# firefox http://java.com/en/download/testjava.jsp

How can I remove all my changes in my SVN working directory?

If you have no changes, you can always be really thorough and/or lazy and do...

rm -rf *
svn update

But, no really, do not do that unless you are really sure that the nuke-from-space option is what you want!! This has the advantage of also nuking all build cruft, temporary files, and things that SVN ignores.

The more correct solution is to use the revert command:

svn revert -R .

The -R causes subversion to recurse and revert everything in and below the current working directory.

Python list subtraction operation

Use a list comprehension:

[item for item in x if item not in y]

If you want to use the - infix syntax, you can just do:

class MyList(list):
    def __init__(self, *args):
        super(MyList, self).__init__(args)

    def __sub__(self, other):
        return self.__class__(*[item for item in self if item not in other])

you can then use it like:

x = MyList(1, 2, 3, 4)
y = MyList(2, 5, 2)
z = x - y   

But if you don't absolutely need list properties (for example, ordering), just use sets as the other answers recommend.

Difference between webdriver.get() and webdriver.navigate()

Navigating

The first thing you’ll want to do with WebDriver is navigate to a page. The normal way to do this is by calling get:

driver.get("http://www.google.com");

WebDriver will wait until the page has fully loaded (that is, the onload event has fired) before returning control to your test or script. It’s worth noting that if your page uses a lot of AJAX on load then WebDriver may not know when it has completely loaded. If you need to ensure such pages are fully loaded then you can use waits.

Navigation: History and Location

Earlier, we covered navigating to a page using the get command (driver.get("http://www.example.com")) As you’ve seen, WebDriver has a number of smaller, task-focused interfaces, and navigation is a useful task. Because loading a page is such a fundamental requirement, the method to do this lives on the main WebDriver interface, but it’s simply a synonym to:

driver.navigate().to("http://www.example.com");

To reiterate: navigate().to() and get() do exactly the same thing. One's just a lot easier to type than the other!

The navigate interface also exposes the ability to move backwards and forwards in your browser’s history:

driver.navigate().forward();
driver.navigate().back();

(Emphasis added)

CRC32 C or C++ implementation

I am the author of the source code at the specified link. While the intention of the source code license is not clear (it will be later today), the code is in fact open and free for use in your free or commercial applications with no strings attached.

How to populate a dropdownlist with json data in jquery?

//javascript
//teams.Table does not exist

function OnSuccessJSON(data, status) {
    var teams = eval('(' + data.d + ')');
    var listItems = "";
    for (var i = 0; i < teams.length; i++) {
      listItems += "<option value='" + teams[i][0]+ "'>" + teams[i][1] + "</option>";
    }
    $("#<%=ddlTeams.ClientID%>").html(listItems);
} 

How can I check if a directory exists?

You might use stat() and pass it the address of a struct stat, then check its member st_mode for having S_IFDIR set.

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

...

char d[] = "mydir";

struct stat s = {0};

if (!stat(d, &s))
  printf("'%s' is %sa directory.\n", d, (s.st_mode & S_IFDIR)  : "" ? "not ");
  // (s.st_mode & S_IFDIR) can be replaced with S_ISDIR(s.st_mode)
else
  perror("stat()");

Bootstrap 4 dropdown with search

As of 10. July 2017, the issue of Bootstrap 4 support with bootstrap-select is still open. In the open issue, there are some ad-hoc solutions which you could try with your project.

Or you could use a library like Select2 and add a theme to match Bootstrap 4. Here is an example: Select 2 with Bootstrap 4 (disclaimer: I'm not the author of this blog post and I haven't verified if this still works with the all versions of Bootstrap 4).

convert from Color to brush

SolidColorBrush brush = new SolidColorBrush( Color.FromArgb(255,255,139,0) )

How do I make jQuery wait for an Ajax call to finish before it returns?

The underlying XMLHttpRequest object (used by jQuery to make the request) supports the asynchronous property. Set it to false. Like

async: false

Get values from an object in JavaScript

If you want to do this in a single line, try:

Object.keys(a).map(function(key){return a[key]})

Mythical man month 10 lines per developer day - how close on large projects?

You should stop using this metric, it is meaningless for the most part. Cohesion, coupling and complexity are more important metrics than lines of code.

How to convert Django Model object to dict with its fields and values?

@Zags solution was gorgeous!

I would add, though, a condition for datefields in order to make it JSON friendly.

Bonus Round

If you want a django model that has a better python command-line display, have your models child class the following:

from django.db import models
from django.db.models.fields.related import ManyToManyField

class PrintableModel(models.Model):
    def __repr__(self):
        return str(self.to_dict())

    def to_dict(self):
        opts = self._meta
        data = {}
        for f in opts.concrete_fields + opts.many_to_many:
            if isinstance(f, ManyToManyField):
                if self.pk is None:
                    data[f.name] = []
                else:
                    data[f.name] = list(f.value_from_object(self).values_list('pk', flat=True))
            elif isinstance(f, DateTimeField):
                if f.value_from_object(self) is not None:
                    data[f.name] = f.value_from_object(self).timestamp()
            else:
                data[f.name] = None
            else:
                data[f.name] = f.value_from_object(self)
        return data

    class Meta:
        abstract = True

So, for example, if we define our models as such:

class OtherModel(PrintableModel): pass

class SomeModel(PrintableModel):
    value = models.IntegerField()
    value2 = models.IntegerField(editable=False)
    created = models.DateTimeField(auto_now_add=True)
    reference1 = models.ForeignKey(OtherModel, related_name="ref1")
    reference2 = models.ManyToManyField(OtherModel, related_name="ref2")

Calling SomeModel.objects.first() now gives output like this:

{'created': 1426552454.926738,
'value': 1, 'value2': 2, 'reference1': 1, u'id': 1, 'reference2': [1]}

Primitive type 'short' - casting in Java

AFAIS, nobody mentions of final usage for that. If you modify your last example and define variables a and b as final variables, then the compiler is assured that their sum, value 5 , can be assigned to a variable of type byte, without any loss of precision. In this case, the compiler is good to assign the sum of a and b to c . Here’s the modified code:

final byte a = 2;
final byte b = 3;
byte c = a + b;

How do I detect whether a Python variable is a function?

Instead of checking for '__call__' (which is not exclusive to functions), you can check whether a user-defined function has attributes func_name, func_doc, etc. This does not work for methods.

>>> def x(): pass
... 
>>> hasattr(x, 'func_name')
True

Another way of checking is using the isfunction() method from the inspect module.

>>> import inspect
>>> inspect.isfunction(x)
True

To check if an object is a method, use inspect.ismethod()

Get Root Directory Path of a PHP project

I want to point to the way Wordpress handles this:

define( 'ABSPATH', dirname( __FILE__ ) . '/' );

As Wordpress is very heavy used all over the web and also works fine locally I have much trust in this method. You can find this definition on the bottom of your wordpress wp-config.php file

Load data from txt with pandas

Based on the latest changes in pandas, you can use, read_csv , read_table is deprecated:

import pandas as pd
pd.read_csv("file.txt", sep = "\t")

How to adjust the size of y axis labels only in R?

Don't know what you are doing (helpful to show what you tried that didn't work), but your claim that cex.axis only affects the x-axis is not true:

set.seed(123)
foo <- data.frame(X = rnorm(10), Y = rnorm(10))
plot(Y ~ X, data = foo, cex.axis = 3)

at least for me with:

> sessionInfo()
R version 2.11.1 Patched (2010-08-17 r52767)
Platform: x86_64-unknown-linux-gnu (64-bit)

locale:
 [1] LC_CTYPE=en_GB.UTF-8       LC_NUMERIC=C              
 [3] LC_TIME=en_GB.UTF-8        LC_COLLATE=en_GB.UTF-8    
 [5] LC_MONETARY=C              LC_MESSAGES=en_GB.UTF-8   
 [7] LC_PAPER=en_GB.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=en_GB.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] grid      stats     graphics  grDevices utils     datasets  methods  
[8] base     

other attached packages:
[1] ggplot2_0.8.8 proto_0.3-8   reshape_0.8.3 plyr_1.2.1   

loaded via a namespace (and not attached):
[1] digest_0.4.2 tools_2.11.1

Also, cex.axis affects the labelling of tick marks. cex.lab is used to control what R call the axis labels.

plot(Y ~ X, data = foo, cex.lab = 3)

but even that works for both the x- and y-axis.


Following up Jens' comment about using barplot(). Check out the cex.names argument to barplot(), which allows you to control the bar labels:

dat <- rpois(10, 3) names(dat) <- LETTERS[1:10] barplot(dat, cex.names = 3, cex.axis = 2)

As you mention that cex.axis was only affecting the x-axis I presume you had horiz = TRUE in your barplot() call as well? As the bar labels are not drawn with an axis() call, applying Joris' (otherwise very useful) answer with individual axis() calls won't help in this situation with you using barplot()

HTH

Resize to fit image in div, and center horizontally and vertically

SOLUTION

<style>
.container {
    margin: 10px;
    width: 115px;
    height: 115px;
    line-height: 115px;
    text-align: center;
    border: 1px solid red;
    background-image: url("http://i.imgur.com/H9lpVkZ.jpg");
    background-repeat: no-repeat;
    background-position: center;
    background-size: contain;

}

</style>

<div class='container'>
</div>

<div class='container' style='width:50px;height:100px;line-height:100px'>
</div>

<div class='container' style='width:140px;height:70px;line-height:70px'>
</div>

Xcode error: Code signing is required for product type 'Application' in SDK 'iOS 10.0'

With Xcode-8.1 & iOS-10.1

  1. Add your Apple ID in Xcode Preferences > Accounts > Add Apple ID:

Step 1

  1. Enable signing to Automatically && Select Team that you have created before:

Step 2

  1. Change the Bundle Identifier:

Step 3

  1. Code Signing to iOS Developer:

Step 4

  1. Provision profile to Automatic:

Step 5

You can now run your project on a device!

Using mysql concat() in WHERE clause?

You can try this:

select * FROM table where (concat(first_name, ' ', last_name)) = $search_term;

Understanding [TCP ACKed unseen segment] [TCP Previous segment not captured]

Another cause of "TCP ACKed Unseen" is the number of packets that may get dropped in a capture. If I run an unfiltered capture for all traffic on a busy interface, I will sometimes see a large number of 'dropped' packets after stopping tshark.

On the last capture I did when I saw this, I had 2893204 packets captured, but once I hit Ctrl-C, I got a 87581 packets dropped message. Thats a 3% loss, so when wireshark opens the capture, its likely to be missing packets and report "unseen" packets.

As I mentioned, I captured a really busy interface with no capture filter, so tshark had to sort all packets, when I use a capture filter to remove some of the noise, I no longer get the error.

How to convert milliseconds into human readable form?

You should use the datetime functions of whatever language you're using, but, just for fun here's the code:

int milliseconds = someNumber;

int seconds = milliseconds / 1000;

int minutes = seconds / 60;

seconds %= 60;

int hours = minutes / 60;

minutes %= 60;

int days = hours / 24;

hours %= 24;

How to convert HTML to PDF using iText

This links might be helpful to convert.

https://code.google.com/p/flying-saucer/

https://today.java.net/pub/a/today/2007/06/26/generating-pdfs-with-flying-saucer-and-itext.html

If it is a college Project, you can even go for these, http://pd4ml.com/examples.htm

Example is given to convert HTML to PDF

Binary Data Posting with curl

You don't need --header "Content-Length: $LENGTH".

curl --request POST --data-binary "@template_entry.xml" $URL

Note that GET request does not support content body widely.

Also remember that POST request have 2 different coding schema. This is first form:

  $ nc -l -p 6666 &
  $ curl  --request POST --data-binary "@README" http://localhost:6666

POST / HTTP/1.1
User-Agent: curl/7.21.0 (x86_64-pc-linux-gnu) libcurl/7.21.0 OpenSSL/0.9.8o zlib/1.2.3.4 libidn/1.15 libssh2/1.2.6
Host: localhost:6666
Accept: */*
Content-Length: 9309
Content-Type: application/x-www-form-urlencoded
Expect: 100-continue

.. -*- mode: rst; coding: cp1251; fill-column: 80 -*-
.. rst2html.py README README.html
.. contents::

You probably request this:

-F/--form name=content
           (HTTP) This lets curl emulate a filled-in form in
              which a user has pressed the submit button. This
              causes curl to POST data using the Content- Type
              multipart/form-data according to RFC2388. This
              enables uploading of binary files etc. To force the
              'content' part to be a file, prefix the file name
              with an @ sign. To just get the content part from a
              file, prefix the file name with the symbol <. The
              difference between @ and < is then that @ makes a
              file get attached in the post as a file upload,
              while the < makes a text field and just get the
              contents for that text field from a file.

Randomize numbers with jQuery?

Javascript has a random() available. Take a look at Math.random().

Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?

It's nice to have your site be accessible by users with JavaScript disabled, in which case the href points to a page that performs the same action as the JavaScript being executed. Otherwise I use "#" with a "return false;" to prevent the default action (scroll to top of the page) as others have mentioned.

Googling for "javascript:void(0)" provides a lot of information on this topic. Some of them, like this one mention reasons to NOT use void(0).

Should I mix AngularJS with a PHP framework?

It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.

It is indeed possible to have PHP render partials and whole views, but I would not recommend it.

To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be easier to maintain, and will be more user friendly.

I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.

Using PHP to render the view:

/user/account

if($loggedIn)
{
    echo "<p>Logged in as ".$user."</p>";
}
else
{
    echo "Please log in.";
}

How the same problem can be solved with an API centric approach by outputting JSON like this:

api/auth/

{
  authorized:true,
  user: {
      username: 'Joe', 
      securityToken: 'secret'
  }
}

and in Angular you could do a get, and handle the response client side.

$http.post("http://example.com/api/auth", {})
.success(function(data) {
    $scope.isLoggedIn = data.authorized;
});

To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.

Difference between chr(13) and chr(10)

Chr(10) is the Line Feed character and Chr(13) is the Carriage Return character.

You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.


Historically, Line Feed would move down a line but not return to column 1:

This  
    is  
        a  
            test.

Similarly Carriage Return would return to column 1 but not move down a line:

This  
is  
a  
test.

Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.

Using Lato fonts in my css (@font-face)

Well, you're missing the letter 'd' in url("~/fonts/Lato-Bol.ttf"); - but assuming that's not it, I would open up your page with developer tools in Chrome and make sure there's no errors loading any of the files (you would probably see an issue in the JavaScript console, or you can check the Network tab and see if anything is red).

(I don't see anything obviously wrong with the code you have posted above)

Other things to check: 1) Are you including your CSS file in your html above the lines where you are trying to use the font-family style? 2) What do you see in the CSS panel in the developer tools for that div? Is font-family: lato crossed out?

What does "./" (dot slash) refer to in terms of an HTML file path location?

For example css files are in folder named CSS and html files are in folder HTML, and both these are in folder named XYZ means we refer css files in html as

<link rel="stylesheet" type="text/css" href="./../CSS/style.css" />

Here .. moves up to HTML
and . refers to the current directory XYZ

---by this logic you would just reference as:

<link rel="stylesheet" type="text/css" href="CSS/style.css" />

Docker-Compose persistent data MySQL

first, you need to delete all old mysql data using

docker-compose down -v

after that add two lines in your docker-compose.yml

volumes:
  - mysql-data:/var/lib/mysql

and

volumes:
  mysql-data:

your final docker-compose.yml will looks like

version: '3.1'

services:
  php:
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - 80:80
    volumes:
      - ./src:/var/www/html/
  db:
    image: mysql
    command: --default-authentication-plugin=mysql_native_password
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: example
    volumes:
      - mysql-data:/var/lib/mysql

  adminer:
    image: adminer
    restart: always
    ports:
      - 8080:8080
volumes:
  mysql-data:

after that use this command

docker-compose up -d

now your data will persistent and will not be deleted even after using this command

docker-compose down

extra:- but if you want to delete all data then you will use

docker-compose down -v

.gitignore and "The following untracked working tree files would be overwritten by checkout"

In my case, the problem was with the submodules. master was merged with another branch which added a new submodule to the project. The branch I was trying to checkout didn't have it, that's why git was complaining about untracked files and none of the other suggested solutions worked for me. I forced the checkout to my new branch, and pulled master.

  • git checkout -f my_branch
  • git pull origin master
  • git submodule update --init

Get the selected option id with jQuery

var id = $(this).find('option:selected').attr('id');

then you do whatever you want with selectedIndex

I've reedited my answer ... since selectedIndex isn't a good variable to give example...

mysql alphabetical order

but result showing all records starting with a or c or d i want to show records only starting with b

You should use WHERE in that case:

select name from user where name = 'b' order by name

If you want to allow regex, you can use the LIKE operator there too if you want. Example:

select name from user where name like 'b%' order by name

That will select records starting with b. Following query on the other hand will select all rows where b is found anywhere in the column:

select name from user where name like '%b%' order by name

How do I install the OpenSSL libraries on Ubuntu?

Another way to install openssl library from source code on Ubuntu, follows steps below, here WORKDIR is your working directory:

sudo apt-get install pkg-config
cd WORKDIR
git clone https://github.com/openssl/openssl.git
cd openssl
./config
make
sudo make install
# Open file /etc/ld.so.conf, add a new line: "/usr/local/lib" at EOF
sudo ldconfig

downcast and upcast

Upcasting and Downcasting:

Upcasting: Casting from Derived-Class to Base Class Downcasting: Casting from Base Class to Derived Class

Let's understand the same as an example:

Consider two classes Shape as My parent class and Circle as a Derived class, defined as follows:

class Shape
{
    public int Width { get; set; }
    public int Height { get; set; }
}

class Circle : Shape
{
    public int Radius { get; set; }
    public bool FillColor { get; set; }
}

Upcasting:

Shape s = new Shape();

Circle c= s;

Both c and s are referencing to the same memory location, but both of them have different views i.e using "c" reference you can access all the properties of the base class and derived class as well but using "s" reference you can access properties of the only parent class.

A practical example of upcasting is Stream class which is baseclass of all types of stream reader of .net framework:

StreamReader reader = new StreamReader(new FileStreamReader());

here, FileStreamReader() is upcasted to streadm reder.

Downcasting:

Shape s = new Circle(); here as explained above, view of s is the only parent, in order to make it for both parent and a child we need to downcast it

var c = (Circle) s;

The practical example of Downcasting is button class of WPF.

Open local folder from link

Linking to local resources is disabled in all modern browsers due to security restrictions.

For Firefox:

For security purposes, Mozilla applications block links to local files (and directories) from remote files. This includes linking to files on your hard drive, on mapped network drives, and accessible via Uniform Naming Convention (UNC) paths. This prevents a number of unpleasant possibilities, including:

  • Allowing sites to detect your operating system by checking default installation paths
  • Allowing sites to exploit system vulnerabilities (e.g., C:\con\con in Windows 95/98)
  • Allowing sites to detect browser preferences or read sensitive data

for IE:

Internet Explorer 6 Service Pack 1 (SP1) no longer allows browsing a local machine from the Internet zone. For instance, if an Internet site contains a link to a local file, Internet Explorer 6 SP1 displays a blank page when a user clicks on the link. Previous versions of Windows Internet Explorer followed the link to the local file.

for Opera (in the context of a security advisory, I'm sure there is a more canonical link for this):

As a security precaution, Opera does not allow Web pages to link to files on the user's local disk

Trying to include a library, but keep getting 'undefined reference to' messages

If the .c source files are converted .cpp (like as in parsec), then the extern needs to be followed by "C" as in

extern "C" void foo();

How to upload a file in Django?

I also had the similar requirement. Most of the examples on net are asking to create models and create forms which I did not wanna use. Here is my final code.

if request.method == 'POST':
    file1 = request.FILES['file']
    contentOfFile = file1.read()
    if file1:
        return render(request, 'blogapp/Statistics.html', {'file': file1, 'contentOfFile': contentOfFile})

And in HTML to upload I wrote:

{% block content %}
    <h1>File content</h1>
    <form action="{% url 'blogapp:uploadComplete'%}" method="post" enctype="multipart/form-data">
         {% csrf_token %}
        <input id="uploadbutton" type="file" value="Browse" name="file" accept="text/csv" />
        <input type="submit" value="Upload" />
    </form>
    {% endblock %}

Following is the HTML which displays content of file:

{% block content %}
    <h3>File uploaded successfully</h3>
    {{file.name}}
    </br>content = {{contentOfFile}}
{% endblock %}

C# switch statement limitations - why?

I have virtually no knowledge of C#, but I suspect that either switch was simply taken as it occurs in other languages without thinking about making it more general or the developer decided that extending it was not worth it.

Strictly speaking you are absolutely right that there is no reason to put these restrictions on it. One might suspect that the reason is that for the allowed cases the implementation is very efficient (as suggested by Brian Ensink (44921)), but I doubt the implementation is very efficient (w.r.t. if-statements) if I use integers and some random cases (e.g. 345, -4574 and 1234203). And in any case, what is the harm in allowing it for everything (or at least more) and saying that it is only efficient for specific cases (such as (almost) consecutive numbers).

I can, however, imagine that one might want to exclude types because of reasons such as the one given by lomaxx (44918).

Edit: @Henk (44970): If Strings are maximally shared, strings with equal content will be pointers to the same memory location as well. Then, if you can make sure that the strings used in the cases are stored consecutively in memory, you can very efficiently implement the switch (i.e. with execution in the order of 2 compares, an addition and two jumps).

Connect to Amazon EC2 file directory using Filezilla and SFTP

Old question but what I've found is that, all you need is to add the ppk file. Settings -> Connections -> SFTP -> Add keyfile User name and the host is same as what you would provide when using putty which is mentioned in http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-connect-to-instance-linux.html Might help someone.

How to remove items from a list while iterating?

One possible solution, useful if you want not only remove some things, but also do something with all elements in a single loop:

alist = ['good', 'bad', 'good', 'bad', 'good']
i = 0
for x in alist[:]:
    if x == 'bad':
        alist.pop(i)
        i -= 1
    # do something cool with x or just print x
    print(x)
    i += 1

Truncate (not round off) decimal numbers in javascript

Number.prototype.truncate = function(places) {
  var shift = Math.pow(10, places);

  return Math.trunc(this * shift) / shift;
};

SQL query to make all data in a column UPPER CASE?

If you want to only update on rows that are not currently uppercase (instead of all rows), you'd need to identify the difference using COLLATE like this:

UPDATE MyTable
SET    MyColumn = UPPER(MyColumn)
WHERE  MyColumn != UPPER(MyColumn) COLLATE Latin1_General_CS_AS 

A Bit About Collation

Cases sensitivity is based on your collation settings, and is typically case insensitive by default.

Collation can be set at the Server, Database, Column, or Query Level:

-- Server
SELECT SERVERPROPERTY('COLLATION')
-- Database
SELECT name, collation_name FROM sys.databases
-- Column 
SELECT COLUMN_NAME, COLLATION_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE CHARACTER_SET_NAME IS NOT NULL

Collation Names specify how a string should be encoded and read, for example:

  • Latin1_General_CI_AS ? Case Insensitive
  • Latin1_General_CS_AS ? Case Sensitive

Android getActivity() is undefined

In my application, it was enough to use:

myclassname.this

Installing lxml module in python

For RHEL/CentOS, run "python --version" command to find out Python version. E.g. below:

$ python --version 
  Python 2.7.12

Now run "sudo yum search lxml" to find out python*-lxml package.

$ sudo yum search lxml
Failed to set locale, defaulting to C
Loaded plugins: priorities, update-motd, upgrade-helper
1014 packages excluded due to repository priority protections
============================================================================================================= N/S matched: lxml =============================================================================================================
python26-lxml-docs.noarch : Documentation for python-lxml
python27-lxml-docs.noarch : Documentation for python-lxml
python26-lxml.x86_64 : ElementTree-like Python bindings for libxml2 and libxslt
python27-lxml.x86_64 : ElementTree-like Python bindings for libxml2 and libxslt

Now you can choose package as per your Python version and run command like below:

$ sudo yum install python27-lxml.x86_64

Django. Override save for model

I have found one another simple way to store the data into the database

models.py

class LinkModel(models.Model):
    link = models.CharField(max_length=500)
    shortLink = models.CharField(max_length=30,unique=True)

In database I have only 2 variables

views.py

class HomeView(TemplateView):
    def post(self,request, *args, **kwargs):
        form = LinkForm(request.POST)

        if form.is_valid():
            text = form.cleaned_data['link'] # text for link

        dbobj = LinkModel()
        dbobj.link = text
        self.no = self.gen.generateShortLink() # no for shortLink
        dbobj.shortLink = str(self.no)
        dbobj.save()         # Saving from views.py

In this I have created the instance of model in views.py only and putting/saving data into 2 variables from views only.

How do I select a sibling element using jQuery?

Here is a link which is useful to learn about select a siblings element in Jquery.

How do I select a sibling element using jQuery

$("selector").nextAll(); 
$("selector").prev(); 

you can also find an element using Jquery selector

$("h2").siblings('table').find('tr'); 

For more information, refer this link next(), nextAll(), prev(), prevAll(), find() and siblings in JQuery

Cannot use mkdir in home directory: permission denied (Linux Lubuntu)

As @kirbyfan64sos notes in a comment, /home is NOT your home directory (a.k.a. home folder):

The fact that /home is an absolute, literal path that has no user-specific component provides a clue.

While /home happens to be the parent directory of all user-specific home directories on Linux-based systems, you shouldn't even rely on that, given that this differs across platforms: for instance, the equivalent directory on macOS is /Users.

What all Unix platforms DO have in common are the following ways to navigate to / refer to your home directory:

  • Using cd with NO argument changes to your home dir., i.e., makes your home dir. the working directory.
    • e.g.: cd # changes to home dir; e.g., '/home/jdoe'
  • Unquoted ~ by itself / unquoted ~/ at the start of a path string represents your home dir. / a path starting at your home dir.; this is referred to as tilde expansion (see man bash)
    • e.g.: echo ~ # outputs, e.g., '/home/jdoe'
  • $HOME - as part of either unquoted or preferably a double-quoted string - refers to your home dir. HOME is a predefined, user-specific environment variable:
    • e.g.: cd "$HOME/tmp" # changes to your personal folder for temp. files

Thus, to create the desired folder, you could use:

mkdir "$HOME/bin"  # same as: mkdir ~/bin

Note that most locations outside your home dir. require superuser (root user) privileges in order to create files or directories - that's why you ran into the Permission denied error.

WPF Image Dynamically changing Image source during runtime

Try Stretch="UniformToFill" on the Image

CSS Div width percentage and padding without breaking layout

You can also use the CSS calc() function to subtract the width of your padding from the percentage of your container's width.

An example:

width: calc((100%) - (32px))

Just be sure to make the subtracted width equal to the total padding, not just one half. If you pad both sides of the inner div with 16px, then you should subtract 32px from the final width, assuming that the example below is what you want to achieve.

_x000D_
_x000D_
.outer {_x000D_
  width: 200px;_x000D_
  height: 120px;_x000D_
  background-color: black;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
  height: 40px;_x000D_
  top: 30px;_x000D_
  position: relative;_x000D_
  padding: 16px;_x000D_
  background-color: teal;_x000D_
}_x000D_
_x000D_
#inner-1 {_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
#inner-2 {_x000D_
  width: calc((100%) - (32px));_x000D_
}
_x000D_
<div class="outer" id="outer-1">_x000D_
  <div class="inner" id="inner-1"> width of 100% </div>_x000D_
</div>_x000D_
_x000D_
<br>_x000D_
<br>_x000D_
_x000D_
<div class="outer" id="outer-2">_x000D_
  <div class="inner" id="inner-2"> width of 100% - 16px </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

class method generates "TypeError: ... got multiple values for keyword argument ..."

The problem is that the first argument passed to class methods in python is always a copy of the class instance on which the method is called, typically labelled self. If the class is declared thus:

class foo(object):
  def foodo(self, thing=None, thong='not underwear'):
    print thing if thing else "nothing" 
    print 'a thong is',thong

it behaves as expected.

Explanation:

Without self as the first parameter, when myfoo.foodo(thing="something") is executed, the foodo method is called with arguments (myfoo, thing="something"). The instance myfoo is then assigned to thing (since thing is the first declared parameter), but python also attempts to assign "something" to thing, hence the Exception.

To demonstrate, try running this with the original code:

myfoo.foodo("something")
print
print myfoo

You'll output like:

<__main__.foo object at 0x321c290>
a thong is something

<__main__.foo object at 0x321c290>

You can see that 'thing' has been assigned a reference to the instance 'myfoo' of the class 'foo'. This section of the docs explains how function arguments work a bit more.

How to initialize an array in one step using Ruby?

Along with the above answers , you can do this too

    =>  [*'1'.."5"]   #remember *
    => ["1", "2", "3", "4", "5"]

How to query DATETIME field using only date in Microsoft SQL Server?

Test this query.

SELECT *,DATE(chat_reg_date) AS is_date,TIME(chat_reg_time) AS is_time FROM chat WHERE chat_inbox_key='$chat_key' 
                         ORDER BY is_date DESC, is_time DESC

Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET)

@RequestMapping is a class level

@GetMapping is a method-level

With sprint Spring 4.3. and up things have changed. Now you can use @GetMapping on the method that will handle the http request. The class-level @RequestMapping specification is refined with the (method-level)@GetMapping annotation

Here is an example:

@Slf4j
@Controller
@RequestMapping("/orders")/* The @Request-Mapping annotation, when applied
                            at the class level, specifies the kind of requests 
                            that this controller handles*/  

public class OrderController {

@GetMapping("/current")/*@GetMapping paired with the classlevel
                        @RequestMapping, specifies that when an 
                        HTTP GET request is received for /order, 
                        orderForm() will be called to handle the request..*/

public String orderForm(Model model) {

model.addAttribute("order", new Order());

return "orderForm";
}
}

Prior to Spring 4.3, it was @RequestMapping(method=RequestMethod.GET)

Extra reading from a book authored by Craig Walls Extra reading from a book authored by Craig Walls

Python: json.loads returns items prefixing with 'u'

Those 'u' characters being appended to an object signifies that the object is encoded in "unicode".

If you want to remove those 'u' chars from your object you can do this:

import json, ast
jdata = ast.literal_eval(json.dumps(jdata)) # Removing uni-code chars

Let's checkout from python shell

>>> import json, ast
>>> jdata = [{u'i': u'imap.gmail.com', u'p': u'aaaa'}, {u'i': u'333imap.com', u'p': u'bbbb'}]
>>> jdata = ast.literal_eval(json.dumps(jdata))
>>> jdata
[{'i': 'imap.gmail.com', 'p': 'aaaa'}, {'i': '333imap.com', 'p': 'bbbb'}]

Install Android App Bundle on device

Use (on Linux): cd android ./gradlew assemblyRelease|assemblyDebug

An unsigned APK is generated for each case (for debug or testing)

NOTE: On Windows, replace gradle executable for gradlew.bat

How to run an application as "run as administrator" from the command prompt?

It looks like psexec -h is the way to do this:

 -h         If the target system is Windows Vista or higher, has the process
            run with the account's elevated token, if available.

Which... doesn't seem to be listed in the online documentation in Sysinternals - PsExec.

But it works on my machine.

The imported project "C:\Microsoft.CSharp.targets" was not found

In my case I could not load one out of 5 projects in my solution.

It helped to close Visual Studio and I had to delete Microsoft.Net.Compilers.1.3.2 nuget folder under packages folder.

Afterwards, open your solution again and the project loaded as expected

Just to be sure, close all instances of VS before you delete the folder.

Microsoft Excel mangles Diacritics in .csv files?

I've also noticed that the question was "answered" some time ago but I don't understand the stories that say you can't open a utf8-encoded csv file successfully in Excel without using the text wizard.

My reproducible experience: Type Old MacDonald had a farm,ÈÌÉÍØ into Notepad, hit Enter, then Save As (using the UTF-8 option).

Using Python to show what's actually in there:

>>> open('oldmac.csv', 'rb').read()
'\xef\xbb\xbfOld MacDonald had a farm,\xc3\x88\xc3\x8c\xc3\x89\xc3\x8d\xc3\x98\r\n'
>>> ^Z

Good. Notepad has put a BOM at the front.

Now go into Windows Explorer, double click on the file name, or right click and use "Open with ...", and up pops Excel (2003) with display as expected.

How do I properly 'printf' an integer and a string in C?

scanf("%s",str) scans only until it finds a whitespace character. With the input "A 1", it will scan only the first character, hence s2 points at the garbage that happened to be in str, since that array wasn't initialised.

LINQ query to find if items in a list are contained in another list

var test2NotInTest1 = test2.Where(t2 => test1.Count(t1 => t2.Contains(t1))==0);

Faster version as per Tim's suggestion:

var test2NotInTest1 = test2.Where(t2 => !test1.Any(t1 => t2.Contains(t1)));

How to find and restore a deleted file in a Git repository

user@bsd:~/work/git$ rm slides.tex
user@bsd:~/work/git$ git pull 
Already up-to-date.
user@bsd:~/work/git$ ls slides.tex
ls: slides.tex: No such file or directory

Restore the deleted file:

user@bsd:~/work/git$ git checkout
D       .slides.tex.swp
D       slides.tex
user@bsd:~/work/git$ git checkout slides.tex 
user@bsd:~/work/git$ ls slides.tex
slides.tex

Git - How to close commit editor?

Alternatives to Nano (might make your life easier):

On Windows, use notepad. In command prompt type:

git config core.editor notepad

On Ubuntu / Linux, use text editor (gedit). In terminal window type:

git config core.editor gedit

List of zeros in python

$ python3
>>> from itertools import repeat
>>> list(repeat(0, 7))
[0, 0, 0, 0, 0, 0, 0]

How to dynamically insert a <script> tag via jQuery after page load?

This answer is technically similar or equal to what jcoffland answered. I just added a query to detect if a script is already present or not. I need this because I work in an intranet website with a couple of modules, of which some are sharing scripts or bring their own, but these scripts do not need to be loaded everytime again. I am using this snippet since more than a year in production environment, it works like a charme. Commenting to myself: Yes I know, it would be more correct to ask if a function exists... :-)

if (!$('head > script[src="js/jquery.searchable.min.js"]').length) {
    $('head').append($('<script />').attr('src','js/jquery.searchable.min.js'));
}

Get the last item in an array

Here's more Javascript art if you came here looking for it

In the spirit of another answer that used reduceRight(), but shorter:

[3, 2, 1, 5].reduceRight(a => a);

It relies on the fact that, in case you don't provide an initial value, the very last element is selected as the initial one (check the docs here). Since the callback just keeps returning the initial value, the last element will be the one being returned in the end.

Beware that this should be considered Javascript art and is by no means the way I would recommend doing it, mostly because it runs in O(n) time, but also because it hurts readability.

And now for the serious answer

The best way I see (considering you want it more concise than array[array.length - 1]) is this:

const last = a => a[a.length - 1];

Then just use the function:

last([3, 2, 1, 5])

The function is actually useful in case you're dealing with an anonymous array like [3, 2, 1, 5] used above, otherwise you'd have to instantiate it twice, which would be inefficient and ugly:

[3, 2, 1, 5][[3, 2, 1, 5].length - 1]

Ugh.

For instance, here's a situation where you have an anonymous array and you'd have to define a variable, but you can use last() instead:

last("1.2.3".split("."));

Import python package from local directory into interpreter

Inside a package if there is setup.py, then better to install it

pip install -e .

How to watch and reload ts-node when TypeScript files change

Another way could be to compile the code first in watch mode with tsc -w and then use nodemon over javascript. This method is similar in speed to ts-node-dev and has the advantage of being more production-like.

 "scripts": {
    "watch": "tsc -w",
    "dev": "nodemon dist/index.js"
  },

Check if instance is of a type

The different answers here have two different meanings.

If you want to check whether an instance is of an exact type then

if (c.GetType() == typeof(TForm))

is the way to go.

If you want to know whether c is an instance of TForm or a subclass then use is/as:

if (c is TForm)

or

TForm form = c as TForm;
if (form != null)

It's worth being clear in your mind about which of these behaviour you actually want.

How do I copy an entire directory of files into an existing directory using Python?

Here is my version of the same task::

import os, glob, shutil

def make_dir(path):
    if not os.path.isdir(path):
        os.mkdir(path)


def copy_dir(source_item, destination_item):
    if os.path.isdir(source_item):
        make_dir(destination_item)
        sub_items = glob.glob(source_item + '/*')
        for sub_item in sub_items:
            copy_dir(sub_item, destination_item + '/' + sub_item.split('/')[-1])
    else:
        shutil.copy(source_item, destination_item)

Printing column separated by comma using Awk command line

If your only requirement is to print the third field of every line, with each field delimited by a comma, you can use cut:

cut -d, -f3 file
  • -d, sets the delimiter to a comma
  • -f3 specifies that only the third field is to be printed

Redirect on select option in select box

    {{-- dynamic select/dropdown --}}
    <select class="form-control m-bot15" name="district_id" 
        onchange ="location = this.options[this.selectedIndex].value;"
        >
          <option value="">--Select--</option>
          <option value="?">All</option>

            @foreach($location as $district)
                <option  value="?district_id={{ $district->district_id }}" >
                  {{ $district->district }}
                </option> 
            @endforeach   

    </select>

How to remove unused dependencies from composer?

Just run composer install - it will make your vendor directory reflect dependencies in composer.lock file.

In other words - it will delete any vendor which is missing in composer.lock.

Please update the composer itself before running this.

Linux: where are environment variables stored?

If you want to put the environment for system-wide use you can do so with /etc/environment file.

is there a post render callback for Angular JS directive?

You can use the 'link' function, also known as postLink, which runs after the template is put in.

app.directive('myDirective', function() {
  return {
    link: function(scope, elm, attrs) { /*I run after template is put in */ },
    template: '<b>Hello</b>'
  }
});

Give this a read if you plan on making directives, it's a big help: http://docs.angularjs.org/guide/directive

vagrant login as root by default

I know this is an old question, but looking at the original question, it looks like the user just wanted to run a command as root, that's what I need to do when I was searching for an answer and stumbled across the question.

So this one is worth knowing in my opinion:

vagrant ssh servername -c "echo vagrant | sudo -S shutdown 0"

vagrant is the password being echoed into the the sudo command, because as we all know, the vagrant account has sudo privileges and when you sudo, you need to specify the password of the user account, not root..and of course by default, the vagrant user's password is vagrant !

By default you need root privileges to shutdown so I guess doing a shutdown is a good test.

Obviously you don't need to specify a server name if there is only one for that vagrant environment. Also, we're talking about local vagrant virtual machine to the host, so there isn't really any security issue that I can see.

Hope this helps.

How do I get a file name from a full path with PHP?

I've done this using the function PATHINFO which creates an array with the parts of the path for you to use! For example, you can do this:

<?php
    $xmlFile = pathinfo('/usr/admin/config/test.xml');

    function filePathParts($arg1) {
        echo $arg1['dirname'], "\n";
        echo $arg1['basename'], "\n";
        echo $arg1['extension'], "\n";
        echo $arg1['filename'], "\n";
    }

    filePathParts($xmlFile);
?>

This will return:

/usr/admin/config
test.xml
xml
test

The use of this function has been available since PHP 5.2.0!

Then you can manipulate all the parts as you need. For example, to use the full path, you can do this:

$fullPath = $xmlFile['dirname'] . '/' . $xmlFile['basename'];

How to add parameters to an external data query in Excel which can't be displayed graphically?

Easy Workaround (no VBA required)

  1. Right Click Table, expand "Table" context manu, select "External Data Properties"
  2. Click button "Connection Properties" (labelled in tooltip only)
  3. Go-to Tab "Definition"

From here, edit the SQL directly by adding '?' wherever you want a parameter. Works the same way as before except you don't get nagged.

Bootstrap 3.0 Sliding Menu from left

Probably late but here is a plugin that can do the job : http://multi-level-push-menu.make.rs/

Also v2 can use mobile gesture such as swipe ;)

How do I use raw_input in Python 3

Timmerman's solution works great when running the code, but if you don't want to get Undefined name errors when using pyflakes or a similar linter you could use the following instead:

try:
    import __builtin__
    input = getattr(__builtin__, 'raw_input')
except (ImportError, AttributeError):
    pass

Why do we use $rootScope.$broadcast in AngularJS?

What does $rootScope.$broadcast do?

It broadcasts the message to respective listeners all over the angular app, a very powerful means to transfer messages to scopes at different hierarchical level(be it parent , child or siblings)

Similarly, we have $rootScope.$emit, the only difference is the former is also caught by $scope.$on while the latter is caught by only $rootScope.$on .

refer for examples :- http://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/

Redirect from a view to another view

It's because your statement does not produce output.

Besides all the warnings of Darin and lazy (they are right); the question still offerst something to learn.

If you want to execute methods that don't directly produce output, you do:

@{ Response.Redirect("~/Account/LogIn?returnUrl=Products");}

This is also true for rendering partials like:

@{ Html.RenderPartial("_MyPartial"); }

How do I use boolean variables in Perl?

I recommend use boolean;. You have to install the boolean module from cpan though.

Is there a Social Security Number reserved for testing/examples?

To expand on the Wikipedia-based answers:

The Social Security Administration (SSA) explicitly states in this document that the having "000" in the first group of numbers "will NEVER be a valid SSN":

I'd consider that pretty definitive.

However, that the 2nd or 3rd groups of numbers won't be "00" or "0000" can be inferred from a FAQ that the SSA publishes which indicates that allocation of those groups starts at "01" or "0001":

But this is only a FAQ and it's never outright stated that "00" or "0000" will never be used.

In another FAQ they provide (http://www.socialsecurity.gov/employer/randomizationfaqs.html#a0=6) that "00" or "0000" will never be used.

I can't find a reference to the 'advertisement' reserved SSNs on the SSA site, but it appears that no numbers starting with a 3 digit number higher than 772 (according to the document referenced above) have been assigned yet, but there's nothing I could find that states those numbers are reserved. Wikipedia's reference is a book that I don't have access to. The Wikipedia information on the advertisement reserved numbers is mentioned across the web, but many are clearly copied from Wikipedia. I think it would be nice to have a citation from the SSA, though I suspect that now that Wikipedia has made the idea popular that these number would now have to be reserved for advertisements even if they weren't initially.

The SSA has a page with a couple of stories about SSN's they've had to retire because they were used in advertisements/samples (maybe the SSA should post a link to whatever their current policy on this might be):

What exactly is the meaning of an API?

1) What is an API?

API is a contract. A promise to perform described services when asked in specific ways.

2) How is it used?

According to the rules specified in the contract. The whole point of an API is to define how it's used.

3) When and where is it used?

It's used when 2 or more separate systems need to work together to achieve something they can't do alone.

Escape single quote character for use in an SQLite query

In C# you can use the following to replace the single quote with a double quote:

 string sample = "St. Mary's";
 string escapedSample = sample.Replace("'", "''");

And the output will be:

"St. Mary''s"

And, if you are working with Sqlite directly; you can work with object instead of string and catch special things like DBNull:

private static string MySqlEscape(Object usString)
{
    if (usString is DBNull)
    {
        return "";
    }
    string sample = Convert.ToString(usString);
    return sample.Replace("'", "''");
}

How can I link to a specific glibc version?

Link with -static. When you link with -static the linker embeds the library inside the executable, so the executable will be bigger, but it can be executed on a system with an older version of glibc because the program will use it's own library instead of that of the system.

How to use PHP string in mySQL LIKE query?

DO it like

$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$yourPHPVAR%'");

Do not forget the % at the end

UILabel text margin

A lot of these answers are complicated. In some cases, that's necessary. However, if you're reading this, your label has no left/right margin, and you just want a little padding, here's the whole solution:

Step 1: Add spaces at the end (literally, hit the spacebar a few times)

Step 2: Set the text alignment of the label to centered

Done