Programs & Examples On #Orca

The Orca MSI Editor is a table-editing tool that can be used to edit .msi files.

session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium

You can specify the exact version of your Chrome installation like this:

webdriver-manager update --versions.chrome 73.0.3683.75

Maybe you need to do a webdriver-manager clean first in the case of a downgrade.

Error: the entity type requires a primary key

None of the answers worked until I removed the HasNoKey() method from the entity. Dont forget to remove this from your data context or the [Key] attribute will not fix anything.

Angular2 RC5: Can't bind to 'Property X' since it isn't a known property of 'Child Component'

<create-report-card-form [currentReportCardCount]="providerData.reportCards.length" ...
                         ^^^^^^^^^^^^^^^^^^^^^^^^

In your HomeComponent template, you are trying to bind to an input on the CreateReportCardForm component that doesn't exist.

In CreateReportCardForm, these are your only three inputs:

@Input() public reportCardDataSourcesItems: SelectItem[];
@Input() public reportCardYearItems: SelectItem[];
@Input() errorMessages: Message[];

Add one for currentReportCardCount and you should be good to go.

AngularJS POST Fails: Response for preflight has invalid HTTP status code 404

Ok so here's how I figured this out. It all has to do with CORS policy. Before the POST request, Chrome was doing a preflight OPTIONS request, which should be handled and acknowledged by the server prior to the actual request. Now this is really not what I wanted for such a simple server. Hence, resetting the headers client side prevents the preflight:

app.config(function ($httpProvider) {
  $httpProvider.defaults.headers.common = {};
  $httpProvider.defaults.headers.post = {};
  $httpProvider.defaults.headers.put = {};
  $httpProvider.defaults.headers.patch = {};
});

The browser will now send a POST directly. Hope this helps a lot of folks out there... My real problem was not understanding CORS enough.

Link to a great explanation: http://www.html5rocks.com/en/tutorials/cors/

Kudos to this answer for showing me the way.

How to get response as String using retrofit without using GSON or any other library in android

** Update ** A scalars converter has been added to retrofit that allows for a String response with less ceremony than my original answer below.

Example interface --

public interface GitHubService {
    @GET("/users/{user}")
    Call<String> listRepos(@Path("user") String user);
}

Add the ScalarsConverterFactory to your retrofit builder. Note: If using ScalarsConverterFactory and another factory, add the scalars factory first.

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(ScalarsConverterFactory.create())
    // add other factories here, if needed.
    .build();

You will also need to include the scalars converter in your gradle file --

implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'

--- Original Answer (still works, just more code) ---

I agree with @CommonsWare that it seems a bit odd that you want to intercept the request to process the JSON yourself. Most of the time the POJO has all the data you need, so no need to mess around in JSONObject land. I suspect your specific problem might be better solved using a custom gson TypeAdapter or a retrofit Converter if you need to manipulate the JSON. However, retrofit provides more the just JSON parsing via Gson. It also manages a lot of the other tedious tasks involved in REST requests. Just because you don't want to use one of the features, doesn't mean you have to throw the whole thing out. There are times you just want to get the raw stream, so here is how to do it -

First, if you are using Retrofit 2, you should start using the Call API. Instead of sending an object to convert as the type parameter, use ResponseBody from okhttp --

public interface GitHubService {
    @GET("/users/{user}")
    Call<ResponseBody> listRepos(@Path("user") String user);
}

then you can create and execute your call --

GitHubService service = retrofit.create(GitHubService.class);
Call<ResponseBody> result = service.listRepos(username);
result.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Response<ResponseBody> response) {
        try {
            System.out.println(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFailure(Throwable t) {
        e.printStackTrace();
    }
});

Note The code above calls string() on the response object, which reads the entire response into a String. If you are passing the body off to something that can ingest streams, you can call charStream() instead. See the ResponseBody docs.

bootstrap 3 wrap text content within div for horizontal alignment

Add the following style to your h3 elements:

word-wrap: break-word;

This will cause the long URLs in them to wrap. The default setting for word-wrap is normal, which will wrap only at a limited set of split tokens (e.g. whitespaces, hyphens), which are not present in a URL.

How to uninstall with msiexec using product id guid without .msi file present

The good thing is, this one is really easily and deterministically to analyze: Either, the msi package is really not installed on the system or you're doing something wrong. Of course the correct call is:

msiexec /x {A4BFF20C-A21E-4720-88E5-79D5A5AEB2E8}

(Admin rights needed of course- With curly braces without any quotes here- quotes are only needed, if paths or values with blank are specified in the commandline.)
If the message is: "This action is only valid for products that are currently installed", then this is true. Either the package with this ProductCode is not installed or there is a typo.

To verify where the fault is:

  1. First try to right click on the (probably) installed .msi file itself. You will see (besides "Install" and "Repair") an Uninstall entry. Click on that.
    a) If that uninstall works, your msi has another ProductCode than you expect (maybe you have the wrong WiX source or your build has dynamic logging where the ProductCode changes).
    b) If that uninstall gives the same "...only valid for products already installed" the package is not installed (which is obviously a precondition to be able to uninstall it).

  2. If 1.a) was the case, you can look for the correct ProductCode of your package, if you open your msi file with Orca, Insted or another editor/tool. Just google for them. Look there in the table with the name "Property" and search for the string "ProductCode" in the first column. In the second column there is the correct value.

There are no other possibilities.

Just a suggestion for the used commandline: I would add at least the "/qb" for a simple progress bar or "/qn" parameter (the latter for complete silent uninstall, but makes only sense if you are sure it works).

How do I debug error ECONNRESET in Node.js?

I just figured this out, at least in my use case.

I was getting ECONNRESET. It turned out that the way my client was set up, it was hitting the server with an API call a ton of times really quickly -- and it only needed to hit the endpoint once.

When I fixed that, the error was gone.

java.rmi.ConnectException: Connection refused to host: 127.0.1.1;

PROBLEM SOLVED

I had exactly the same error. When the remote object got binded to the rmiregistry it was attached with the loopback IP Address which will obviously fail if you try to invoke a method from a remote address. In order to fix this we need to set the java.rmi.server.hostname property to the IP address where other devices can reach your rmiregistry over the network. It doesn't work when you try to set the parameter through the JVM. It worked for me just by adding the following line to my code just before binding the object to the rmiregistry:

System.setProperty("java.rmi.server.hostname","192.168.1.2");

In this case the IP address on the local network of the PC binding the remote object on the RMI Registry is 192.168.1.2.

Adding a custom header to HTTP request using angular.js

my suggestion will be add a function call settings like this inside the function check the header which is appropriate for it. I am sure it will definitely work. it is perfectly working for me.

function getSettings(requestData) {
    return {
        url: requestData.url,
        dataType: requestData.dataType || "json",
        data: requestData.data || {},
        headers: requestData.headers || {
            "accept": "application/json; charset=utf-8",
            'Authorization': 'Bearer ' + requestData.token
        },
        async: requestData.async || "false",
        cache: requestData.cache || "false",
        success: requestData.success || {},
        error: requestData.error || {},
        complete: requestData.complete || {},
        fail: requestData.fail || {}
    };
}

then call your data like this

    var requestData = {
        url: 'API end point',
        data: Your Request Data,
        token: Your Token
    };

    var settings = getSettings(requestData);
    settings.method = "POST"; //("Your request type")
    return $http(settings);

How to pass data in the ajax DELETE request other than headers

deleteRequest: function (url, Id, bolDeleteReq, callback, errorCallback) {
    $.ajax({
        url: urlCall,
        type: 'DELETE',
        data: {"Id": Id, "bolDeleteReq" : bolDeleteReq},
        success: callback || $.noop,
        error: errorCallback || $.noop
    });
}

Note: the use of headers was introduced in JQuery 1.5.:

A map of additional header key/value pairs to send along with the request. This setting is set before the beforeSend function is called; therefore, any values in the headers setting can be overwritten from within the beforeSend function.

Numpy `ValueError: operands could not be broadcast together with shape ...`

If X and beta do not have the same shape as the second term in the rhs of your last line (i.e. nsample), then you will get this type of error. To add an array to a tuple of arrays, they all must be the same shape.

I would recommend looking at the numpy broadcasting rules.

How to add dll in c# project

In the right hand column under your solution explorer, you can see next to the reference to "Science" its marked as a warning. Either that means it cant find it, or its objecting to it for some other reason. While this is the case and your code requires it (and its not just in the references list) it wont compile.

Please post the warning message, we can try help you further.

How to name variables on the fly?

Don't make data frames. Keep the list, name its elements but do not attach it.

The biggest reason for this is that if you make variables on the go, almost always you will later on have to iterate through each one of them to perform something useful. There you will again be forced to iterate through each one of the names that you have created on the fly.

It is far easier to name the elements of the list and iterate through the names.

As far as attach is concerned, its really bad programming practice in R and can lead to a lot of trouble if you are not careful.

Date validation with ASP.NET validator

I believe that the dates have to be specified in the current culture of the application. You might want to experiment with setting CultureInvariantValues to true and see if that solves your problem. Otherwise you may need to change the DateTimeFormat for the current culture (or the culture itself) to get what you want.

Content-Disposition:What are the differences between "inline" and "attachment"?

It might also be worth mentioning that inline will try to open Office Documents (xls, doc etc) directly from the server, which might lead to a User Credentials Prompt.

see this link:

http://forums.asp.net/t/1885657.aspx/1?Access+the+SSRS+Report+in+excel+format+on+server

somebody tried to deliver an Excel Report from SSRS via ASP.Net -> the user always got prompted to enter the credentials. After clicking cancel on the prompt it would be opened anyway...

If the Content Disposition is marked as Attachment it will automatically be saved to the temp folder after clicking open and then opened in Excel from the local copy.

AddTransient, AddScoped and AddSingleton Services Differences

AddSingleton()

AddSingleton() creates a single instance of the service when it is first requested and reuses that same instance in all the places where that service is needed.

AddScoped()

In a scoped service, with every HTTP request, we get a new instance. However, within the same HTTP request, if the service is required in multiple places, like in the view and in the controller, then the same instance is provided for the entire scope of that HTTP request. But every new HTTP request will get a new instance of the service.

AddTransient()

With a transient service, a new instance is provided every time a service instance is requested whether it is in the scope of the same HTTP request or across different HTTP requests.

Excel - programm cells to change colour based on another cell

Select ColumnB and as two CF formula rules apply:

Green: =AND(B1048576="X",B1="Y")

Red: =AND(B1048576="X",B1="W")

enter image description here

Securing a password in a properties file

Actually, this is a duplicate of Encrypt Password in Configuration Files?.

The best solution I found so far is in this answert: https://stackoverflow.com/a/1133815/1549977

Pros: Password is saved a a char array, not as a string. It's still not good, but better than anything else.

$http.get(...).success is not a function

The .success syntax was correct up to Angular v1.4.3.

For versions up to Angular v.1.6, you have to use then method. The then() method takes two arguments: a success and an error callback which will be called with a response object.

Using the then() method, attach a callback function to the returned promise.

Something like this:

app.controller('MainCtrl', function ($scope, $http){
   $http({
      method: 'GET',
      url: 'api/url-api'
   }).then(function (response){

   },function (error){

   });
}

See reference here.

Shortcut methods are also available.

$http.get('api/url-api').then(successCallback, errorCallback);

function successCallback(response){
    //success code
}
function errorCallback(error){
    //error code
}

The data you get from the response is expected to be in JSON format. JSON is a great way of transporting data, and it is easy to use within AngularJS

The major difference between the 2 is that .then() call returns a promise (resolved with a value returned from a callback) while .success() is more traditional way of registering callbacks and doesn't return a promise.

What does bundle exec rake mean?

You're running bundle exec on a program. The program's creators wrote it when certain versions of gems were available. The program Gemfile specifies the versions of the gems the creators decided to use. That is, the script was made to run correctly against these gem versions.

Your system-wide Gemfile may differ from this Gemfile. You may have newer or older gems with which this script doesn't play nice. This difference in versions can give you weird errors.

bundle exec helps you avoid these errors. It executes the script using the gems specified in the script's Gemfile rather than the systemwide Gemfile. It executes the certain gem versions with the magic of shell aliases.

See more on the man page.

Here's an example Gemfile:

source 'http://rubygems.org'

gem 'rails', '2.8.3'

Here, bundle exec would execute the script using rails version 2.8.3 and not some other version you may have installed system-wide.

How do I clone into a non-empty directory?

I had a similar problem with a new Apache web directory (account created with WHM) that I planned to use as a staging web server. I needed to initially clone my new project with the code base there and periodically deploy changes by pulling from repository.

The problem was that the account already contained web server files like:

.bash_history
.bash_logout
.bash_profile
.bashrc
.contactemail
.cpanel/
...

...that I did not want to either delete or commit to my repository. I needed them to just stay there unstaged and untracked.

What I did:

I went to my web folder (existing_folder):

cd /home/existing_folder

and then:

git init
git remote add origin PATH/TO/REPO
git pull origin master
git status

It displayed (as expected) a list of many not staged files - those that already existed initially from my cPanel web account.

Then, thanks to this article, I just added the list of those files to:

**.git/info/exclude**

This file, almost like the .gitignore file, allows you to ignore files from being staged. After this I had nothing to commit in the .git/ directory - it works like a personal .gitignore that no one else can see.

Now checking git status returns:

On branch master
nothing to commit, working tree clean

Now I can deploy changes to this web server by simply pulling from my git repository. Hope this helps some web developers to easily create a staging server.

Detect whether there is an Internet connection available on Android

The getActiveNetworkInfo() method of ConnectivityManager returns a NetworkInfo instance representing the first connected network interface it can find or null if none if the interfaces are connected. Checking if this method returns null should be enough to tell if an internet connection is available.

private boolean isNetworkAvailable() {
     ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
     NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
     return activeNetworkInfo != null; 
}

You will also need:

in your android manifest.

Edit:

Note that having an active network interface doesn't guarantee that a particular networked service is available. Networks issues, server downtime, low signal, captive portals, content filters and the like can all prevent your app from reaching a server. For instance you can't tell for sure if your app can reach Twitter until you receive a valid response from the Twitter service.

getActiveNetworkInfo() shouldn't never give null. I don't know what they were thinking when they came up with that. It should give you an object always.

Share link on Google+

No, you cannot. Google Plus has been discontinued. Clicking any link for any answer here brings me to this text:

Google+ is no longer available for consumer (personal) and brand accounts

From all of us on the Google+ team,

thank you for making Google+ such a special place.

There is one section that reads that the product is continued for "G Suite," but as of Feb., 2020, the chat and social service listed for G Suite is Hangouts, not Google+.

The format https://plus.google.com/share?url=YOUR_URL_HERE was documented at https://developers.google.com/+/web/share/, but this documentation has since been removed, probably because no part of Google+ continues in development. If you are feeling nostalgic, you can see what the API used to say with an Archive.org link.

Ant: How to execute a command for each file in directory?

Here is way to do this using javascript and the ant scriptdef task, you don't need ant-contrib for this code to work since scriptdef is a core ant task.

<scriptdef name="bzip2-files" language="javascript">
<element name="fileset" type="fileset"/>
<![CDATA[
  importClass(java.io.File);
  filesets = elements.get("fileset");

  for (i = 0; i < filesets.size(); ++i) {
    fileset = filesets.get(i);
    scanner = fileset.getDirectoryScanner(project);
    scanner.scan();
    files = scanner.getIncludedFiles();
    for( j=0; j < files.length; j++) {

        var basedir  = fileset.getDir(project);
        var filename = files[j];
        var src = new File(basedir, filename);
        var dest= new File(basedir, filename + ".bz2");

        bzip2 = self.project.createTask("bzip2");        
        bzip2.setSrc( src);
        bzip2.setDestfile(dest ); 
        bzip2.execute();
    }
  }
]]>
</scriptdef>

<bzip2-files>
    <fileset id="test" dir="upstream/classpath/jars/development">
            <include name="**/*.jar" />
    </fileset>
</bzip2-files>

Working with select using AngularJS's ng-options

The question is already answered (BTW, really good and comprehensive answer provided by Ben), but I would like to add another element for completeness, which may be also very handy.

In the example suggested by Ben:

<select ng-model="blah" ng-options="item.ID as item.Title for item in items"></select>

the following ngOptions form has been used: select as label for value in array.

Label is an expression, which result will be the label for <option> element. In that case you can perform certain string concatenations, in order to have more complex option labels.

Examples:

  • ng-options="item.ID as item.Title + ' - ' + item.ID for item in items" gives you labels like Title - ID
  • ng-options="item.ID as item.Title + ' (' + item.Title.length + ')' for item in items" gives you labels like Title (X), where X is length of Title string.

You can also use filters, for example,

  • ng-options="item.ID as item.Title + ' (' + (item.Title | uppercase) + ')' for item in items" gives you labels like Title (TITLE), where Title value of Title property and TITLE is the same value but converted to uppercase characters.
  • ng-options="item.ID as item.Title + ' (' + (item.SomeDate | date) + ')' for item in items" gives you labels like Title (27 Sep 2015), if your model has a property SomeDate

Cannot get to $rootScope

You can not ask for instance during configuration phase - you can ask only for providers.

var app = angular.module('modx', []);

// configure stuff
app.config(function($routeProvider, $locationProvider) {
  // you can inject any provider here
});

// run blocks
app.run(function($rootScope) {
  // you can inject any instance here
});

See http://docs.angularjs.org/guide/module for more info.

What is the final version of the ADT Bundle?

You can also get an updated version of the Eclipse's ADT plugin (based on an unreleased 24.2.0 version) that I managed to patch and compile at https://github.com/khaledev/ADT.

How to make circular background using css?

If you want to do it with only 1 element, you can use the ::before and ::after pseudo elements for the same div instead of a wrapper.
See http://css-tricks.com/pseudo-element-roundup/

disable horizontal scroll on mobile web

Try this code,overflow will help to remove scrollbar.You can use it also for any div which is scrolling.

html, body {
   overflow-x: hidden;
 }
body {
   width:100%;
 }

GitHub - failed to connect to github 443 windows/ Failed to connect to gitHub - No Error

Before you try the fancy stuff, try disabling the firewall and antivirus and see if it works. That was my problem.

python pip: force install ignoring dependencies

When I were trying install librosa package with pip (pip install librosa), this error were appeared:

ERROR: Cannot uninstall 'llvmlite'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall.

I tried to remove llvmlite, but pip uninstall could not remove it. So, I used capability of ignore of pip by this code:

pip install librosa --ignore-installed llvmlite

Indeed, you can use this rule for ignoring a package you don't want to consider:

pip install {package you want to install} --ignore-installed {installed package you don't want to consider}

Accessing UI (Main) Thread safely in WPF

The best way to go about it would be to get a SynchronizationContext from the UI thread and use it. This class abstracts marshalling calls to other threads, and makes testing easier (in contrast to using WPF's Dispatcher directly). For example:

class MyViewModel
{
    private readonly SynchronizationContext _syncContext;

    public MyViewModel()
    {
        // we assume this ctor is called from the UI thread!
        _syncContext = SynchronizationContext.Current;
    }

    // ...

    private void watcher_Changed(object sender, FileSystemEventArgs e)
    {
         _syncContext.Post(o => DGAddRow(crp.Protocol, ft), null);
    }
}

Exception: Serialization of 'Closure' is not allowed

As already stated: closures, out of the box, cannot be serialized.

However, using the __sleep(), __wakeup() magic methods and reflection u CAN manually make closures serializable. For more details see extending-php-5-3-closures-with-serialization-and-reflection

This makes use of reflection and the php function eval. Do note this opens up the possibility of CODE injection, so please take notice of WHAT you are serializing.

Java Generics With a Class & an Interface - Together

You can't do it with "anonymous" type parameters (ie, wildcards that use ?), but you can do it with "named" type parameters. Simply declare the type parameter at method or class level.

import java.util.List;
interface A{}
interface B{}
public class Test<E extends B & A, T extends List<E>> {
    T t;
}

UIDevice uniqueIdentifier deprecated - What to do now?

If someone stumble upon to this question, when searching for an alternative. I have followed this approach in IDManager class, This is a collection from different solutions. KeyChainUtil is a wrapper to read from keychain. You can also use the hashed MAC address as a kind of unique ID.

/*  Apple confirmed this bug in their system in response to a Technical Support Incident 
    request. They said that identifierForVendor and advertisingIdentifier sometimes 
    returning all zeros can be seen both in development builds and apps downloaded over the 
    air from the App Store. They have no work around and can't say when the problem will be fixed. */
#define kBuggyASIID             @"00000000-0000-0000-0000-000000000000"

+ (NSString *) getUniqueID {
    if (NSClassFromString(@"ASIdentifierManager")) {
        NSString * asiID = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
        if ([asiID compare:kBuggyASIID] == NSOrderedSame) {
            NSLog(@"Error: This device return buggy advertisingIdentifier.");
            return [IDManager getUniqueUUID];
        } else {
            return asiID;
        }

    } else {
        return [IDManager getUniqueUUID];
    }
}


+ (NSString *) getUniqueUUID {
    NSError * error;
    NSString * uuid = [KeychainUtils getPasswordForUsername:kBuyassUser andServiceName:kIdOgBetilngService error:&error];
    if (error) {
        NSLog(@"Error geting unique UUID for this device! %@", [error localizedDescription]);
        return nil;
    }
    if (!uuid) {
        DLog(@"No UUID found. Creating a new one.");
        uuid = [IDManager GetUUID];
        uuid = [Util md5String:uuid];
        [KeychainUtils storeUsername:USER_NAME andPassword:uuid forServiceName:SERVICE_NAME updateExisting:YES error:&error];
        if (error) {
            NSLog(@"Error getting unique UUID for this device! %@", [error localizedDescription]);
            return nil;
        }
    }
    return uuid;
}

/* NSUUID is after iOS 6. */
+ (NSString *)GetUUID
{
    CFUUIDRef theUUID = CFUUIDCreate(NULL);
    CFStringRef string = CFUUIDCreateString(NULL, theUUID);
    CFRelease(theUUID);
    return [(NSString *)string autorelease];
}

#pragma mark - MAC address
// Return the local MAC addy
// Courtesy of FreeBSD hackers email list
// Last fallback for unique identifier
+ (NSString *) getMACAddress
{
    int                 mib[6];
    size_t              len;
    char                *buf;
    unsigned char       *ptr;
    struct if_msghdr    *ifm;
    struct sockaddr_dl  *sdl;

    mib[0] = CTL_NET;
    mib[1] = AF_ROUTE;
    mib[2] = 0;
    mib[3] = AF_LINK;
    mib[4] = NET_RT_IFLIST;

    if ((mib[5] = if_nametoindex("en0")) == 0) {
        printf("Error: if_nametoindex error\n");
        return NULL;
    }

    if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
        printf("Error: sysctl, take 1\n");
        return NULL;
    }

    if ((buf = malloc(len)) == NULL) {
        printf("Error: Memory allocation error\n");
        return NULL;
    }

    if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
        printf("Error: sysctl, take 2\n");
        free(buf); // Thanks, Remy "Psy" Demerest
        return NULL;
    }

    ifm = (struct if_msghdr *)buf;
    sdl = (struct sockaddr_dl *)(ifm + 1);
    ptr = (unsigned char *)LLADDR(sdl);
    NSString *outstring = [NSString stringWithFormat:@"%02X:%02X:%02X:%02X:%02X:%02X", *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];

    free(buf);
    return outstring;
}

+ (NSString *) getHashedMACAddress
{
    NSString * mac = [IDManager getMACAddress];
    return [Util md5String:mac];
}

+ (NSString *)md5String:(NSString *)plainText
{
    if(plainText == nil || [plainText length] == 0)
        return nil;

    const char *value = [plainText UTF8String];
    unsigned char outputBuffer[CC_MD5_DIGEST_LENGTH];
    CC_MD5(value, strlen(value), outputBuffer);

    NSMutableString *outputString = [[NSMutableString alloc] initWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for(NSInteger count = 0; count < CC_MD5_DIGEST_LENGTH; count++){
        [outputString appendFormat:@"%02x",outputBuffer[count]];
    }
    NSString * retString = [NSString stringWithString:outputString];
    [outputString release];
    return retString;
}

How do I get the total number of unique pairs of a set in the database?

What you're looking for is n choose k. Basically:

enter image description here

For every pair of 100 items, you'd have 4,950 combinations - provided order doesn't matter (AB and BA are considered a single combination) and you don't want to repeat (AA is not a valid pair).

Missing Microsoft RDLC Report Designer in Visual Studio

I've had the same problem as you and I installed Microsoft rdlc designer to solve my problem.

And if you already installed this but still can't found rdlc designer try open visual studio > tools > Extension and Updates > then enable Miscrosoft Rdlc designer extensions.

Remove leading comma from a string

Assuming the string is called myStr:

// Strip start and end quotation mark and possible initial comma
myStr=myStr.replace(/^,?'/,'').replace(/'$/,'');

// Split stripping quotations
myArray=myStr.split("','");

Note that if a string can be missing in the list without even having its quotation marks present and you want an empty spot in the corresponding location in the array, you'll need to write the splitting manually for a robust solution.

How do I count a JavaScript object's attributes?

 var miobj = [
  {"padreid":"0", "sw":"0", "dtip":"UNO", "datos":[]},
  {"padreid":"1", "sw":"0", "dtip":"DOS", "datos":[]}
 ];
 alert(miobj.length) //=== 2

but

 alert(miobj[0].length) //=== undefined

this function is very good

Object.prototype.count = function () {
    var count = 0;
    for(var prop in this) {
        if(this.hasOwnProperty(prop))
            count = count + 1;
    }
    return count;
}

alert(miobj.count()) // === 2
alert(miobj[0].count()) // === 4

How do I turn off the mysql password validation?

Here is what I do to remove the validate password plugin:

  1. Login to the mysql server as root mysql -h localhost -u root -p
  2. Run the following sql command: uninstall plugin validate_password;
  3. If last line doesn't work (new mysql release), you should execute UNINSTALL COMPONENT 'file://component_validate_password';

I would not recommend this solution for a production system. I used this solution on a local mysql instance for development purposes only.

Loop through all the rows of a temp table and call a stored procedure for each row

Try returning the dataset from your stored procedure to your datatable in C# or VB.Net. Then the large amount of data in your datatable can be copied to your destination table using a Bulk Copy. I have used BulkCopy for loading large datatables with thousands of rows, into Sql tables with great success in terms of performance.

You may want to experiment with BulkCopy in your C# or VB.Net code.

Xcode process launch failed: Security

Updated answer for Xcode 7: Tapping the app no longer works (as of beta 1 it just displays an "untrusted enterprise developer" message with only a Dismiss button).

To fix, open the Settings app, go to General / Profiles, and you'll see your profile. Mark it trusted and things should start working normally again.

Updated For iOS 9.2.1 and Xcode 7.2.1:

Goto: Settings > General > Device Management > Select App from Developer Apps > Trust App.

Parse strings to double with comma and point

You can check if the string contains a decimal point using

string s="";

        if (s.Contains(','))
        { 
        //treat as double how you wish
        }

and then treat that as a decimal, otherwise just pass the non-double value along.

matplotlib set yaxis label size

If you are using the 'pylab' for interactive plotting you can set the labelsize at creation time with pylab.ylabel('Example', fontsize=40).

If you use pyplot programmatically you can either set the fontsize on creation with ax.set_ylabel('Example', fontsize=40) or afterwards with ax.yaxis.label.set_size(40).

Why do I get access denied to data folder when using adb?

When you are in the shell directory for the device. Just run

su - root

Then you should be able to access the data/ folder.

Set background image in CSS using jquery

<div class="rmz-srchbg">
  <input type="text" id="globalsearchstr" name="search" value="" class="rmz-txtbox">
  <input type="submit" value="&nbsp;" id="srchbtn" class="rmz-srchico">
  <br style="clear:both;">
</div>
$(document).ready(function() {
  $('#globalsearchstr').bind('mouseenter', function() {
    $(this).parent().css("background", "black");
  });
});

Entity Framework 6 Code first Default value

You can do it by manually edit code first migration:

public override void Up()
{    
   AddColumn("dbo.Events", "Active", c => c.Boolean(nullable: false, defaultValue: true));
} 

How to deserialize xml to object

Your classes should look like this

[XmlRoot("StepList")]
public class StepList
{
    [XmlElement("Step")]
    public List<Step> Steps { get; set; }
}

public class Step
{
    [XmlElement("Name")]
    public string Name { get; set; }
    [XmlElement("Desc")]
    public string Desc { get; set; }
}

Here is my testcode.

string testData = @"<StepList>
                        <Step>
                            <Name>Name1</Name>
                            <Desc>Desc1</Desc>
                        </Step>
                        <Step>
                            <Name>Name2</Name>
                            <Desc>Desc2</Desc>
                        </Step>
                    </StepList>";

XmlSerializer serializer = new XmlSerializer(typeof(StepList));
using (TextReader reader = new StringReader(testData))
{
    StepList result = (StepList) serializer.Deserialize(reader);
}

If you want to read a text file you should load the file into a FileStream and deserialize this.

using (FileStream fileStream = new FileStream("<PathToYourFile>", FileMode.Open)) 
{
    StepList result = (StepList) serializer.Deserialize(fileStream);
}

Call a React component method from outside

method 1 using ChildRef:

public childRef: any = React.createRef<Hello>();

public onButtonClick= () => {
    console.log(this.childRef.current); // this will have your child reference
}

<Hello ref = { this.childRef }/>
<button onclick="onButtonClick()">Click me!</button>

Method 2: using window register

public onButtonClick= () => {
    console.log(window.yourRef); // this will have your child reference
}

<Hello ref = { (ref) => {window.yourRef = ref} }/>`
<button onclick="onButtonClick()">Click me!</button>

Save Javascript objects in sessionStorage

The solution is to stringify the object before calling setItem on the sessionStorage.

var user = {'name':'John'};
sessionStorage.setItem('user', JSON.stringify(user));
var obj = JSON.parse(sessionStorage.user);

How to run a Command Prompt command with Visual Basic code?

Or, you could do it the really simple way.

Dim OpenCMD 
OpenCMD = CreateObject("wscript.shell")
OpenCMD.run("Command Goes Here")

How can I read a whole file into a string variable

I think the best thing to do, if you're really concerned about the efficiency of concatenating all of these files, is to copy them all into the same bytes buffer.

buf := bytes.NewBuffer(nil)
for _, filename := range filenames {
  f, _ := os.Open(filename) // Error handling elided for brevity.
  io.Copy(buf, f)           // Error handling elided for brevity.
  f.Close()
}
s := string(buf.Bytes())

This opens each file, copies its contents into buf, then closes the file. Depending on your situation you may not actually need to convert it, the last line is just to show that buf.Bytes() has the data you're looking for.

Check play state of AVPlayer

You can tell it's playing using:

AVPlayer *player = ...
if ((player.rate != 0) && (player.error == nil)) {
    // player is playing
}

Swift 3 extension:

extension AVPlayer {
    var isPlaying: Bool {
        return rate != 0 && error == nil
    }
}

How to convert numpy arrays to standard TensorFlow format?

You can use tf.pack (tf.stack in TensorFlow 1.0.0) method for this purpose. Here is how to pack a random image of type numpy.ndarray into a Tensor:

import numpy as np
import tensorflow as tf
random_image = np.random.randint(0,256, (300,400,3))
random_image_tensor = tf.pack(random_image)
tf.InteractiveSession()
evaluated_tensor = random_image_tensor.eval()

UPDATE: to convert a Python object to a Tensor you can use tf.convert_to_tensor function.

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

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

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

You can think of @synchronized as a compiler rewrite:

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

is transformed into:

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

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

public static const in TypeScript

If you did want something that behaved more like a static constant value in modern browsers (in that it can't be changed by other code), you could add a get only accessor to the Library class (this will only work for ES5+ browsers and NodeJS):

export class Library {
    public static get BOOK_SHELF_NONE():string { return "None"; }
    public static get BOOK_SHELF_FULL():string { return "Full"; }   
}

var x = Library.BOOK_SHELF_NONE;
console.log(x);
Library.BOOK_SHELF_NONE = "Not Full";
x = Library.BOOK_SHELF_NONE;
console.log(x);

If you run it, you'll see how the attempt to set the BOOK_SHELF_NONE property to a new value doesn't work.

2.0

In TypeScript 2.0, you can use readonly to achieve very similar results:

export class Library {
    public static readonly BOOK_SHELF_NONE = "None";
    public static readonly BOOK_SHELF_FULL = "Full";
}

The syntax is a bit simpler and more obvious. However, the compiler prevents changes rather than the run time (unlike in the first example, where the change would not be allowed at all as demonstrated).

Have bash script answer interactive prompts

A simple

echo "Y Y N N Y N Y Y N" | ./your_script

This allow you to pass any sequence of "Y" or "N" to your script.

IIS 500.19 with 0x80070005 The requested page cannot be accessed because the related configuration data for the page is invalid error

In my case, configSections must be at top in configuration

<configuration>
<configSections>
...
</configSections>
<othersetting>
</othersetting>
.....

How to support placeholder attribute in IE8 and 9

    <script>
        if ($.browser.msie) {
            $('input[placeholder]').each(function() {

                var input = $(this);

                $(input).val(input.attr('placeholder'));

                $(input).focus(function() {
                    if (input.val() == input.attr('placeholder')) {
                        input.val('');
                    }
                });

                $(input).blur(function() {
                    if (input.val() == '' || input.val() == input.attr('placeholder')) {
                        input.val(input.attr('placeholder'));
                    }
                });
            });
        }
        ;
    </script>

Cannot implicitly convert type from Task<>

You need to make TestGetMethod async too and attach await in front of GetIdList(); will unwrap the task to List<int>, So if your helper function is returning Task make sure you have await as you are calling the function async too.

public Task<List<int>> TestGetMethod()
{
    return GetIdList();
}    

async Task<List<int>> GetIdList()
{
    using (HttpClient proxy = new HttpClient())
    {
        string response = await proxy.GetStringAsync("www.test.com");
        List<int> idList = JsonConvert.DeserializeObject<List<int>>();
        return idList;
    }
}

Another option

public async void TestGetMethod(List<int> results)
{
    results = await GetIdList(); // await will unwrap the List<int>
}

AttributeError: 'str' object has no attribute 'strftime'

you should change cr_date(str) to datetime object then you 'll change the date to the specific format:

cr_date = '2013-10-31 18:23:29.000227'
cr_date = datetime.datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f')
cr_date = cr_date.strftime("%m/%d/%Y")

Pandas get topmost n records within each group

Sometimes sorting the whole data ahead is very time consuming. We can groupby first and doing topk for each group:

g = df.groupby(['id']).apply(lambda x: x.nlargest(topk,['value'])).reset_index(drop=True)

iPhone keyboard, Done button and resignFirstResponder

I made a small test project with just a UITextField and this code

#import <UIKit/UIKit.h>
@interface TextFieldTestViewController : UIViewController
<UITextFieldDelegate>
{
    UITextField *textField;
}
@property (nonatomic, retain) IBOutlet UITextField *textField;
@end

#import "TextFieldTestViewController.h"
@implementation TextFieldTestViewController
@synthesize textField;

- (void)viewDidLoad
{
    [self.textField setDelegate:self];
    [self.textField setReturnKeyType:UIReturnKeyDone];
    [self.textField addTarget:self
                  action:@selector(textFieldFinished:)
        forControlEvents:UIControlEventEditingDidEndOnExit];
    [super viewDidLoad];
}
- (IBAction)textFieldFinished:(id)sender
{
    // [sender resignFirstResponder];
}

- (void)dealloc {
    [super dealloc];
}
@end

The text field is an unmodified UITextField dragged onto the NIB, with the outlet connected.
After loading the app, clicking in the text field brings up the keyboard. Pressing the "Done" button makes the text field lose focus and animates out the keyboard. Note that the advice around the web is to always use [sender resignFirstResponder] but this works without it.

Email & Phone Validation in Swift

You can create separate class for validation as below:

enum AIValidationRule: Int {
case
EmptyCheck,
MinMaxLength,
FixedLength,
EmailCheck,
UpperCase,
LowerCase,
SpecialCharacter,
DigitCheck,
WhiteSpaces,
None

}

let ValidationManager = AIValidationManager.sharedManager


func validateTextField(txtField:AITextField, forRule rule:AIValidationRule, withMinimumChar minChar:Int, andMaximumChar maxChar:Int) -> (isValid:Bool, errMessage:String, txtFieldWhichFailedValidation:AITextField)? {

    switch rule {

    case .EmptyCheck:
        return (txtField.text?.characters.count == 0) ? (false,"Please enter \(txtField.placeholder!.lowercased())",txtField) : nil


    case .MinMaxLength:
        return (txtField.text!.characters.count < minChar || txtField.text!.characters.count > maxChar) ? (false,"\(txtField.placeholder!) should be of \(minChar) to \(maxChar) characters",txtField) : nil

    case .FixedLength:
        return (txtField.text!.characters.count != minChar) ? (false,"\(txtField.placeholder!) should be of \(minChar) characters",txtField) : nil


    case .EmailCheck:
        return (!(txtField.text?.isValidEmail())!) ? (false,"Please enter valid email",txtField) : nil


    case .UpperCase:
        return ((txtField.text! as NSString).rangeOfCharacter(from: NSCharacterSet.uppercaseLetters).location == NSNotFound) ? (false,"\(txtField.placeholder!) should contain atleast one uppercase letter",txtField) : nil


    case .LowerCase:
        return ((txtField.text! as NSString).rangeOfCharacter(from: NSCharacterSet.lowercaseLetters).location == NSNotFound) ? (false,"\(txtField.placeholder!) should contain atleast one lowercase letter",txtField) : nil


    case .SpecialCharacter:
        let symbolCharacterSet = NSMutableCharacterSet.symbol()
        symbolCharacterSet.formUnion(with: NSCharacterSet.punctuationCharacters)
        return ((txtField.text! as NSString).rangeOfCharacter(from: symbolCharacterSet as CharacterSet).location == NSNotFound) ? (false,"\(txtField.placeholder!) should contain atleast one special letter",txtField) : nil


    case .DigitCheck:
        return ((txtField.text! as NSString).rangeOfCharacter(from: NSCharacterSet(charactersIn: "0123456789") as CharacterSet).location == NSNotFound) ? (false,"\(txtField.placeholder!) should contain atleast one digit letter",txtField) : nil

    case .WhiteSpaces:
        return (txtField.text!.containsAdjacentSpaces() || txtField.text!.isLastCharcterAWhiteSpace()) ? (false,"\(txtField.placeholder!) seems to be invalid",txtField) : nil

    case .None:
        return nil
    }
}

    func validateTextField(txtField:AITextField, forRules rules:[AIValidationRule]) -> (isValid:Bool, errMessage:String, txtFieldWhichFailedValidation:AITextField)? {
    return validateTextField(txtField: txtField, forRules: rules, withMinimumChar: 0, andMaximumChar: 0)
}



func validateTextField(txtField:AITextField, forRules rules:[AIValidationRule], withMinimumChar minChar:Int, andMaximumChar maxChar:Int) -> (isValid:Bool, errMessage:String, txtFieldWhichFailedValidation:AITextField)? {

    var strMessage:String = ""
    for eachRule in rules {

        if let result = validateTextField(txtField: txtField, forRule: eachRule, withMinimumChar: minChar, andMaximumChar: maxChar) {
            if(eachRule == AIValidationRule.EmptyCheck){
                return result
            }else{
                strMessage += "\(strMessage.characters.count == 0 ? "" : "\n\n") \(result.errMessage)"
            }
        }
    }
    return strMessage.characters.count > 0 ? (false,strMessage,txtField) : nil
}

Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'

Please see my working sample application on Github and compare with your set up.

Javascript dynamic array of strings

Just initialize an array and push the element on the array. It will automatic scale the array.

var a = [ ];

a.push('Some string'); console.log(a); // ['Some string'] 
a.push('another string'); console.log(a); // ['Some string', 'another string'] 
a.push('Some string'); console.log(a); // ['Some string', 'another string', 'Some string']

Application Loader stuck at "Authenticating with the iTunes store" when uploading an iOS app

Dec 10th 2019, Xcode Version 11.2.1, MacOS X 10.15.1

I was facing exactly same issue yesterday and I thought it might be network issues, at least it looks like so. But this morning I had tried couple different networks and several VPN connections, none of them is working!

The highest voted answer here asks me to reset a cache folder named .itmstransporter under my home dir, the run a program iTMSTransporter under a specific folder, but I can't find both of them.

But soon I figured that it is the cache folder for the people who uses the legacy uploader program: Application Loader, which is deprecated by Apple and can be no longer found in Xcode 11. Then I found that the latest Xcode has located iTMSTransporter here:

/Applications/Xcode.app/Contents/SharedFrameworks/ContentDeliveryServices.framework/itms/bin/iTMSTransporter

And its cache folder is here:

/Users/your_user_name/Library/Caches/com.apple.amp.itmstransporter/

I removed my existed cache folder, and run iTMSTransporter without any parameter, it soon started to output logs and download a bunch of files, and finished in 2 or 3 minutes. Then I tried again to upload my ipa file, it works!!!

CONCLUTION:

  1. Either the old Application Loader, or the latest Xcode, uses a Java program iTMSTransporter to process the ipa file uploading.
  2. To function correctly, iTMSTransporter requires a set of jar files downloaded from Internet and cached in your local folder.
  3. If your cache is somehow broken, or doesn't exist at all, directly invoking iTMSTransporter with functional parameters such as --upload-app in our case, iTMSTransporter DOES NOT WARN YOU, NOR FIX CACHE BY ITSELF, it just gets stuck there, SAYS NOTHING AT ALL! (Whoever wrote this iTMSTransporter, you seriously need to improve your programming sense).
  4. Invoking iTMSTransporter without any parameter fixes the cache.
  5. A functional cache is about 65MB, at Dec 10th 2019 with Xcode Version 11.2.1 (11B500)

jQuery: Get selected element tag name

This is yet another way:

$('selector')[0].tagName

How do I output the difference between two specific revisions in Subversion?

To compare entire revisions, it's simply:

svn diff -r 8979:11390


If you want to compare the last committed state against your currently saved working files, you can use convenience keywords:

svn diff -r PREV:HEAD

(Note, without anything specified afterwards, all files in the specified revisions are compared.)


You can compare a specific file if you add the file path afterwards:

svn diff -r 8979:HEAD /path/to/my/file.php

Ansible date variable

The command ansible localhost -m setup basically says "run the setup module against localhost", and the setup module gathers the facts that you see in the output.

When you run the echo command these facts don't exist since the setup module wasn't run. A better method to testing things like this would be to use ansible-playbook to run a playbook that looks something like this:

- hosts: localhost
  tasks:
      - debug: var=ansible_date_time

      - debug: msg="the current date is {{ ansible_date_time.date }}"

Because this runs as a playbook facts for localhost are gathered before the tasks are run. The output of the above playbook will be something like this:

PLAY [localhost] **************************************************

GATHERING FACTS ***************************************************************
ok: [localhost]

TASK: [debug var=ansible_date_time] *******************************************
ok: [localhost] => {
    "ansible_date_time": {
        "date": "2015-07-09",
        "day": "09",
        "epoch": "1436461166",
        "hour": "16",
        "iso8601": "2015-07-09T16:59:26Z",
        "iso8601_micro": "2015-07-09T16:59:26.896629Z",
        "minute": "59",
        "month": "07",
        "second": "26",
        "time": "16:59:26",
        "tz": "UTC",
        "tz_offset": "+0000",
        "weekday": "Thursday",
        "year": "2015"
    }
}

TASK: [debug msg="the current date is {{ ansible_date_time.date }}"] **********
ok: [localhost] => {
    "msg": "the current date is 2015-07-09"
}

PLAY RECAP ********************************************************************
localhost      : ok=3    changed=0    unreachable=0    failed=0

Turn off warnings and errors on PHP and MySQL

You can set the type of error reporting you need in php.ini or by using the error_reporting() function on top of your script.

$(document).on('click', '#id', function() {}) vs $('#id').on('click', function(){})

The first example demonstrates event delegation. The event handler is bound to an element higher up the DOM tree (in this case, the document) and will be executed when an event reaches that element having originated on an element matching the selector.

This is possible because most DOM events bubble up the tree from the point of origin. If you click on the #id element, a click event is generated that will bubble up through all of the ancestor elements (side note: there is actually a phase before this, called the 'capture phase', when the event comes down the tree to the target). You can capture the event on any of those ancestors.

The second example binds the event handler directly to the element. The event will still bubble (unless you prevent that in the handler) but since the handler is bound to the target, you won't see the effects of this process.

By delegating an event handler, you can ensure it is executed for elements that did not exist in the DOM at the time of binding. If your #id element was created after your second example, your handler would never execute. By binding to an element that you know is definitely in the DOM at the time of execution, you ensure that your handler will actually be attached to something and can be executed as appropriate later on.

How can I get javascript to read from a .json file?

Actually, you are looking for the AJAX CALL, in which you will replace the URL parameter value with the link of the JSON file to get the JSON values.

$.ajax({
    url: "File.json", //the path of the file is replaced by File.json
    dataType: "json",
    success: function (response) {
        console.log(response); //it will return the json array
    }
});

Oracle - how to remove white spaces?

Run below query replacing TABLE_NAME & COLUMN_NAME with your actual table & column names:

UPDATE TABLE_NAME SET COLUMN_NAME=TRIM(' ' from COLUMN_NAME);

Error: Unexpected value 'undefined' imported by the module

Another reason could be some code like this:

_x000D_
_x000D_
import { NgModule } from '@angular/core';_x000D_
import { SharedModule } from 'app/shared/shared.module';_x000D_
import { CoreModule } from 'app/core/core.module';_x000D_
import { RouterModule } from '@angular/router';_x000D_
import { COMPANY_ROUTES } from 'app/company/company.routing';_x000D_
import { CompanyService } from 'app/company/services/company.service';_x000D_
import { CompanyListComponent } from 'app/company/components/company-list/company-list.component';_x000D_
_x000D_
@NgModule({_x000D_
    imports: [_x000D_
        CoreModule,_x000D_
        SharedModule,_x000D_
  RouterModule.forChild(COMPANY_ROUTES)_x000D_
    ],_x000D_
    declarations: [_x000D_
  CompanyListComponent_x000D_
    ],_x000D_
    providers: [_x000D_
  CompanyService_x000D_
    ],_x000D_
    exports: [_x000D_
    ]_x000D_
})_x000D_
export class CompanyModule { }
_x000D_
_x000D_
_x000D_

Because exports is empty array and it has , before it, it should be removed.

Webpack.config how to just copy the index.html to the dist folder

I also found it easy and generic enough to put my index.html file in dist/ directory and add <script src='main.js'></script> to index.html to include my bundled webpack files. main.js seems to be default output name of our bundle if no other specified in webpack's conf file. I guess it's not good and long-term solution, but I hope it can help to understand how webpack works.

Search and replace a line in a file in Python

As lassevk suggests, write out the new file as you go, here is some example code:

fin = open("a.txt")
fout = open("b.txt", "wt")
for line in fin:
    fout.write( line.replace('foo', 'bar') )
fin.close()
fout.close()

How to run a method every X seconds

You can please try this code to call the handler every 15 seconds via onResume() and stop it when the activity is not visible, via onPause().

Handler handler = new Handler();
Runnable runnable;
int delay = 15*1000; //Delay for 15 seconds.  One second = 1000 milliseconds.


@Override
protected void onResume() {
   //start handler as activity become visible

    handler.postDelayed( runnable = new Runnable() {
        public void run() {
            //do something

            handler.postDelayed(runnable, delay);
        }
    }, delay);

    super.onResume();
}

// If onPause() is not included the threads will double up when you 
// reload the activity 

@Override
protected void onPause() {
    handler.removeCallbacks(runnable); //stop handler when activity not visible
    super.onPause();
}

Node.js, can't open files. Error: ENOENT, stat './path/to/file'

Paths specified with a . are relative to the current working directory, not relative to the script file. So the file might be found if you run node app.js but not if you run node folder/app.js. The only exception to this is require('./file') and that is only possible because require exists per-module and thus knows what module it is being called from.

To make a path relative to the script, you must use the __dirname variable.

var path = require('path');

path.join(__dirname, 'path/to/file')

or potentially

path.join(__dirname, 'path', 'to', 'file')

Android ListView selected item stay highlighted

Use the id instead:

This is the easiest method that can handle even if the list is long:

public View getView(final int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    Holder holder=new Holder();
    View rowView;
    rowView = inflater.inflate(R.layout.list_item, null);
    //Handle your items.
    //StringHolder.mSelectedItem is a public static variable.
    if(getItemId(position)==StringHolder.mSelectedItem){
        rowView.setBackgroundColor(Color.LTGRAY);

    }else{
        rowView.setBackgroundColor(Color.TRANSPARENT);
    }
    return rowView;
}

And then in your onclicklistener:

list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            StringHolder.mSelectedItem = catagoryAdapter.getItemId(i-1);
            catagoryAdapter.notifyDataSetChanged();
.....

What does "<html xmlns="http://www.w3.org/1999/xhtml">" do?

The namespace name http://www.w3.org/1999/xhtml 
is intended for use in various specifications such as:

Recommendations:

    XHTML™ 1.0: The Extensible HyperText Markup Language
    XHTML Modularization
    XHTML 1.1
    XHTML Basic
    XHTML Print
    XHTML+RDFa

Check here for more detail

CSS transition fade in

CSS Keyframes support is pretty good these days:

_x000D_
_x000D_
.fade-in {_x000D_
 opacity: 1;_x000D_
 animation-name: fadeInOpacity;_x000D_
 animation-iteration-count: 1;_x000D_
 animation-timing-function: ease-in;_x000D_
 animation-duration: 2s;_x000D_
}_x000D_
_x000D_
@keyframes fadeInOpacity {_x000D_
 0% {_x000D_
  opacity: 0;_x000D_
 }_x000D_
 100% {_x000D_
  opacity: 1;_x000D_
 }_x000D_
}
_x000D_
<h1 class="fade-in">Fade Me Down Scotty</h1>
_x000D_
_x000D_
_x000D_

What does the Java assert keyword do, and when should it be used?

A lot of good answers explaining what the assert keyword does, but few answering the real question, "when should the assert keyword be used in real life?"

The answer: almost never.

Assertions, as a concept, are wonderful. Good code has lots of if (...) throw ... statements (and their relatives like Objects.requireNonNull and Math.addExact). However, certain design decisions have greatly limited the utility of the assert keyword itself.

The driving idea behind the assert keyword is premature optimization, and the main feature is being able to easily turn off all checks. In fact, the assert checks are turned off by default.

However, it is critically important that invariant checks continue to be done in production. This is because perfect test coverage is impossible, and all production code will have bugs which assertions should help to diagnose and mitigate.

Therefore, the use of if (...) throw ... should be preferred, just as it is required for checking parameter values of public methods and for throwing IllegalArgumentException.

Occasionally, one might be tempted to write an invariant check that does take an undesirably long time to process (and is called often enough for it to matter). However, such checks will slow down testing which is also undesirable. Such time-consuming checks are usually written as unit tests. Nevertheless, it may sometimes make sense to use assert for this reason.

Do not use assert simply because it is cleaner and prettier than if (...) throw ... (and I say that with great pain, because I like clean and pretty). If you just cannot help yourself, and can control how your application is launched, then feel free to use assert but always enable assertions in production. Admittedly, this is what I tend to do. I am pushing for a lombok annotation that will cause assert to act more like if (...) throw .... Vote for it here.

(Rant: the JVM devs were a bunch of awful, prematurely optimizing coders. That is why you hear about so many security issues in the Java plugin and JVM. They refused to include basic checks and assertions in production code, and we are continuing to pay the price.)

Bootstrap 3 Navbar Collapse

I did the CSS way with my install of Bootstrap 3.0.0, since I am not that familiar with LESS. Here is the code that I added to my custom css file (which I load after bootstrap.css) which allowed me to control so the menu was always working like an accordion.
Note: I wrapped my whole navbar inside a div with the class sidebar to separate out the behavior I wanted so it did not affect other navbars on my site, like the main menu. Adjust along your needs, hope it is of help.

/* Sidebar Menu Fix */

.sidebar .navbar-nav {
  margin: 7.5px -15px;
}
.sidebar .navbar-nav > li > a {
  padding-top: 10px;
  padding-bottom: 10px;
  line-height: 20px;
}
.sidebar .navbar-collapse {
  max-height: 500px;
}
.sidebar .navbar-nav .open .dropdown-menu {
  position: static;
  float: none;
  width: auto;
  margin-top: 0;
  background-color: transparent;
  border: 0;
  box-shadow: none;
}
.sidebar .dropdown-menu > li > a {
  color: #777777;
}
.sidebar .navbar-default .navbar-nav .open .dropdown-menu > li > a:hover,
.sidebar .navbar-default .navbar-nav .open .dropdown-menu > li > a:focus {
  color: #333333;
  background-color: transparent;
}
.sidebar .navbar-default .navbar-nav .open .dropdown-menu > .active > a,
.sidebar .navbar-default .navbar-nav .open .dropdown-menu > .active > a:hover,
.sidebar .navbar-default .navbar-nav .open .dropdown-menu > .active > a:focus {
  color: #555555;
  background-color: #e7e7e7;
}
.sidebar .navbar-nav {
  float: none;
}
.sidebar .navbar-nav > li {
  float: none;
}

Additional note: I also added a change to the toggle of the main menu navbar (since the code above on my site is used for a "submenu" on the side.

I changed:

<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

into:

<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse-topmenu">

And then also adjusted:

<div class="navbar-collapse collapse navbar-collapse">

into:

<div class="navbar-collapse collapse navbar-collapse-topmenu">

If you will only have one navbar I guess you will not need to worry about this, but it helped me in my case.

How do I correctly detect orientation change using Phonegap on iOS?

I'm pretty new to iOS and Phonegap as well, but I was able to do this by adding in an eventListener. I did the same thing (using the example you reference), and couldn't get it to work. But this seemed to do the trick:

// Event listener to determine change (horizontal/portrait)
window.addEventListener("orientationchange", updateOrientation); 

function updateOrientation(e) {
switch (e.orientation)
{   
    case 0:
        // Do your thing
        break;

    case -90:
        // Do your thing
        break;

    case 90:
        // Do your thing
        break;

    default:
        break;
    }
}

You may have some luck searching the PhoneGap Google Group for the term "orientation".

One example I read about as an example on how to detect orientation was Pie Guy: (game, js file). It's similar to the code you've posted, but like you... I couldn't get it to work.

One caveat: the eventListener worked for me, but I'm not sure if this is an overly intensive approach. So far it's been the only way that's worked for me, but I don't know if there are better, more streamlined ways.


UPDATE fixed the code above, it works now

Retrieve data from website in android app

You can do the HTML parsing but it is not at all recommended instead ask the website owners to provide web services then you can parse that information.

C#, Looping through dataset and show each record from a dataset column

I believe you intended it more this way:

foreach (DataTable table in ds.Tables)
{
    foreach (DataRow dr in table.Rows)
    {
        DateTime TaskStart = DateTime.Parse(dr["TaskStart"].ToString());
        TaskStart.ToString("dd-MMMM-yyyy");
        rpt.SetParameterValue("TaskStartDate", TaskStart);
    }
}

You always accessed your first row in your dataset.

Load text file as strings using numpy.loadtxt()

Is it essential that you need a NumPy array? Otherwise you could speed things up by loading the data as a nested list.

def load(fname):
    ''' Load the file using std open'''
    f = open(fname,'r')

    data = []
    for line in f.readlines():
        data.append(line.replace('\n','').split(' '))

    f.close()

    return data

For a text file with 4000x4000 words this is about 10 times faster than loadtxt.

Printing a 2D array in C

First you need to input the two numbers say num_rows and num_columns perhaps using argc and argv then do a for loop to print the dots.

int j=0;
int k=0;
for (k=0;k<num_columns;k++){
   for (j=0;j<num_rows;j++){
       printf(".");
   }
 printf("\n");
 }

you'd have to replace the dot with something else later.

Git pull after forced update

Pull with rebase

A regular pull is fetch + merge, but what you want is fetch + rebase. This is an option with the pull command:

git pull --rebase

How to use SQL LIKE condition with multiple values in PostgreSQL?

Following query helped me. Instead of using LIKE, you can use ~*.

select id, name from hosts where name ~* 'julia|lena|jack';

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

Encountered the same issue, after downloading a project, in debug mode. Searched for hours without any luck. Following resolved my problem;

Project Properties -> Linker -> Output file -> $(OutDir)$(TargetName)$(TargetExt)

It was previously pointing to a folder that MSVS wasn't running from whilst debugging mode.

EDIT: soon as I posted this I came across: unable to start "program.exe" the system cannot find the file specified vs2008 which explains the same thing.

Include an SVG (hosted on GitHub) in MarkDown

The purpose of raw.github.com is to allow users to view the contents of a file, so for text based files this means (for certain content types) you can get the wrong headers and things break in the browser.

When this question was asked (in 2012) SVGs didn't work. Since then Github has implemented various improvements. Now (at least for SVG), the correct Content-Type headers are sent.

Examples

All of the ways stated below will work.

I copied the SVG image from the question to a repo on github in order to create the examples below

Linking to files using relative paths (Works, but obviously only on github.com / github.io)

Code

![Alt text](./controllers_brief.svg)
<img src="./controllers_brief.svg">

Result

See the working example on github.com.

Linking to RAW files

Code

![Alt text](https://raw.github.com/potherca-blog/StackOverflow/master/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg)
<img src="https://raw.github.com/potherca-blog/StackOverflow/master/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg">

Result

Alt text

Linking to RAW files using ?sanitize=true

Code

![Alt text](https://raw.github.com/potherca-blog/StackOverflow/master/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg?sanitize=true)
<img src="https://raw.github.com/potherca-blog/StackOverflow/master/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg?sanitize=true">

Result

Alt text

Linking to files hosted on github.io

Code

![Alt text](https://potherca-blog.github.io/StackOverflow/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg)
<img src="https://potherca-blog.github.io/StackOverflow/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg">

Result

Alt text


Some comments regarding changes that happened along the way:

  • Github has implemented a feature which makes it possible for SVG's to be used with the Markdown image syntax. The SVG image will be sanitized and displayed with the correct HTTP header. Certain tags (like <script>) are removed.

    To view the sanitized SVG or to achieve this effect from other places (i.e. from markdown files not hosted in repos on http://github.com/) simply append ?sanitize=true to the SVG's raw URL.

  • As stated by AdamKatz in the comments, using a source other than github.io can introduce potentially privacy and security risks. See the answer by CiroSantilli and the answer by DavidChambers for more details.

  • The issue to resolve this was opened on Github on October 13th 2015 and was resolved on August 31th 2017

bundle install fails with SSL certificate verification error

Thx to @Alexander.Iljushkin for:

gem update --system --source http://rubygems.org/

After that bundler still failed and the solution to that was:

gem install bundler

How to pass arguments and redirect stdin from a file to program run in gdb?

You can do this:

gdb --args path/to/executable -every -arg you can=think < of

The magic bit being --args.

Just type run in the gdb command console to start debugging.

Format an Integer using Java String Format

Use %03d in the format specifier for the integer. The 0 means that the number will be zero-filled if it is less than three (in this case) digits.

See the Formatter docs for other modifiers.

Setting Timeout Value For .NET Web Service

After creating your client specifying the binding and endpoint address, you can assign an OperationTimeout,

client.InnerChannel.OperationTimeout = new TimeSpan(0, 5, 0);

Pythonically add header to a csv file

This worked for me.

header = ['row1', 'row2', 'row3']
some_list = [1, 2, 3]
with open('test.csv', 'wt', newline ='') as file:
    writer = csv.writer(file, delimiter=',')
    writer.writerow(i for i in header)
    for j in some_list:
        writer.writerow(j)

MySQL Workbench Edit Table Data is read only

If you set a default schema for your DB Connection then Select will run in readonly mode until you set explicitly your schema

USE mydb;
SELECT * FROM mytable

this will also run in edit mode:

SELECT * FROM mydb.mytable 

(MySql 5.2.42 / MacOsX)

I hope this helps.

"Failed to install the following Android SDK packages as some licences have not been accepted" error

I just done File -> Invalidate caches and restart Then install missing packages. Worked for me.

Correct owner/group/permissions for Apache 2 site files/folders under Mac OS X?

On my 10.6 system:

vhosts folder:
 owner:root
 group:wheel
 permissions:755

vhost.conf files:
 owner:root
 group:wheel
 permissions:644

Change Timezone in Lumen or Laravel 5

Use php time zones from php manual Php time zones

For example mine i changed from the UTC value in config/app.php with

'timezone' => 'Africa/Nairobi',

What is the difference between UNION and UNION ALL?

It is good to understand with a Venn diagramm.

here is the link to the source. There is a good description.

enter image description here

Error when using scp command "bash: scp: command not found"

Make sure the scp command is available on both sides - both on the client and on the server.

If this is Fedora or Red Hat Enterprise Linux and clones (CentOS), make sure this package is installed:

    yum -y install openssh-clients

If you work with Debian or Ubuntu and clones, install this package:

    apt-get install openssh-client

Again, you need to do this both on the server and the client, otherwise you can encounter "weird" error messages on your client: scp: command not found or similar although you have it locally. This already confused thousands of people, I guess :)

ab load testing

The apache benchmark tool is very basic, and while it will give you a solid idea of some performance, it is a bad idea to only depend on it if you plan to have your site exposed to serious stress in production.

Having said that, here's the most common and simplest parameters:

-c: ("Concurrency"). Indicates how many clients (people/users) will be hitting the site at the same time. While ab runs, there will be -c clients hitting the site. This is what actually decides the amount of stress your site will suffer during the benchmark.

-n: Indicates how many requests are going to be made. This just decides the length of the benchmark. A high -n value with a -c value that your server can support is a good idea to ensure that things don't break under sustained stress: it's not the same to support stress for 5 seconds than for 5 hours.

-k: This does the "KeepAlive" funcionality browsers do by nature. You don't need to pass a value for -k as it it "boolean" (meaning: it indicates that you desire for your test to use the Keep Alive header from HTTP and sustain the connection). Since browsers do this and you're likely to want to simulate the stress and flow that your site will have from browsers, it is recommended you do a benchmark with this.

The final argument is simply the host. By default it will hit http:// protocol if you don't specify it.

ab -k -c 350 -n 20000 example.com/

By issuing the command above, you will be hitting http://example.com/ with 350 simultaneous connections until 20 thousand requests are met. It will be done using the keep alive header.

After the process finishes the 20 thousand requests, you will receive feedback on stats. This will tell you how well the site performed under the stress you put it when using the parameters above.

For finding out how many people the site can handle at the same time, just see if the response times (means, min and max response times, failed requests, etc) are numbers your site can accept (different sites might desire different speeds). You can run the tool with different -c values until you hit the spot where you say "If I increase it, it starts to get failed requests and it breaks".

Depending on your website, you will expect an average number of requests per minute. This varies so much, you won't be able to simulate this with ab. However, think about it this way: If your average user will be hitting 5 requests per minute and the average response time that you find valid is 2 seconds, that means that 10 seconds out of a minute 1 user will be on requests, meaning only 1/6 of the time it will be hitting the site. This also means that if you have 6 users hitting the site with ab simultaneously, you are likely to have 36 users in simulation, even though your concurrency level (-c) is only 6.

This depends on the behavior you expect from your users using the site, but you can get it from "I expect my user to hit X requests per minute and I consider an average response time valid if it is 2 seconds". Then just modify your -c level until you are hitting 2 seconds of average response time (but make sure the max response time and stddev is still valid) and see how big you can make -c.

I hope I explained this clear :) Good luck

Eclipse copy/paste entire line keyboard shortcut

You have to turn off the graphics hot keys that flip the screen. If you're on Windows, you need to right click on the Windows desktop and select "Graphics Properties..." (or something similar depending on your version of Windows). This will bring up a screen where you can manage graphics and display options, look for a place where you can disable hot keys, sometimes it's hidden under something like "Options and Support". Turn off the CTRL + ALT + ? and CTRL + ALT + ? hotkeys (alternatively you can just disable all graphics hot keys if you're not using them).

ArrayList or List declaration in Java

The difference is that variant 1 forces you to use an ArrayList while variant 2 only guarantees you have anything that implements List<String>.

Later on you could change that to List<String> arrayList = new LinkedList<String>(); without much hassle. Variant 1 might require you to change not only that line but other parts as well if they rely on working with an ArrayList<String>.

Thus I'd use List<String> in almost any case, except when I'd need to call the additional methods that ArrayList provides (which was never the case so far): ensureCapacity(int) and trimToSize().

Should image size be defined in the img tag height/width attributes or in CSS?

I'm using contentEditable to allow rich text editing in my app. I don't know how it slips through, but when an image is inserted, and then resized (by dragging the anchors on its side), it generates something like this:

  <img style="width:55px;height:55px" width="100" height="100" src="pic.gif" border=0/>

(subsequent testing shown that inserted images did not contain this "rogue" style attr+param).

When rendered by the browser (IE7), the width and height in the style overrides the img width/height param (so the image is shown like how I wanted it.. resized to 55px x 55px. So everything went well so it seems.

When I output the page to a ms-word document via setting the mime type application/msword or pasting the browser rendering to msword document, all the images reverted back to its default size. I finally found out that msword is discarding the style and using the img width and height tag (which has the value of the original image size).

Took me a while to found this out. Anyway... I've coded a javascript function to traverse all tags and "transferring" the img style.width and style.height values into the img.width and img.height, then clearing both the values in style, before I proceed saving this piece of html/richtext data into the database.

cheers.

opps.. my answer is.. no. leave both attributes directly under img, rather than style.

Installing Numpy on 64bit Windows 7 with Python 2.7.3

Download numpy-1.9.2+mkl-cp27-none-win32.whl from http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy .

Copy the file to C:\Python27\Scripts

Run cmd from the above location and type

pip install numpy-1.9.2+mkl-cp27-none-win32.whl

You will hopefully get the below output:

Processing c:\python27\scripts\numpy-1.9.2+mkl-cp27-none-win32.whl
Installing collected packages: numpy
Successfully installed numpy-1.9.2

Hope that works for you.

EDIT 1
Adding @oneleggedmule 's suggestion:

You can also run the following command in the cmd:

pip2.7 install numpy-1.9.2+mkl-cp27-none-win_amd64.whl

Basically, writing pip alone also works perfectly (as in the original answer). Writing the version 2.7 can also be done for the sake of clarity or specification.

Facebook Open Graph not clearing cache

I had a different, but similar problem with Facebook recently, and found that the scraper/debug page mentioned, simply does not appear to read any page in its entirety. My meta properties for Open Graph were further down in the head section, and the scraper would constantly inform me that the image specification was not correct, and would use a cached version regardless. I moved the Open Graph tags further up in the code, near the very top of the page, and then everything worked perfectly, every time.

export html table to csv

Using just jQuery, vanilla Javascript, and the table2CSV library:

export-to-html-table-as-csv-file-using-jquery

Put this code into a script to be loaded in the head section:

 $(document).ready(function () {
    $('table').each(function () {
        var $table = $(this);

        var $button = $("<button type='button'>");
        $button.text("Export to spreadsheet");
        $button.insertAfter($table);

        $button.click(function () {
            var csv = $table.table2CSV({
                delivery: 'value'
            });
            window.location.href = 'data:text/csv;charset=UTF-8,' 
            + encodeURIComponent(csv);
        });
    });
})

Notes:

Requires jQuery and table2CSV: Add script references to both libraries before the script above.

The table selector is used as an example, and can be adjusted to suit your needs.

It only works in browsers with full Data URI support: Firefox, Chrome and Opera, not in IE, which only supports Data URIs for embedding binary image data into a page.

For full browser compatibility you would have to use a slightly different approach that requires a server side script to echo the CSV.

Share application "link" in Android

You can use also ShareCompat class from support library.

ShareCompat.IntentBuilder.from(activity)
    .setType("text/plain")
    .setChooserTitle("Chooser title")
    .setText("http://play.google.com/store/apps/details?id=" + activity.getPackageName())
    .startChooser();

https://developer.android.com/reference/android/support/v4/app/ShareCompat.html

How to create a .jar file or export JAR in IntelliJ IDEA (like Eclipse Java archive export)?

In intellij8 I was using a specific plugin "Jar Tool" that is configurable and allows to pack a JAR archive.

Set disable attribute based on a condition for Html.TextBoxFor

Actually, the internal behavior is translating the anonymous object to a dictionary. So what I do in these scenarios is go for a dictionary:

@{
  var htmlAttributes = new Dictionary<string, object>
  {
    { "class" , "form-control"},
    { "placeholder", "Why?" }        
  };
  if (Model.IsDisabled)
  {
    htmlAttributes.Add("disabled", "disabled");
  }
}
@Html.EditorFor(m => m.Description, new { htmlAttributes = htmlAttributes })

Or, as Stephen commented here:

@Html.EditorFor(m => m.Description,
    Model.IsDisabled ? (object)new { disabled = "disabled" } : (object)new { })

How to use the PRINT statement to track execution as stored procedure is running?

Can I just ask about the long term need for this facility - is it for debuging purposes?

If so, then you may want to consider using a proper debugger, such as the one found in Visual Studio, as this allows you to step through the procedure in a more controlled way, and avoids having to constantly add/remove PRINT statement from the procedure.

Just my opinion, but I prefer the debugger approach - for code and databases.

How to get Selected Text from select2 when using <input>

I finally figured it out doing this:

var $your-original-element = $('.your-original-element');
var data = $your-original-element.select2('data')[0]['text'];
alert(data);

if you also want the value:

var value = $your-original-element.select2('data')[0]['id'];
alert(value);

Python FileNotFound

try block should be around open. Not around prompt.

while True:
    prompt = input("\n Hello to Sudoku valitator,"
    "\n \n Please type in the path to your file and press 'Enter': ")
    try:
        sudoku = open(prompt, 'r').readlines()
    except FileNotFoundError:
        print("Wrong file or file path")
    else:
        break

Bootstrap 4: Multilevel Dropdown Inside Navigation

I use the following piece of CSS and JavaScript. It uses an extra class dropdown-submenu. I tested it with Bootstrap 4 beta.

It supports multi level sub menus.

_x000D_
_x000D_
$('.dropdown-menu a.dropdown-toggle').on('click', function(e) {_x000D_
  if (!$(this).next().hasClass('show')) {_x000D_
    $(this).parents('.dropdown-menu').first().find('.show').removeClass('show');_x000D_
  }_x000D_
  var $subMenu = $(this).next('.dropdown-menu');_x000D_
  $subMenu.toggleClass('show');_x000D_
_x000D_
_x000D_
  $(this).parents('li.nav-item.dropdown.show').on('hidden.bs.dropdown', function(e) {_x000D_
    $('.dropdown-submenu .show').removeClass('show');_x000D_
  });_x000D_
_x000D_
_x000D_
  return false;_x000D_
});
_x000D_
.dropdown-submenu {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.dropdown-submenu a::after {_x000D_
  transform: rotate(-90deg);_x000D_
  position: absolute;_x000D_
  right: 6px;_x000D_
  top: .8em;_x000D_
}_x000D_
_x000D_
.dropdown-submenu .dropdown-menu {_x000D_
  top: 0;_x000D_
  left: 100%;_x000D_
  margin-left: .1rem;_x000D_
  margin-right: .1rem;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">_x000D_
_x000D_
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>_x000D_
_x000D_
<nav class="navbar navbar-expand-lg navbar-light bg-light">_x000D_
  <a class="navbar-brand" href="#">Navbar</a>_x000D_
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">_x000D_
    <span class="navbar-toggler-icon"></span>_x000D_
  </button>_x000D_
  <div class="collapse navbar-collapse" id="navbarNavDropdown">_x000D_
    <ul class="navbar-nav">_x000D_
      <li class="nav-item active">_x000D_
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>_x000D_
      </li>_x000D_
      <li class="nav-item dropdown">_x000D_
        <a class="nav-link dropdown-toggle" href="http://example.com" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">_x000D_
          Dropdown link_x000D_
        </a>_x000D_
        <ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">_x000D_
          <li><a class="dropdown-item" href="#">Action</a></li>_x000D_
          <li><a class="dropdown-item" href="#">Another action</a></li>_x000D_
          <li class="dropdown-submenu">_x000D_
            <a class="dropdown-item dropdown-toggle" href="#">Submenu</a>_x000D_
            <ul class="dropdown-menu">_x000D_
              <li><a class="dropdown-item" href="#">Submenu action</a></li>_x000D_
              <li><a class="dropdown-item" href="#">Another submenu action</a></li>_x000D_
_x000D_
_x000D_
              <li class="dropdown-submenu">_x000D_
                <a class="dropdown-item dropdown-toggle" href="#">Subsubmenu</a>_x000D_
                <ul class="dropdown-menu">_x000D_
                  <li><a class="dropdown-item" href="#">Subsubmenu action</a></li>_x000D_
                  <li><a class="dropdown-item" href="#">Another subsubmenu action</a></li>_x000D_
                </ul>_x000D_
              </li>_x000D_
              <li class="dropdown-submenu">_x000D_
                <a class="dropdown-item dropdown-toggle" href="#">Second subsubmenu</a>_x000D_
                <ul class="dropdown-menu">_x000D_
                  <li><a class="dropdown-item" href="#">Subsubmenu action</a></li>_x000D_
                  <li><a class="dropdown-item" href="#">Another subsubmenu action</a></li>_x000D_
                </ul>_x000D_
              </li>_x000D_
_x000D_
_x000D_
_x000D_
            </ul>_x000D_
          </li>_x000D_
        </ul>_x000D_
      </li>_x000D_
    </ul>_x000D_
  </div>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

Whitespace Matching Regex - Java

For your purpose you can use this snnippet:

import org.apache.commons.lang3.StringUtils;

StringUtils.normalizeSpace(string);

This will normalize the spacing to single and will strip off the starting and trailing whitespaces as well.

String sampleString = "Hello    world!";
sampleString.replaceAll("\\s{2}", " "); // replaces exactly two consecutive spaces
sampleString.replaceAll("\\s{2,}", " "); // replaces two or more consecutive white spaces

How to format Joda-Time DateTime to only mm/dd/yyyy?

Please try to this one

public void Method(Datetime time)
{
    time.toString("yyyy-MM-dd'T'HH:mm:ss"));
}

Eclipse C++ : "Program "g++" not found in PATH"

enter image description hereIf you just want to run C program but meet this error, it might mean that MinGw c++ compiler has not been installed even if "C:\MinGW\bin" has already been added to Windows Path variable.

Solution:

  1. Run "mingw-get-setup.exe" to open MinGW Installation Manager

  2. Open All Packages->MinGw->MinGW Base System->MinGW Compiler Suite

  3. Select the following compilers to install:

    . mingw32-gcc-g++

    . mingw32-gcc-v3-core

    . mingw32-gcc-vc-g++

  4. Click Installation->Apply Changes to apply the above changes

  5. Wait for the installation finishing(There might be some errors, just ignore them).

  6. Restart Eclipse.

  7. Done.

It Worked in my environment.

Hope it works in your case.

how can I set visible back to true in jquery

Depends, if i remember correctly i think asp.net won't render the html object out when you set visible to false.

If you want to be able to control it from the client side, then you better just include the css value to set it invisible rather than using visible =false.

change PATH permanently on Ubuntu

Add

export PATH=$PATH:/home/me/play

to your ~/.profile and execute

source ~/.profile 

in order to immediately reflect changes to your current terminal instance.

Find ALL tweets from a user (not just the first 3,200)

The only way to see more is to start saving them before the user's tweet count hits 3200. Services which show more than 3200 tweets have saved them in their own dbs. There's currently no way to get more than that through any Twitter API.

http://www.quora.com/Is-there-a-way-to-get-more-than-3200-tweets-from-a-twitter-user-using-Twitters-API-or-scraping

https://dev.twitter.com/discussions/276

Note from that second link: "…the 3,200 limit is for browsing the timeline only. Tweets can always be requested by their ID using the GET statuses/show/:id method."

SQL Developer is returning only the date, not the time. How do I fix this?

Date format can also be set by using below query :-

alter SESSION set NLS_DATE_FORMAT = 'date_format'

e.g. : alter SESSION set NLS_DATE_FORMAT = 'DD-MM-YYYY HH24:MI:SS'

Global variables in header file

Don't initialize variables in headers. Put declaration in header and initialization in one of the c files.

In the header:

extern int i;

In file2.c:

int i=1;

Sequelize, convert entity to plain object

you can use the query options {raw: true} to return the raw result. Your query should like follows:

db.Sensors.findAll({
  where: {
    nodeid: node.nodeid
  },
  raw: true,
})

also if you have associations with include that gets flattened. So, we can use another parameter nest:true

db.Sensors.findAll({
  where: {
    nodeid: node.nodeid
  },
  raw: true,
  nest: true,
})

HTML form do some "action" when hit submit button

Ok, I'll take a stab at this. If you want to work with PHP, you will need to install and configure both PHP and a webserver on your machine. This article might get you started: PHP Manual: Installation on Windows systems

Once you have your environment setup, you can start working with webforms. Directly From the article: Processing form data with PHP:

For this example you will need to create two pages. On the first page we will create a simple HTML form to collect some data. Here is an example:

<html>   
<head>
 <title>Test Page</title>
</head>   
<body>   
    <h2>Data Collection</h2><p>
    <form action="process.php" method="post">  
        <table>
            <tr>
                <td>Name:</td>
                <td><input type="text" name="Name"/></td>
            </tr>   
            <tr>
                <td>Age:</td>
                <td><input type="text" name="Age"/></td>
            </tr>   
            <tr>
                <td colspan="2" align="center">
                <input type="submit"/>
                </td>
            </tr>
        </table>
    </form>
</body>
</html>

This page will send the Name and Age data to the page process.php. Now lets create process.php to use the data from the HTML form we made:

<?php   
    print "Your name is ". $Name;   
    print "<br />";   
    print "You are ". $Age . " years old";   
    print "<br />";   $old = 25 + $Age;
    print "In 25 years you will be " . $old . " years old";   
?>

As you may be aware, if you leave out the method="post" part of the form, the URL with show the data. For example if your name is Bill Jones and you are 35 years old, our process.php page will display as http://yoursite.com/process.php?Name=Bill+Jones&Age=35 If you want, you can manually change the URL in this way and the output will change accordingly.

Additional JavaScript Example

This single file example takes the html from your question and ties the onSubmit event of the form to a JavaScript function that pulls the values of the 2 textboxes and displays them in an alert box.

Note: document.getElementById("fname").value gets the object with the ID tag that equals fname and then pulls it's value - which in this case is the text in the First Name textbox.

 <html>
    <head>
     <script type="text/javascript">
     function ExampleJS(){
        var jFirst = document.getElementById("fname").value;
        var jLast = document.getElementById("lname").value;
        alert("Your name is: " + jFirst + " " + jLast);
     }
     </script>

    </head>
    <body>
        <FORM NAME="myform" onSubmit="JavaScript:ExampleJS()">

             First name: <input type="text" id="fname" name="firstname" /><br />
             Last name:  <input type="text" id="lname" name="lastname" /><br />
            <input name="Submit"  type="submit" value="Update" />
        </FORM>
    </body>
</html>

How to implement a ViewPager with different Fragments / Layouts

Create new instances in your fragments and do like so in your Activity

 private class SlidePagerAdapter extends FragmentStatePagerAdapter {
    public SlidePagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        switch(position){
            case 0:
                return Fragment1.newInstance();
            case 1:
                return Fragment2.newInstance();
            case 2:
                return Fragment3.newInstance();
            case 3:
                return Fragment4.newInstance();


            default: break;

        }
        return null;
    }

Call japplet from jframe

First of all, Applets are designed to be run from within the context of a browser (or applet viewer), they're not really designed to be added into other containers.

Technically, you can add a applet to a frame like any other component, but personally, I wouldn't. The applet is expecting a lot more information to be available to it in order to allow it to work fully.

Instead, I would move all of the "application" content to a separate component, like a JPanel for example and simply move this between the applet or frame as required...

ps- You can use f.setLocationRelativeTo(null) to center the window on the screen ;)

Updated

You need to go back to basics. Unless you absolutely must have one, avoid applets until you understand the basics of Swing, case in point...

Within the constructor of GalzyTable2 you are doing...

JApplet app = new JApplet(); add(app); app.init(); app.start(); 

...Why are you adding another applet to an applet??

Case in point...

Within the main method, you are trying to add the instance of JFrame to itself...

f.getContentPane().add(f, button2); 

Instead, create yourself a class that extends from something like JPanel, add your UI logical to this, using compound components if required.

Then, add this panel to whatever top level container you need.

Take the time to read through Creating a GUI with Swing

Updated with example

import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException;  public class GalaxyTable2 extends JPanel {      private static final int PREF_W = 700;     private static final int PREF_H = 600;      String[] columnNames                     = {"Phone Name", "Brief Description", "Picture", "price",                         "Buy"};  // Create image icons     ImageIcon Image1 = new ImageIcon(                     getClass().getResource("s1.png"));     ImageIcon Image2 = new ImageIcon(                     getClass().getResource("s2.png"));     ImageIcon Image3 = new ImageIcon(                     getClass().getResource("s3.png"));     ImageIcon Image4 = new ImageIcon(                     getClass().getResource("s4.png"));     ImageIcon Image5 = new ImageIcon(                     getClass().getResource("note.png"));     ImageIcon Image6 = new ImageIcon(                     getClass().getResource("note2.png"));     ImageIcon Image7 = new ImageIcon(                     getClass().getResource("note3.png"));      Object[][] rowData = {         {"Galaxy S", "3G Support,CPU 1GHz",             Image1, 120, false},         {"Galaxy S II", "3G Support,CPU 1.2GHz",             Image2, 170, false},         {"Galaxy S III", "3G Support,CPU 1.4GHz",             Image3, 205, false},         {"Galaxy S4", "4G Support,CPU 1.6GHz",             Image4, 230, false},         {"Galaxy Note", "4G Support,CPU 1.4GHz",             Image5, 190, false},         {"Galaxy Note2 II", "4G Support,CPU 1.6GHz",             Image6, 190, false},         {"Galaxy Note 3", "4G Support,CPU 2.3GHz",             Image7, 260, false},};      MyTable ss = new MyTable(                     rowData, columnNames);      // Create a table     JTable jTable1 = new JTable(ss);      public GalaxyTable2() {         jTable1.setRowHeight(70);          add(new JScrollPane(jTable1),                         BorderLayout.CENTER);          JPanel buttons = new JPanel();          JButton button = new JButton("Home");         buttons.add(button);         JButton button2 = new JButton("Confirm");         buttons.add(button2);          add(buttons, BorderLayout.SOUTH);     }      @Override      public Dimension getPreferredSize() {         return new Dimension(PREF_W, PREF_H);     }      public void actionPerformed(ActionEvent e) {         new AMainFrame7().setVisible(true);     }      public static void main(String[] args) {          EventQueue.invokeLater(new Runnable() {             @Override             public void run() {                 try {                     UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());                 } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {                     ex.printStackTrace();                 }                  JFrame frame = new JFrame("Testing");                 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);                 frame.add(new GalaxyTable2());                 frame.pack();                 frame.setLocationRelativeTo(null);                 frame.setVisible(true);             }         });     } } 

You also seem to have a lack of understanding about how to use layout managers.

Take the time to read through Creating a GUI with Swing and Laying components out in a container

Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviations with _mm_popcnt_u64 on Intel CPUs

I can't give an authoritative answer, but provide an overview of a likely cause. This reference shows pretty clearly that for the instructions in the body of your loop there is a 3:1 ratio between latency and throughput. It also shows the effects of multiple dispatch. Since there are (give-or-take) three integer units in modern x86 processors, it's generally possible to dispatch three instructions per cycle.

So between peak pipeline and multiple dispatch performance and failure of these mechanisms, we have a factor of six in performance. It's pretty well known that the complexity of the x86 instruction set makes it quite easy for quirky breakage to occur. The document above has a great example:

The Pentium 4 performance for 64-bit right shifts is really poor. 64-bit left shift as well as all 32-bit shifts have acceptable performance. It appears that the data path from the upper 32 bits to the lower 32 bit of the ALU is not well designed.

I personally ran into a strange case where a hot loop ran considerably slower on a specific core of a four-core chip (AMD if I recall). We actually got better performance on a map-reduce calculation by turning that core off.

Here my guess is contention for integer units: that the popcnt, loop counter, and address calculations can all just barely run at full speed with the 32-bit wide counter, but the 64-bit counter causes contention and pipeline stalls. Since there are only about 12 cycles total, potentially 4 cycles with multiple dispatch, per loop body execution, a single stall could reasonably affect run time by a factor of 2.

The change induced by using a static variable, which I'm guessing just causes a minor reordering of instructions, is another clue that the 32-bit code is at some tipping point for contention.

I know this is not a rigorous analysis, but it is a plausible explanation.

How can I remove Nan from list Python/NumPy

In your example 'nan' is a string so instead of using isnan() just check for the string

like this:

cleanedList = [x for x in countries if x != 'nan']

Change the color of a checked menu item in a navigation drawer

I believe app:itemBackground expects a drawable. So follow the steps below :

Make a drawable file highlight_color.xml with following contents :

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
     <solid android:color="YOUR HIGHLIGHT COLOR"/>
</shape>

Make another drawable file nav_item_drawable.xml with following contents:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:drawable="@drawable/highlight_color" android:state_checked="true"/>
</selector>

Finally add app:itemBackground tag in the NavView :

<android.support.design.widget.NavigationView
android:id="@+id/activity_main_navigationview"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/drawer_header"
app:itemIconTint="@color/black"
app:itemTextColor="@color/primary_text"
app:itemBackground="@drawable/nav_item_drawable"
app:menu="@menu/menu_drawer">

here the highlight_color.xml file defines a solid color drawable for the background. Later this color drawable is assigned to nav_item_drawable.xml selector.

This worked for me. Hopefully this will help.

********************************************** UPDATED **********************************************

Though the above mentioned answer gives you fine control over some properties, but the way I am about to describe feels more SOLID and is a bit COOLER.

So what you can do is, you can define a ThemeOverlay in the styles.xml for the NavigationView like this :

    <style name="ThemeOverlay.AppCompat.navTheme">

        <!-- Color of text and icon when SELECTED -->
        <item name="colorPrimary">@color/color_of_your_choice</item> 

        <!-- Background color when SELECTED -->
        <item name="colorControlHighlight">@color/color_of_your_choice</item> 

    </style>

now apply this ThemeOverlay to app:theme attribute of NavigationView, like this:

<android.support.design.widget.NavigationView
android:id="@+id/activity_main_navigationview"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:theme="@style/ThemeOverlay.AppCompat.navTheme"
app:headerLayout="@layout/drawer_header"
app:menu="@menu/menu_drawer">

I hope this will help.

jQuery input button click event listener

More on gdoron's answer, it can also be done this way:

$(window).on("click", "#filter", function() {
    alert('clicked!');
});

without the need to place them all into $(function(){...})

Install tkinter for Python

Tkinter is a GUI module for python. you can use it to make GUI based applications in python. Tkinter provides several GUI widgets like buttons,menu, canvas,text,frame,label etc. to develop desktop applications.Though Tkinter is very popular and is included with windows, macosx install of python, There are also alternative choices like pyQt, wxPython...

In this tutorial we will see how to install it on linux and use it with an example.

First, check if you have python installed and also check its version

Open up your terminal and type python. if its installed then it will show information like version, help... check your version (mine is python 2.7.9)

aman@vostro:~$ python Python 2.7.9 (default, Apr 2 2015, 15:33:21) [GCC 4.9.2] on linux2 Type "help", "copyright", "credits" or "license" for more information.

If you don't have python then install it sudo apt-get install python

If you want to install python 3 then enter the following. If you are a newbie, I would recommend python 2 instead of python 3. Python 2 is still very popular and many apps are made on it. On ubuntu python2 is still the default sudo apt-get install python3

Finally, Install Tkinter

sudo apt-get install python-tk

for python 3

sudo apt-get install python3-tk

How to Use it

Now, lets check if Tkinter is working well with this little example

open your terminal and enter into your python shell. python

for python3 python3

if python was installed correctly you will get a >>> prompt. aman@vostro:~$ python

Python 2.7.9 (default, Apr  2 2015, 15:33:21)
[GCC 4.9.2] on linux2

Type "help", "copyright", "credits" or "license" for more information.
>>>

Now import Tkinter module. it wont show any error if it got imported correctly. NOTE: Make sure you type Tkinter (not tkinter) in python2 and tkinter (not Tkinter) in python3.

>>>import Tkinter

Now, just to check you can create an empty window using Tkinter.

>>>Tkinter.Tk()

Error message "Unable to install or run the application. The application requires stdole Version 7.0.3300.0 in the GAC"

So it turns out that the .NET files were copied to C:\Program Files\Microsoft.NET\Primary Interop Assemblies\. However, they were never registered in the GAC.

I ended up manually dragging the files in C:\Program Files\Microsoft.NET\Primary Interop Assemblies to C:\windows\assembly and the application worked on that problem machine. You could also do this programmatically with Gacutil.

So it seems that something happened to .NET during the install, but this seems to correct the problem. I hope that helps someone else out!

Renaming the current file in Vim

There's a little plugin that let's you do this.

Android 6.0 Marshmallow. Cannot write to SD Card

First i will give you Dangerous Permission List in Android M and Later version

enter image description here enter image description here

Then give you example of how to request for permission in Android M and later version.

I ask user to WRITE_EXTERNAL_STORAGE permission.

First add permission in your android menifest file

Step 1 Declare requestcode

 private static String TAG = "PermissionDemo";
 private static final int REQUEST_WRITE_STORAGE = 112; 

Step 2 Add this code when you want ask user for permission

 //ask for the permission in android M
    int permission = ContextCompat.checkSelfPermission(this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE);

    if (permission != PackageManager.PERMISSION_GRANTED) {
        Log.i(TAG, "Permission to record denied");

        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("Permission to access the SD-CARD is required for this app to Download PDF.")
                    .setTitle("Permission required");

            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int id) {
                    Log.i(TAG, "Clicked");
                    makeRequest();
                }
            });

            AlertDialog dialog = builder.create();
            dialog.show();

        } else {
            makeRequest();
        }
    }

    protected void makeRequest() {
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                REQUEST_WRITE_STORAGE);
    }

Step 3 Add override method for Request

 @Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case REQUEST_WRITE_STORAGE: {

            if (grantResults.length == 0
                    || grantResults[0] !=
                    PackageManager.PERMISSION_GRANTED) {

                Log.i(TAG, "Permission has been denied by user");

            } else {

                Log.i(TAG, "Permission has been granted by user");

            }
            return;
        }
    }
}

Note: Do not forget to add permission in menifest file

BEST EXAMPLE BELOW WITH MULTIPLE PERMISSION PLUS COVER ALL SCENARIO

I added comments so you can easily understand.

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.production.hometech.busycoder.R;

import java.util.ArrayList;

public class PermissionInActivity extends AppCompatActivity implements View.OnClickListener {

    private static final int REQUEST_PERMISSION_SETTING = 99;
    private Button bt_camera;
    private static final String[] PARAMS_TAKE_PHOTO = {
            Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    private static final int RESULT_PARAMS_TAKE_PHOTO = 11;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_permission_in);

        bt_camera = (Button) findViewById(R.id.bt_camera);

        bt_camera.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {

            case R.id.bt_camera:

                takePhoto();

                break;

        }
    }


    /**
     * shouldShowRequestPermissionRationale() = This will return true if the user had previously declined to grant you permission
     * NOTE :  that ActivityCompat also has a backwards-compatible implementation of
     * shouldShowRequestPermissionRationale(), so you can avoid your own API level
     * checks.
     * <p>
     * shouldShowRequestPermissionRationale() =  returns false if the user declined the permission and checked the checkbox to ask you to stop pestering the
     * user.
     * <p>
     * requestPermissions() = request for the permisssiion
     */
    private void takePhoto() {

        if (canTakePhoto()) {

            Toast.makeText(this, "You can take PHOTO", Toast.LENGTH_SHORT).show();

        } else if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

            Toast.makeText(this, "You should give permission", Toast.LENGTH_SHORT).show();
            ActivityCompat.requestPermissions(this, netPermisssion(PARAMS_TAKE_PHOTO), RESULT_PARAMS_TAKE_PHOTO);

        } else {
            ActivityCompat.requestPermissions(this, netPermisssion(PARAMS_TAKE_PHOTO), RESULT_PARAMS_TAKE_PHOTO);
        }

    }

    //  This method return  permission denied String[] so we can request again
    private String[] netPermisssion(String[] wantedPermissions) {
        ArrayList<String> result = new ArrayList<>();

        for (String permission : wantedPermissions) {
            if (!hasPermission(permission)) {
                result.add(permission);
            }
        }

        return (result.toArray(new String[result.size()]));

    }

    private boolean canTakePhoto() {
        return (hasPermission(Manifest.permission.CAMERA) && hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE));
    }

    /**
     * checkSelfPermission() = you can check if you have been granted a runtime permission or not
     * ex = ContextCompat.checkSelfPermission(this,permissionString)== PackageManager.PERMISSION_GRANTED
     * <p>
     * ContextCompat offers a backwards-compatible implementation of checkSelfPermission(), ActivityCompat offers a backwards-compatible
     * implementation of requestPermissions() that you can use.
     *
     * @param permissionString
     * @return
     */
    private boolean hasPermission(String permissionString) {
        return (ContextCompat.checkSelfPermission(this, permissionString) == PackageManager.PERMISSION_GRANTED);
    }

    /**
     * requestPermissions() action goes to onRequestPermissionsResult() whether user can GARNT or DENIED those permisssions
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == RESULT_PARAMS_TAKE_PHOTO) {

            if (canTakePhoto()) {

                Toast.makeText(this, "You can take picture", Toast.LENGTH_SHORT).show();

            } else if (!(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE))) {


                final AlertDialog.Builder settingDialog = new AlertDialog.Builder(PermissionInActivity.this);
                settingDialog.setTitle("Permissioin");
                settingDialog.setMessage("Now you need to enable permisssion from the setting because without permission this app won't run properly \n\n  goto -> setting -> appInfo");
                settingDialog.setCancelable(false);

                settingDialog.setPositiveButton("Setting", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                        dialogInterface.cancel();

                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        Uri uri = Uri.fromParts("package", getPackageName(), null);
                        intent.setData(uri);
                        startActivityForResult(intent, REQUEST_PERMISSION_SETTING);
                        Toast.makeText(getBaseContext(), "Go to Permissions to Grant all permission ENABLE", Toast.LENGTH_LONG).show();

                    }
                });
                settingDialog.show();

                Toast.makeText(this, "You need to grant permission from setting", Toast.LENGTH_SHORT).show();

            }

        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_PERMISSION_SETTING) {

            if (canTakePhoto()) {

                Toast.makeText(this, "You can take PHOTO", Toast.LENGTH_SHORT).show();

            }

        }

    }


}

Special Case for Configuration change

It is possible that the user will rotate the device or otherwise trigger a configuration change while our permission dialog is in the foreground. Since our activity is still visible behind that dialog, we get destroyed and recreated… but we do not want to re-raise the permission dialog again.

That is why we have a boolean, named isInPermission, that tracks whether or not we are in the middle of requesting permissions. We hold onto that value in onSaveInstanceState():

@Override
protected void onSaveInstanceState(Bundle outState) {
  super.onSaveInstanceState(outState);
  outState.putBoolean(STATE_IN_PERMISSION, isInPermission);
}

We restore it in onCreate(). If we do not hold all of the desired permissions, but isInPermission is true, we skip requesting the permissions, since we are in the middle of doing so already.

How to convert MySQL time to UNIX timestamp using PHP?

Slightly abbreviated could be...

echo date("Y-m-d H:i:s", strtotime($mysqltime));

C++ Passing Pointer to Function (Howto) + C++ Pointer Manipulation

There is a difference in the * usage when you are defining a variable and when you are using it.

In declaration,

int *myVariable;

Means a pointer to an integer data type. In usage however,

*myVariable = 3;

Means dereference the pointer and make the structure it is pointing at equal to three, rather then make the pointer equal to the memory address 0x 0003.

So in your function, you want to do this:

void makePointerEqualSomething(int* pInteger)
{
    *pInteger = 7;
}

In the function declaration, * means you are passing a pointer, but in its actual code body * means you are accessing what the pointer is pointing at.

In an attempt to wave away any confusion you have, I'll briefly go into the ampersand (&)

& means get the address of something, its exact location in the computers memory, so

 int & myVariable;

In a declaration means the address of an integer, or a pointer!

This however

int someData;    
pInteger = &someData;

Means make the pInteger pointer itself (remember, pointers are just memory addresses of what they point at) equal to the address of 'someData' - so now pInteger will point at some data, and can be used to access it when you deference it:

*pInteger += 9000;

Does this make sense to you? Is there anything else that you find confusing?

@Edit3:

Nearly correct, except for three statements

bar = *oof;

means that the bar pointer is equal to an integer, not what bar points at, which is invalid.

&bar = &oof;

The ampersand is like a function, once it returns a memory address you cannot modify where it came from. Just like this code:

returnThisInt("72") = 86; 

Is invalid, so is yours.

Finally,

bar = oof

Does not mean that "bar points to the oof pointer." Rather, this means that bar points to the address that oof points to, so bar points to whatever foo is pointing at - not bar points to foo which points to oof.

How to save a spark DataFrame as csv on disk?

Writing dataframe to disk as csv is similar read from csv. If you want your result as one file, you can use coalesce.

df.coalesce(1)
      .write
      .option("header","true")
      .option("sep",",")
      .mode("overwrite")
      .csv("output/path")

If your result is an array you should use language specific solution, not spark dataframe api. Because all these kind of results return driver machine.

When to use React "componentDidUpdate" method?

A simple example would be an app that collects input data from the user and then uses Ajax to upload said data to a database. Here's a simplified example (haven't run it - may have syntax errors):

export default class Task extends React.Component {
  
  constructor(props, context) {
    super(props, context);
    this.state = {
      name: "",
      age: "",
      country: ""
    };
  }

  componentDidUpdate() {
    this._commitAutoSave();
  }

  _changeName = (e) => {
    this.setState({name: e.target.value});
  }

  _changeAge = (e) => {
    this.setState({age: e.target.value});
  }

  _changeCountry = (e) => {
    this.setState({country: e.target.value});
  }

  _commitAutoSave = () => {
    Ajax.postJSON('/someAPI/json/autosave', {
      name: this.state.name,
      age: this.state.age,
      country: this.state.country
    });
  }

  render() {
    let {name, age, country} = this.state;
    return (
      <form>
        <input type="text" value={name} onChange={this._changeName} />
        <input type="text" value={age} onChange={this._changeAge} />
        <input type="text" value={country} onChange={this._changeCountry} />
      </form>
    );
  }
}

So whenever the component has a state change it will autosave the data. There are other ways to implement it too. The componentDidUpdate is particularly useful when an operation needs to happen after the DOM is updated and the update queue is emptied. It's probably most useful on complex renders and state or DOM changes or when you need something to be the absolutely last thing to be executed.

The example above is rather simple though, but probably proves the point. An improvement could be to limit the amount of times the autosave can execute (e.g max every 10 seconds) because right now it will run on every key-stroke.

I made a demo on this fiddle as well to demonstrate.


For more info, refer to the official docs:

componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.

Use this as an opportunity to operate on the DOM when the component has been updated. This is also a good place to do network requests as long as you compare the current props to previous props (e.g. a network request may not be necessary if the props have not changed).

How can I delete one element from an array by value

Borrowing from Travis in the comments, this is a better answer:

I personally like [1, 2, 7, 4, 5] - [7] which results in => [1, 2, 4, 5] from irb

I modified his answer seeing that 3 was the third element in his example array. This could lead to some confusion for those who don't realize that 3 is in position 2 in the array.

Where does git config --global get written to?

I think it is important to post this quote:

Git for Windows supports four levels of configuration. At the lowest level is the machine specific configuration settings known as "portable" and lives a "%ProgramData%\Git\config". One priority level us the installation specific configuration settings known as "system", which live at "\mingw64\etc\gitconfig". Both of these configuration file, generally require elevated privileges to modify.

Starting with the use specific values known as "global" configuration, which can be found at "%UserProfile%.gitconfig", we find the "user editable" configuration files. The highest priority configuration settings are in the "local" configuration, which can usually be found at ".git\config".

It see the recommendation in the blog linked is to modify the "system" or "installation" specific configuration settings, which is fine but users should expect that other installations of Git would not absorb said settings. If you want machine wide settings, use the "portable" configuration file, otherwise choose the "global" or "local" configuration files.

Hopefully, people find this information useful.

source

Can't ping a local VM from the host

I had a similar issue. You won't be able to ping the VM's from external devices if using NAT setting from within VMware's networking options. I switched to bridged connection so that the guest virtual machine will get it's own IP address and and then I added a second adapter set to NAT for the guest to get to the Internet.

for loop in Python

In Python you generally have for in loops instead of general for loops like C/C++, but you can achieve the same thing with the following code.

for k in range(1, c+1, 2):
  do something with k

Reference Loop in Python.

What's alternative to angular.copy in Angular

For shallow copying you could use Object.assign which is a ES6 feature

let x = { name: 'Marek', age: 20 };
let y = Object.assign({}, x);
x === y; //false

DO NOT use it for deep cloning

How to change legend title in ggplot

Many people spend a lot of time changing labels, legend labels, titles and the names of the axis because they don't know it is possible to load tables in R that contains spaces " ". You can however do this to save time or reduce the size of your code, by specifying the separators when you load a table that is for example delimited with tabs (or any other separator than default or a single space):

read.table(sep = '\t')

or by using the default loading parameters of the csv format:

read.csv()

This means you can directly keep the name "NEW LEGEND TITLE" as a column name (header) in your original data file to avoid specifying a new legend title in every plot.

How can I find non-ASCII characters in MySQL?

In Oracle we can use below.

SELECT * FROM TABLE_A WHERE ASCIISTR(COLUMN_A) <> COLUMN_A;

Resize Cross Domain Iframe Height

It is only possible to do this cross domain if you have access to implement JS on both domains. If you have that, then here is a little library that solves all the problems with sizing iFrames to their contained content.

https://github.com/davidjbradshaw/iframe-resizer

It deals with the cross domain issue by using the post-message API, and also detects changes to the content of the iFrame in a few different ways.

Works in all modern browsers and IE8 upwards.

Import local function from a module housed in another directory with relative imports in Jupyter Notebook using Python 3

I have found that python-dotenv helps solve this issue pretty effectively. Your project structure ends up changing slightly, but the code in your notebook is a bit simpler and consistent across notebooks.

For your project, do a little install.

pipenv install python-dotenv

Then, project changes to:

+-- .env (this can be empty)
+-- ipynb
¦   +-- 20170609-Examine_Database_Requirements.ipynb
¦   +-- 20170609-Initial_Database_Connection.ipynb
+-- lib
    +-- __init__.py
    +-- postgres.py

And finally, your import changes to:

import os
import sys

from dotenv import find_dotenv


sys.path.append(os.path.dirname(find_dotenv()))

A +1 for this package is that your notebooks can be several directories deep. python-dotenv will find the closest one in a parent directory and use it. A +2 for this approach is that jupyter will load environment variables from the .env file on startup. Double whammy.

Writing an Excel file in EPPlus

It's best if you worked with DataSets and/or DataTables. Once you have that, ideally straight from your stored procedure with proper column names for headers, you can use the following method:

ws.Cells.LoadFromDataTable(<DATATABLE HERE>, true, OfficeOpenXml.Table.TableStyles.Light8);

.. which will produce a beautiful excelsheet with a nice table!

Now to serve your file, assuming you have an ExcelPackage object as in your code above called pck..

Response.Clear();

Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", "attachment;filename=" + sFilename);

Response.BinaryWrite(pck.GetAsByteArray());
Response.End();

Permission denied (publickey). fatal: The remote end hung up unexpectedly while pushing back to git repository

Googled "Permission denied (publickey). fatal: The remote end hung up unexpectedly", first result an exact SO dupe:

GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly which links here in the accepted answer (from the original poster, no less): http://help.github.com/linux-set-up-git/

The type must be a reference type in order to use it as parameter 'T' in the generic type or method

If you put constrains on a generic class or method, every other generic class or method that is using it need to have "at least" those constrains.

Java JTextField with input hint

Here is a simple way that looks good in any L&F:

public class HintTextField extends JTextField {
    public HintTextField(String hint) {
        _hint = hint;
    }
    @Override
    public void paint(Graphics g) {
        super.paint(g);
        if (getText().length() == 0) {
            int h = getHeight();
            ((Graphics2D)g).setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            Insets ins = getInsets();
            FontMetrics fm = g.getFontMetrics();
            int c0 = getBackground().getRGB();
            int c1 = getForeground().getRGB();
            int m = 0xfefefefe;
            int c2 = ((c0 & m) >>> 1) + ((c1 & m) >>> 1);
            g.setColor(new Color(c2, true));
            g.drawString(_hint, ins.left, h / 2 + fm.getAscent() / 2 - 2);
        }
    }
    private final String _hint;
}

How can I handle the warning of file_get_contents() function in PHP?

You can prepend an @: $content = @file_get_contents($site);

This will supress any warning - use sparingly!. See Error Control Operators

Edit: When you remove the 'http://' you're no longer looking for a web page, but a file on your disk called "www.google....."

Tomcat started in Eclipse but unable to connect to http://localhost:8085/

Eclipse hooks Dynamic Web projects into tomcat and maintains it's own configuration but does not deploy the standard tomcat ROOT.war. As http://localhost:8085/ link returns 404 does indeed show that tomcat is up and running, just can't find a web app deployed to root.

By default, any deployed dynamic web projects use their project name as context root, so you should see http://localhost:8085/yourprojectname working properly, but check the Servers tab first to ensure that your web project has actually been deployed.

Hope that helps.

Asp Net Web API 2.1 get client IP address

With Web API 2.2: Request.GetOwinContext().Request.RemoteIpAddress

javascript : sending custom parameters with window.open() but its not working

if you want to pass POST variables, you have to use a HTML Form:

<form action="http://localhost:8080/login" method="POST" target="_blank">
    <input type="text" name="cid" />
    <input type="password" name="pwd" />
    <input type="submit" value="open" />
</form>

or:

if you want to pass GET variables in an URL, write them without single-quotes:

http://yourdomain.com/login?cid=username&pwd=password

here's how to create the string above with javascrpt variables:

myu = document.getElementById('cid').value;
myp = document.getElementById('pwd').value;
window.open("http://localhost:8080/login?cid="+ myu +"&pwd="+ myp ,"MyTargetWindowName");

in the document with that url, you have to read the GET parameters. if it's in php, use:

$_GET['username']

be aware: to transmit passwords that way is a big security leak!

Command not found error in Bash variable assignment

Drop the spaces around the = sign:

#!/bin/bash 
STR="Hello World" 
echo $STR 

How to get certain commit from GitHub project

If you want to go with any certain commit or want to code of any certain commit then you can use below command:

git checkout <BRANCH_NAME>
git reset --hard  <commit ID which code you want>
git push --force

Example:

 git reset --hard fbee9dd 
 git push --force

Unable to Build using MAVEN with ERROR - Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile

I had the same issue. When compared the java version mentioned in the pom.xml file is different and the JAVA_HOME env variable was pointing to different version of jdk.

Have the JAVA_HOME and pom.xml updated to the same jdk installation path

What are some reasons for jquery .focus() not working?

This solved!!!

setTimeout(function(){
    $("#name").filter(':visible').focus();
}, 500);

You can adjust time accordingly.

jQuery duplicate DIV into another DIV

_x000D_
_x000D_
$(document).ready(function(){  _x000D_
    $("#btn_clone").click(function(){  _x000D_
        $("#a_clone").clone().appendTo("#b_clone");  _x000D_
    });  _x000D_
});  
_x000D_
.container{_x000D_
    padding: 15px;_x000D_
    border: 12px solid #23384E;_x000D_
    background: #28BAA2;_x000D_
    margin-top: 10px;_x000D_
}
_x000D_
<!DOCTYPE html>  _x000D_
<html>  _x000D_
<head>  _x000D_
<title>jQuery Clone Method</title> _x000D_
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> _x000D_
_x000D_
_x000D_
</head>  _x000D_
<body> _x000D_
<div class="container">_x000D_
<p id="a_clone"><b> This is simple example of clone method.</b></p>  _x000D_
<p id="b_clone"><b>Note:</b>Click The Below button Click Me</p>  _x000D_
<button id="btn_clone">Click Me!</button>  _x000D_
</div> _x000D_
</body>  _x000D_
</html>  
_x000D_
_x000D_
_x000D_

For more detail and demo

How to set OnClickListener on a RadioButton in Android?

For Kotlin Here is added the lambda expression and Optimized the Code.

   radioGroup.setOnCheckedChangeListener { radioGroup, optionId ->
        run {
            when (optionId) {
                R.id.radioButton1 -> {
                    // do something when radio button 1 is selected
                }
                R.id.radioButton2 -> {
                    // do something when radio button 2 is selected
                }
                // add more cases here to handle other buttons in the your RadioGroup
            }
        }
    }

Hope this will help you. Thanks!

how to disable DIV element and everything inside

The following css statement disables click events

pointer-events:none;

Sort an array in Java

Here is how to use this in your program:

public static void main(String args[])
{
    int [] array = new int[10];

    array[0] = ((int)(Math.random()*100+1));
    array[1] = ((int)(Math.random()*100+1));
    array[2] = ((int)(Math.random()*100+1));
    array[3] = ((int)(Math.random()*100+1));
    array[4] = ((int)(Math.random()*100+1));
    array[5] = ((int)(Math.random()*100+1));
    array[6] = ((int)(Math.random()*100+1));
    array[7] = ((int)(Math.random()*100+1));
    array[8] = ((int)(Math.random()*100+1));
    array[9] = ((int)(Math.random()*100+1));

    Arrays.sort(array); 

    System.out.println(array[0] +" " + array[1] +" " + array[2] +" " + array[3]
    +" " + array[4] +" " + array[5]+" " + array[6]+" " + array[7]+" " 
    + array[8]+" " + array[9] );        

}

Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed

This worked for me too, but with an addition (below).

protected void Page_Load(object sender, EventArgs e) {
  ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
  scriptManager.RegisterPostBackControl(this.btnExcelExport);
  //Further code goes here....
}

I was registering a script on my button to click on another button after its event was finished processing. In order for it to work, I had to remove the other button from the Update Panel (just in case somebody faces the same problem).

Given a class, see if instance has method (Ruby)

If you're checking to see if an object can respond to a series of methods, you could do something like:

methods = [:valid?, :chase, :test]

def has_methods?(something, methods)
  methods & something.methods == methods
end

the methods & something.methods will join the two arrays on their common/matching elements. something.methods includes all of the methods you're checking for, it'll equal methods. For example:

[1,2] & [1,2,3,4,5]
==> [1,2]

so

[1,2] & [1,2,3,4,5] == [1,2]
==> true

In this situation, you'd want to use symbols, because when you call .methods, it returns an array of symbols and if you used ["my", "methods"], it'd return false.

Change CSS properties on click

    <script>
        function change_css(){
            document.getElementById('result').style.cssText = 'padding:20px; background-color:#b2b2ff; color:#0c0800; border:1px solid #0c0800; font-size:22px;';
        }
    </script>

</head>

<body>
    <center>
        <div id="error"></div>
        <center>
            <div id="result"><h2> Javascript Example On click Change Css style</h2></div>
            <button onclick="change_css();">Check</button><br />
        </center>
    </center>
</body>

Do you recommend using semicolons after every statement in JavaScript?

An ambiguous case that breaks in the absence of a semicolon:

// define a function
var fn = function () {
    //...
} // semicolon missing at this line

// then execute some code inside a closure
(function () {
    //...
})();

This will be interpreted as:

var fn = function () {
    //...
}(function () {
    //...
})();

We end up passing the second function as an argument to the first function and then trying to call the result of the first function call as a function. The second function will fail with a "... is not a function" error at runtime.

How do I start/stop IIS Express Server?

You can stop any IIS Express application or you can stop all application. Right click on IIS express icon , which is located at right bottom corner of task bar. Then Select Show All Application

enter image description here

How to show code but hide output in RMarkdown?

As @ J_F answered in the comments, using {r echo = T, results = 'hide'}.

I wanted to expand on their answer - there are great resources you can access to determine all possible options for your chunk and output display - I keep a printed copy at my desk!

You can find them either on the RStudio Website under Cheatsheets (look for the R Markdown cheatsheet and R Markdown Reference Guide) or, in RStudio, navigate to the "Help" tab, choose "Cheatsheets", and look for the same documents there.

Finally to set default chunk options, you can run (in your first chunk) something like the following code if you want most chunks to have the same behavior:

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = T,
                      results = "hide")
```

Later, you can modify the behavior of individual chunks like this, which will replace the default value for just the results option.

```{r analysis, results="markup"}
# code here
```

Convert array into csv

The accepted answer from Paul is great. I've made a small extension to this which is very useful if you have an multidimensional array like this (which is quite common):

Array
(
    [0] => Array
        (
            [a] => "a"
            [b] => "b"
        )

    [1] => Array
        (
            [a] => "a2"
            [b] => "b2"
        )

    [2] => Array
        (
            [a] => "a3"
            [b] => "b3"
        )

    [3] => Array
        (
            [a] => "a4"
            [b] => "b4"
        )

    [4] => Array
        (
            [a] => "a5"
            [b] => "b5"
        )

)

So I just took Paul's function from above:

/**
  * Formats a line (passed as a fields  array) as CSV and returns the CSV as a string.
  * Adapted from http://us3.php.net/manual/en/function.fputcsv.php#87120
  */
function arrayToCsv( array &$fields, $delimiter = ';', $enclosure = '"', $encloseAll = false, $nullToMysqlNull = false ) {
    $delimiter_esc = preg_quote($delimiter, '/');
    $enclosure_esc = preg_quote($enclosure, '/');

    $output = array();
    foreach ( $fields as $field ) {
        if ($field === null && $nullToMysqlNull) {
            $output[] = 'NULL';
            continue;
        }

        // Enclose fields containing $delimiter, $enclosure or whitespace
        if ( $encloseAll || preg_match( "/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field ) ) {
            $output[] = $enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure;
        }
        else {
            $output[] = $field;
        }
    }

    return implode( $delimiter, $output );
}

And added this:

function a2c($array, $glue = "\n")
{
    $ret = [];
    foreach ($array as $item) {
        $ret[] = arrayToCsv($item);
    }
    return implode($glue, $ret);
}

So you can just call:

$csv = a2c($array);

If you want a special line ending you can use the optional parameter "glue" for this.

Find maximum value of a column and return the corresponding row values using Pandas

The country and place is the index of the series, if you don't need the index, you can set as_index=False:

df.groupby(['country','place'], as_index=False)['value'].max()

Edit:

It seems that you want the place with max value for every country, following code will do what you want:

df.groupby("country").apply(lambda df:df.irow(df.value.argmax()))

Visual Studio Code - Target of URI doesn't exist 'package:flutter/material.dart'

Basically

  1. Check for correct indentation of your package in dependencies
  2. if your editor supports, it automatically runs -> flutter pub get
  3. Either way -> open terminal-> flutter pub get or flutter packages get
  4. check .packages file, see if your package is present else reinstall package
  5. Most important : Restart your IDE (Visual studio or Android Studio)

Start debugging your project

Most probably , your errors will be fixed by then

Hope it works for you

Error including image in Latex

I had the same problem, caused by a clash between the graphicx package and an inclusion of the epsfig package that survived the ages...

Please check that there is no inclusion of epsfig, it is deprecated.

How can I create keystore from an existing certificate (abc.crt) and abc.key files?

You must use OpenSSL and keytool.

OpenSSL for CER & PVK file > P12

openssl pkcs12 -export -name servercert -in selfsignedcert.crt -inkey serverprivatekey.key -out myp12keystore.p12

Keytool for p12 > JKS

keytool -importkeystore -destkeystore mykeystore.jks -srckeystore myp12keystore.p12 -srcstoretype pkcs12 -alias servercert

Using variables inside a bash heredoc

As a late corolloary to the earlier answers here, you probably end up in situations where you want some but not all variables to be interpolated. You can solve that by using backslashes to escape dollar signs and backticks; or you can put the static text in a variable.

Name='Rich Ba$tard'
dough='$$$dollars$$$'
cat <<____HERE
$Name, you can win a lot of $dough this week!
Notice that \`backticks' need escaping if you want
literal text, not `pwd`, just like in variables like
\$HOME (current value: $HOME)
____HERE

Demo: https://ideone.com/rMF2XA

Note that any of the quoting mechanisms -- \____HERE or "____HERE" or '____HERE' -- will disable all variable interpolation, and turn the here-document into a piece of literal text.

A common task is to combine local variables with script which should be evaluated by a different shell, programming language, or remote host.

local=$(uname)
ssh -t remote <<:
    echo "$local is the value from the host which ran the ssh command"
    # Prevent here doc from expanding locally; remote won't see backslash
    remote=\$(uname)
    # Same here
    echo "\$remote is the value from the host we ssh:ed to"
:

How to find the Target *.exe file of *.appref-ms

ClickOnce applications are stored under the user's profile at %LocalAppData%\Apps\2.0\.

From there, use the search function to find your application.

List all sequences in a Postgres db 8.1 with SQL

I know this post is pretty old, but I found the solution by CMS to be very useful as I was looking for an automated way to link a sequence to the table AND column, and wanted to share. The use of pg_depend catalog table was the key. I expanded what was done to:

WITH fq_objects AS (SELECT c.oid,n.nspname || '.' ||c.relname AS fqname ,
                           c.relkind, c.relname AS relation
                    FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace ),

     sequences AS (SELECT oid,fqname FROM fq_objects WHERE relkind = 'S'),
     tables    AS (SELECT oid, fqname FROM fq_objects WHERE relkind = 'r' )
SELECT
       s.fqname AS sequence,
       '->' as depends,
       t.fqname AS table,
       a.attname AS column
FROM
     pg_depend d JOIN sequences s ON s.oid = d.objid
                 JOIN tables t ON t.oid = d.refobjid
                 JOIN pg_attribute a ON a.attrelid = d.refobjid and a.attnum = d.refobjsubid
WHERE
     d.deptype = 'a' ;

This version adds column to the list of fields returned. With both the table name and the column name in hand, a call to pg_set_serial_sequence makes it easy to ensure that all sequences in the database are set correctly. For example:

CREATE OR REPLACE FUNCTION public.reset_sequence(tablename text, columnname text)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
    _sql VARCHAR := '';
BEGIN
    _sql := $$SELECT setval( pg_get_serial_sequence('$$ || tablename || $$', '$$ || columnname || $$'), (SELECT COALESCE(MAX($$ || columnname || $$),1) FROM $$ || tablename || $$), true)$$;
    EXECUTE _sql;
END;
$function$;

Hope this helps someone with resetting sequences!

ng-repeat :filter by single field

Search by color:

<input type="text" ng-model="searchinput">
<div ng-repeat="product in products | filter:{color:searchinput}">

you can do an inner nest too.

filter:{prop1:{innerprop1:searchinput}}

Pseudo-terminal will not be allocated because stdin is not a terminal

The warning message Pseudo-terminal will not be allocated because stdin is not a terminal. is due to the fact that no command is specified for ssh while stdin is redirected from a here document. Due to the lack of a specified command as an argument ssh first expects an interactive login session (which would require the allocation of a pty on the remote host) but then has to realize that its local stdin is no tty/pty. Redirecting ssh's stdin from a here document normally requires a command (such as /bin/sh) to be specified as an argument to ssh - and in such a case no pty will be allocated on the remote host by default.

Since there are no commands to be executed via ssh that require the presence of a tty/pty (such as vim or top) the -t switch to ssh is superfluous. Just use ssh -T user@server <<EOT ... or ssh user@server /bin/bash <<EOT ... and the warning will go away.

If <<EOF is not escaped or single-quoted (i. e. <<\EOT or <<'EOT') variables inside the here document will be expanded by the local shell before it is executing ssh .... The effect is that the variables inside the here document will remain empty because they are defined only in the remote shell.

So, if $REL_DIR should be both accessible by the local shell and defined in the remote shell, $REL_DIR has to be defined outside the here document before the ssh command (version 1 below); or, if <<\EOT or <<'EOT' is used, the output of the ssh command can be assigned to REL_DIR if the only output of the ssh command to stdout is genererated by echo "$REL_DIR" inside the escaped/single-quoted here document (version 2 below).

A third option would be to store the here document in a variable and then pass this variable as a command argument to ssh -t user@server "$heredoc" (version 3 below).

And, last but not least, it would be no bad idea to check if the directories on the remote host were created successfully (see: check if file exists on remote host with ssh).

# version 1

unset DEP_ROOT REL_DIR
DEP_ROOT='/tmp'
datestamp=$(date +%Y%m%d%H%M%S)
REL_DIR="${DEP_ROOT}/${datestamp}"

ssh localhost /bin/bash <<EOF
if [ ! -d "$DEP_ROOT" ] && [ ! -e "$DEP_ROOT" ]; then
   echo "creating the root directory" 1>&2
   mkdir "$DEP_ROOT"
fi
mkdir "$REL_DIR"
#echo "$REL_DIR"
exit
EOF

scp -r ./dir1 user@server:"$REL_DIR"
scp -r ./dir2 user@server:"$REL_DIR"


# version 2

REL_DIR="$(
ssh localhost /bin/bash <<\EOF
DEP_ROOT='/tmp'
datestamp=$(date +%Y%m%d%H%M%S)
REL_DIR="${DEP_ROOT}/${datestamp}"
if [ ! -d "$DEP_ROOT" ] && [ ! -e "$DEP_ROOT" ]; then
   echo "creating the root directory" 1>&2
   mkdir "$DEP_ROOT"
fi
mkdir "$REL_DIR"
echo "$REL_DIR"
exit
EOF
)"

scp -r ./dir1 user@server:"$REL_DIR"
scp -r ./dir2 user@server:"$REL_DIR"


# version 3

heredoc="$(cat <<'EOF'
# -onlcr: prevent the terminal from converting bare line feeds to carriage return/line feed pairs
stty -echo -onlcr
DEP_ROOT='/tmp'
datestamp="$(date +%Y%m%d%H%M%S)"
REL_DIR="${DEP_ROOT}/${datestamp}"
if [ ! -d "$DEP_ROOT" ] && [ ! -e "$DEP_ROOT" ]; then
   echo "creating the root directory" 1>&2
   mkdir "$DEP_ROOT"
fi
mkdir "$REL_DIR"
echo "$REL_DIR"
stty echo onlcr
exit
EOF
)"

REL_DIR="$(ssh -t localhost "$heredoc")"

scp -r ./dir1 user@server:"$REL_DIR"
scp -r ./dir2 user@server:"$REL_DIR"

Split files using tar, gz, zip, or bzip2

If you are splitting from Linux, you can still reassemble in Windows.

copy /b file1 + file2 + file3 + file4 filetogether

Best way to handle multiple constructors in Java

You need to specify what are the class invariants, i.e. properties which will always be true for an instance of the class (for example, the title of a book will never be null, or the size of a dog will always be > 0).

These invariants should be established during construction, and be preserved along the lifetime of the object, which means that methods shall not break the invariants. The constructors can set these invariants either by having compulsory arguments, or by setting default values:

class Book {
    private String title; // not nullable
    private String isbn;  // nullable

    // Here we provide a default value, but we could also skip the 
    // parameterless constructor entirely, to force users of the class to
    // provide a title
    public Book()
    {
        this("Untitled"); 
    }

    public Book(String title) throws IllegalArgumentException
    {
        if (title == null) 
            throw new IllegalArgumentException("Book title can't be null");
        this.title = title;
        // leave isbn without value
    }
    // Constructor with title and isbn
}

However, the choice of these invariants highly depends on the class you're writing, how you'll use it, etc., so there's no definitive answer to your question.

How can I create a progress bar in Excel VBA?

There have been many other great posts, however I'd like to say that theoretically you should be able to create a REAL progress bar control:

  1. Use CreateWindowEx() to create the progress bar

A C++ example:

hwndPB = CreateWindowEx(0, PROGRESS_CLASS, (LPTSTR) NULL, WS_CHILD | WS_VISIBLE, rcClient.left,rcClient.bottom - cyVScroll,rcClient.right, cyVScroll,hwndParent, (HMENU) 0, g_hinst, NULL);

hwndParent Should be set to the parent window. For that one could use the status bar, or a custom form! Here's the window structure of Excel found from Spy++:

enter image description here

This should therefore be relatively simple using FindWindowEx() function.

hwndParent = FindWindowEx(Application.hwnd,,"MsoCommandBar","Status Bar")

After the progress bar has been created you must use SendMessage() to interact with the progress bar:

Function MAKELPARAM(ByVal loWord As Integer, ByVal hiWord As Integer)
    Dim lparam As Long
    MAKELPARAM = loWord Or (&H10000 * hiWord)
End Function

SendMessage(hwndPB, PBM_SETRANGE, 0, MAKELPARAM(0, 100))
SendMessage(hwndPB, PBM_SETSTEP, 1, 0)
For i = 1 to 100
    SendMessage(hwndPB, PBM_STEPIT, 0, 0) 
Next
DestroyWindow(hwndPB)

I'm not sure how practical this solution is, but it might look somewhat more 'official' than other methods stated here.

SSL handshake fails with - a verisign chain certificate - that contains two CA signed certificates and one self-signed certificate

It sounds like the intermediate certificate is missing. As of April 2006, all SSL certificates issued by VeriSign require the installation of an Intermediate CA Certificate.

It could be that you don't have the entire certificate chain loaded on your server. Some businesses do not allow their computers to download additional certificates, causing a failure to complete an SSL handshake.

Here is some information on intermediate chains:
https://knowledge.verisign.com/support/ssl-certificates-support/index?page=content&id=AR657
https://knowledge.verisign.com/support/ssl-certificates-support/index?page=content&id=AD146

Intermediate CA Certificates

Change private static final field using Java reflection

In case of presence of a Security Manager, one can make use of AccessController.doPrivileged

Taking the same example from accepted answer above:

import java.lang.reflect.*;

public class EverythingIsTrue {
    static void setFinalStatic(Field field, Object newValue) throws Exception {
        field.setAccessible(true);
        Field modifiersField = Field.class.getDeclaredField("modifiers");

        // wrapping setAccessible 
        AccessController.doPrivileged(new PrivilegedAction() {
            @Override
            public Object run() {
                modifiersField.setAccessible(true);
                return null;
            }
        });

        modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
        field.set(null, newValue);
    }

    public static void main(String args[]) throws Exception {      
      setFinalStatic(Boolean.class.getField("FALSE"), true);
      System.out.format("Everything is %s", false); // "Everything is true"
    }
}

In lambda expression, AccessController.doPrivileged, can be simplified to:

AccessController.doPrivileged((PrivilegedAction) () -> {
    modifiersField.setAccessible(true);
    return null;
});

Java Class.cast() vs. cast operator

It's always problematic and often misleading to try and translate constructs and concepts between languages. Casting is no exception. Particularly because Java is a dynamic language and C++ is somewhat different.

All casting in Java, no matter how you do it, is done at runtime. Type information is held at runtime. C++ is a bit more of a mix. You can cast a struct in C++ to another and it's merely a reinterpretation of the bytes that represent those structs. Java doesn't work that way.

Also generics in Java and C++ are vastly different. Don't concern yourself overly with how you do C++ things in Java. You need to learn how to do things the Java way.

PostgreSQL: Which version of PostgreSQL am I running?

If Select version() returns with Memo try using the command this way:

Select version::char(100) 

or

Select version::varchar(100)

Using the grep and cut delimiter command (in bash shell scripting UNIX) - and kind of "reversing" it?

You don't need to change the delimiter to display the right part of the string with cut.

The -f switch of the cut command is the n-TH element separated by your delimiter : :, so you can just type :

 grep puddle2_1557936 | cut -d ":" -f2

Another solutions (adapt it a bit) if you want fun :

Using :

grep -oP 'puddle2_1557936:\K.*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                        
/home/rogers.williams/folderz/puddle2

or still with look around

grep -oP '(?<=puddle2_1557936:).*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                    
/home/rogers.williams/folderz/puddle2

or with :

perl -lne '/puddle2_1557936:(.*)/ and print $1' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                      
/home/rogers.williams/folderz/puddle2

or using (thanks to glenn jackman)

ruby -F: -ane '/puddle2_1557936/ and puts $F[1]' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

awk -F'puddle2_1557936:' '{print $2}'  <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

python -c 'import sys; print(sys.argv[1].split("puddle2_1557936:")[1])' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or using only :

IFS=: read _ a <<< "puddle2_1557936:/home/rogers.williams/folderz/puddle2"
echo "$a"
/home/rogers.williams/folderz/puddle2

or using in a :

js<<EOF
var x = 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
print(x.substr(x.indexOf(":")+1))
EOF
/home/rogers.williams/folderz/puddle2

or using in a :

php -r 'preg_match("/puddle2_1557936:(.*)/", $argv[1], $m); echo "$m[1]\n";' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2' 
/home/rogers.williams/folderz/puddle2

Wrapping text inside input type="text" element HTML/CSS

That is the textarea's job - for multiline text input. The input won't do it; it wasn't designed to do it.

So use a textarea. Besides their visual differences, they are accessed via JavaScript the same way (use value property).

You can prevent newlines being entered via the input event and simply using a replace(/\n/g, '').

How do I convert from int to Long in Java?

 //Suppose you have int and you wan to convert it to Long
 int i=78;
 //convert to Long
 Long l=Long.valueOf(i)

Laravel Eloquent "WHERE NOT IN"

The dynamic way of implement whereNotIn:

 $users = User::where('status',0)->get();
    foreach ($users as $user) {
                $data[] = $user->id;
            }
    $available = User::orderBy('name', 'DEC')->whereNotIn('id', $data)->get();

Debug assertion failed. C++ vector subscript out of range

v has 10 element, the index starts from 0 to 9.

for(int j=10;j>0;--j)
{
    cout<<v[j];   // v[10] out of range
}

you should update for loop to

for(int j=9; j>=0; --j)
//      ^^^^^^^^^^
{
    cout<<v[j];   // out of range
}

Or use reverse iterator to print element in reverse order

for (auto ri = v.rbegin(); ri != v.rend(); ++ri)
{
  std::cout << *ri << std::endl;
}

Using an array as needles in strpos

You can also try using strpbrk() for the negation (none of the letters have been found):

$find_letters = array('a', 'c', 'd');
$string = 'abcdefg';

if(strpbrk($string, implode($find_letters)) === false)
{
    echo 'None of these letters are found in the string!';
}

"date(): It is not safe to rely on the system's timezone settings..."

In addition to setting the date.timezone= as mentioned in several answers, I found an error in the php.ini file that was keeping it from getting to the date.timezone. The way I found it was by running php from the command line in a terminal. this caused an error to be reported at line 114. In my case I had uncommented a setting for displaying errors that had '|' between 2 values. It did not like it. I removed one of the values and the | and everything was good after that

What's the difference between process.cwd() vs __dirname?

$ find proj

proj
proj/src
proj/src/index.js

$ cat proj/src/index.js

console.log("process.cwd() = " + process.cwd());
console.log("__dirname = " + __dirname);

$ cd proj; node src/index.js

process.cwd() = /tmp/proj
__dirname = /tmp/proj/src

How to find the nearest parent of a Git branch?

Remember that, as described in "Git: Finding what branch a commit came from", you cannot easily pinpoint the branch where that commit has been made (branches can be renamed, moved, deleted...), even though git branch --contains <commit> is a start.

  • You can go back from commit to commit until git branch --contains <commit> doesn't list the feature branch and list develop branch,
  • compare that commit SHA1 to /refs/heads/develop

If the two commits id match, you are good to go (that would mean the feature branch has its origin at the HEAD of develop).

error: Your local changes to the following files would be overwritten by checkout

i had got the same error. Actually i tried to override the flutter Old SDK Package with new Updated Package. so that error occurred.

i opened flutter sdk directory with VS Code and cleaned the project

use this code in VSCode cmd

git clean -dxf

then use git pull

Lost connection to MySQL server during query?

very simple to solve, go to the control panel of you phpadmin and click on config/then edit the .ini file you see. look for port 3306 if that's not the port you are using for your connection change 3306 to the port you are using. on your login screen just put localhost for your server, your port if its not the default or if you did not change the file name my.ini in sql configuration leavit as is. then put your username:root or the one you created then the password:1234 or the one you assigned. if you are connecting localy, do not check the url option. then type the name of the database you want to edit. note: once you are connected you will see the list of databases you have on your server or the server you are connecting to.

How does one use glide to download an image into a bitmap?

It looks like overriding the Target class or one of the implementations like BitmapImageViewTarget and overriding the setResource method to capture the bitmap might be the way to go...

This is untested. :-)

    Glide.with(context)
         .load("http://goo.gl/h8qOq7")
         .asBitmap()
         .into(new BitmapImageViewTarget(imageView) {
                     @Override
                     protected void setResource(Bitmap resource) {
                         // Do bitmap magic here
                         super.setResource(resource);
                     }
         });

'Malformed UTF-8 characters, possibly incorrectly encoded' in Laravel

I got this error and i fixed the issue with iconv function like following:

iconv('latin5', 'utf-8', $data['index']);

git rm - fatal: pathspec did not match any files

This chains work in my case:

  1. git rm -r WebApplication/packages

There was a confirmation git-dialog. You should choose "y" option.

  1. git commit -m "blabla"
  2. git push -f origin <ur_branch>

how to set select element as readonly ('disabled' doesnt pass select value on server)

without disabling the selected value on submitting..

$('#selectID option:not(:selected)').prop('disabled', true);

If you use Jquery version lesser than 1.7
$('#selectID option:not(:selected)').attr('disabled', true);

It works for me..

Why do I get "a label can only be part of a statement and a declaration is not a statement" if I have a variable that is initialized after a label?

This is a quirk of the C grammar. A label (Cleanup:) is not allowed to appear immediately before a declaration (such as char *str ...;), only before a statement (printf(...);). In C89 this was no great difficulty because declarations could only appear at the very beginning of a block, so you could always move the label down a bit and avoid the issue. In C99 you can mix declarations and code, but you still can't put a label immediately before a declaration.

You can put a semicolon immediately after the label's colon (as suggested by Renan) to make there be an empty statement there; this is what I would do in machine-generated code. Alternatively, hoist the declaration to the top of the function:

int main (void) 
{
    char *str;
    printf("Hello ");
    goto Cleanup;
Cleanup:
    str = "World\n";
    printf("%s\n", str);
    return 0;
}

Add a space (" ") after an element using :after

Explanation

It's worth noting that your code does insert a space

h2::after {
  content: " ";
}

However, it's immediately removed.

From Anonymous inline boxes,

White space content that would subsequently be collapsed away according to the 'white-space' property does not generate any anonymous inline boxes.

And from The 'white-space' processing model,

If a space (U+0020) at the end of a line has 'white-space' set to 'normal', 'nowrap', or 'pre-line', it is also removed.

Solution

So if you don't want the space to be removed, set white-space to pre or pre-wrap.

_x000D_
_x000D_
h2 {_x000D_
  text-decoration: underline;_x000D_
}_x000D_
h2.space::after {_x000D_
  content: " ";_x000D_
  white-space: pre;_x000D_
}
_x000D_
<h2>I don't have space:</h2>_x000D_
<h2 class="space">I have space:</h2>
_x000D_
_x000D_
_x000D_

Do not use non-breaking spaces (U+00a0). They are supposed to prevent line breaks between words. They are not supposed to be used as non-collapsible space, that wouldn't be semantic.

Running shell command and capturing the output

You can use following commands to run any shell command. I have used them on ubuntu.

import os
os.popen('your command here').read()

Note: This is deprecated since python 2.6. Now you must use subprocess.Popen. Below is the example

import subprocess

p = subprocess.Popen("Your command", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0]
print p.split("\n")

Render HTML to PDF in Django site

Try wkhtmltopdf with either one of the following wrappers

django-wkhtmltopdf or python-pdfkit

This worked great for me,supports javascript and css or anything for that matter which a webkit browser supports.

For more detailed tutorial please see this blog post

How do I make a https post in Node Js without any third party module?

For example, like this:

const querystring = require('querystring');
const https = require('https');

var postData = querystring.stringify({
    'msg' : 'Hello World!'
});

var options = {
  hostname: 'posttestserver.com',
  port: 443,
  path: '/post.php',
  method: 'POST',
  headers: {
       'Content-Type': 'application/x-www-form-urlencoded',
       'Content-Length': postData.length
     }
};

var req = https.request(options, (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (d) => {
    process.stdout.write(d);
  });
});

req.on('error', (e) => {
  console.error(e);
});

req.write(postData);
req.end();