Programs & Examples On #Claims

pod has unbound PersistentVolumeClaims

You have to define a PersistentVolume providing disc space to be consumed by the PersistentVolumeClaim.

When using storageClass Kubernetes is going to enable "Dynamic Volume Provisioning" which is not working with the local file system.


To solve your issue:

  • Provide a PersistentVolume fulfilling the constraints of the claim (a size >= 100Mi)
  • Remove the storageClass-line from the PersistentVolumeClaim
  • Remove the StorageClass from your cluster

How do these pieces play together?

At creation of the deployment state-description it is usually known which kind (amount, speed, ...) of storage that application will need.
To make a deployment versatile you'd like to avoid a hard dependency on storage. Kubernetes' volume-abstraction allows you to provide and consume storage in a standardized way.

The PersistentVolumeClaim is used to provide a storage-constraint alongside the deployment of an application.

The PersistentVolume offers cluster-wide volume-instances ready to be consumed ("bound"). One PersistentVolume will be bound to one claim. But since multiple instances of that claim may be run on multiple nodes, that volume may be accessed by multiple nodes.

A PersistentVolume without StorageClass is considered to be static.

"Dynamic Volume Provisioning" alongside with a StorageClass allows the cluster to provision PersistentVolumes on demand. In order to make that work, the given storage provider must support provisioning - this allows the cluster to request the provisioning of a "new" PersistentVolume when an unsatisfied PersistentVolumeClaim pops up.


Example PersistentVolume

In order to find how to specify things you're best advised to take a look at the API for your Kubernetes version, so the following example is build from the API-Reference of K8S 1.17:

apiVersion: v1
kind: PersistentVolume
metadata:
  name: ckan-pv-home
  labels:
    type: local
spec:
  capacity:
    storage: 100Mi
  hostPath:
    path: "/mnt/data/ckan"

The PersistentVolumeSpec allows us to define multiple attributes. I chose a hostPath volume which maps a local directory as content for the volume. The capacity allows the resource scheduler to recognize this volume as applicable in terms of resource needs.


Additional Resources:

sudo: docker-compose: command not found

If docker-compose is installed for your user but not installed for root user and if you need to run it only once and forget about it afterwords perform the next actions:

  • Find out path to docker-compose:

      which docker-compose
    
  • Run the command specifying full path to docker-compose from the previous command, eg:

      sudo /home/your-user/your-path-to-compose/docker-compose up
    

ASP.NET Core Identity - get current user

I have put something like this in my Controller class and it worked:

IdentityUser user = await userManager.FindByNameAsync(HttpContext.User.Identity.Name);

where userManager is an instance of Microsoft.AspNetCore.Identity.UserManager class (with all weird setup that goes with it).

Install pip in docker

You might want to change the DNS settings of the Docker daemon. You can edit (or create) the configuration file at /etc/docker/daemon.json with the dns key, as

{
    "dns": ["your_dns_address", "8.8.8.8"]
}

In the example above, the first element of the list is the address of your DNS server. The second item is the Google’s DNS which can be used when the first one is not available.

Before proceeding, save daemon.json and restart the docker service.

sudo service docker restart

Once fixed, retry to run the build command.

What is secret key for JWT based authentication and how to generate it?

The algorithm (HS256) used to sign the JWT means that the secret is a symmetric key that is known by both the sender and the receiver. It is negotiated and distributed out of band. Hence, if you're the intended recipient of the token, the sender should have provided you with the secret out of band.

If you're the sender, you can use an arbitrary string of bytes as the secret, it can be generated or purposely chosen. You have to make sure that you provide the secret to the intended recipient out of band.

For the record, the 3 elements in the JWT are not base64-encoded but base64url-encoded, which is a variant of base64 encoding that results in a URL-safe value.

How to extend available properties of User.Identity

Whenever you want to extend the properties of User.Identity with any additional properties like the question above, add these properties to the ApplicationUser class first like so:

public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }

    // Your Extended Properties
    public long? OrganizationId { get; set; }
}

Then what you need is to create an extension method like so (I create mine in an new Extensions folder):

namespace App.Extensions
{
    public static class IdentityExtensions
    {
        public static string GetOrganizationId(this IIdentity identity)
        {
            var claim = ((ClaimsIdentity)identity).FindFirst("OrganizationId");
            // Test for null to avoid issues during local testing
            return (claim != null) ? claim.Value : string.Empty;
        }
    }
}

When you create the Identity in the ApplicationUser class, just add the Claim -> OrganizationId like so:

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here => this.OrganizationId is a value stored in database against the user
        userIdentity.AddClaim(new Claim("OrganizationId", this.OrganizationId.ToString()));

        return userIdentity;
    }

Once you added the claim and have your extension method in place, to make it available as a property on your User.Identity, add a using statement on the page/file you want to access it:

in my case: using App.Extensions; within a Controller and @using. App.Extensions withing a .cshtml View file.

EDIT:

What you can also do to avoid adding a using statement in every View is to go to the Views folder, and locate the Web.config file in there. Now look for the <namespaces> tag and add your extension namespace there like so:

<add namespace="App.Extensions" />

Save your file and you're done. Now every View will know of your extensions.

You can access the Extension Method:

var orgId = User.Identity.GetOrganizationId();

How to decode a QR-code image in (preferably pure) Python?

I'm answering only the part of the question about zbar installation.

I spent nearly half an hour a few hours to make it work on Windows + Python 2.7 64-bit, so here are additional notes to the accepted answer:

PS: Making it work with Python 3.x is even more difficult: Compile zbar for Python 3.x.

PS2: I just tested pyzbar with pip install pyzbar and it's MUCH easier, it works out-of-the-box (the only thing is you need to have VC Redist 2013 files installed). It is also recommended to use this library in this pyimagesearch.com article.

The client and server cannot communicate, because they do not possess a common algorithm - ASP.NET C# IIS TLS 1.0 / 1.1 / 1.2 - Win32Exception

There are several other posts about this now and they all point to enabling TLS 1.2. Anything less is unsafe.

You can do this in .NET 3.5 with a patch.
You can do this in .NET 4.0 and 4.5 with a single line of code

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // .NET 4.5
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; // .NET 4.0

In .NET 4.6, it automatically uses TLS 1.2.

See here for more details: .NET support for TLS

iPhone 6 Plus resolution confusion: Xcode or Apple's website? for development

Real/physical iPhone 6 Plus resolution is 1920x1080 but in Xcode you make your interface for 2208x1242 resolution (736x414 points) and on device it is automatically scaled down to 1920x1080 pixels.

iPhone resolutions quick reference:

Device          Points    Pixels     Scale  Physical Pixels   PPI   Ratio   Size
iPhone XS Max   896x414   2688x1242  3x     2688x1242         458   19.5:9  6.5"
iPhone XR       896x414   1792x828   2x     1792x828          326   19.5:9  6.1"
iPhone X        812x375   2436x1125  3x     2436x1125         458   19.5:9  5.8"
iPhone 6 Plus   736x414   2208x1242  3x     1920x1080         401   16:9    5.5"
iPhone 6        667x375   1334x750   2x     1334x750          326   16:9    4.7"
iPhone 5        568x320   1136x640   2x     1136x640          326   16:9    4.0"
iPhone 4        480x320   960x640    2x     960x640           326   3:2     3.5"
iPhone 3GS      480x320   480x320    1x     480x320           163   3:2     3.5"

iPhone resolutions

How to update a claim in ASP.NET Identity?

Compiled some answers from here into re-usable ClaimsManager class with my additions.

Claims got persisted, user cookie updated, sign in refreshed.

Please note that ApplicationUser can be substituted with IdentityUser if you didn't customize former. Also in my case it needs to have slightly different logic in Development environment, so you might want to remove IWebHostEnvironment dependency.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using YourMvcCoreProject.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Hosting;

namespace YourMvcCoreProject.Identity
{
    public class ClaimsManager
    {
        private readonly UserManager<ApplicationUser> _userManager;
        private readonly SignInManager<ApplicationUser> _signInManager;
        private readonly IWebHostEnvironment _env;
        private readonly ClaimsPrincipalAccessor _currentPrincipalAccessor;

        public ClaimsManager(
            ClaimsPrincipalAccessor currentPrincipalAccessor,
            UserManager<ApplicationUser> userManager,
            SignInManager<ApplicationUser> signInManager,
            IWebHostEnvironment env)
        {
            _currentPrincipalAccessor = currentPrincipalAccessor;
            _userManager = userManager;
            _signInManager = signInManager;
            _env = env;
        }

        /// <param name="refreshSignin">Sometimes (e.g. when adding multiple claims at once) it is desirable to refresh cookie only once, for the last one </param>
        public async Task AddUpdateClaim(string claimType, string claimValue, bool refreshSignin = true)
        {
            await AddClaim(
                _currentPrincipalAccessor.ClaimsPrincipal,
                claimType,
                claimValue, 
                async user =>
                {
                    await RemoveClaim(_currentPrincipalAccessor.ClaimsPrincipal, user, claimType);
                },
                refreshSignin);
        }

        public async Task AddClaim(string claimType, string claimValue, bool refreshSignin = true)
        {
            await AddClaim(_currentPrincipalAccessor.ClaimsPrincipal, claimType, claimValue, refreshSignin);
        }

        /// <summary>
        /// At certain stages of user auth there is no user yet in context but there is one to work with in client code (e.g. calling from ClaimsTransformer)
        /// that's why we have principal as param
        /// </summary>
        public async Task AddClaim(ClaimsPrincipal principal, string claimType, string claimValue, bool refreshSignin = true)
        {
            await AddClaim(
                principal,
                claimType,
                claimValue, 
                async user =>
                {
                    // allow reassignment in dev
                    if (_env.IsDevelopment()) 
                        await RemoveClaim(principal, user, claimType);

                    if (GetClaim(principal, claimType) != null)
                        throw new ClaimCantBeReassignedException(claimType);                
                },
                refreshSignin);
        }

        public async Task RemoveClaims(IEnumerable<string> claimTypes, bool refreshSignin = true)
        {
            await RemoveClaims(_currentPrincipalAccessor.ClaimsPrincipal, claimTypes, refreshSignin);
        }

        public async Task RemoveClaims(ClaimsPrincipal principal, IEnumerable<string> claimTypes, bool refreshSignin = true)
        {
            AssertAuthenticated(principal);
            foreach (var claimType in claimTypes)
            {
                await RemoveClaim(principal, claimType);
            }
            // reflect the change in the Identity cookie
            if (refreshSignin)
                await _signInManager.RefreshSignInAsync(await _userManager.GetUserAsync(principal));
        }

        public async Task RemoveClaim(string claimType, bool refreshSignin = true)
        {
            await RemoveClaim(_currentPrincipalAccessor.ClaimsPrincipal, claimType, refreshSignin);
        }

        public async Task RemoveClaim(ClaimsPrincipal principal, string claimType, bool refreshSignin = true)
        {
            AssertAuthenticated(principal);
            var user = await _userManager.GetUserAsync(principal);
            await RemoveClaim(principal, user, claimType);
            // reflect the change in the Identity cookie
            if (refreshSignin)
                await _signInManager.RefreshSignInAsync(user);
        }

        private async Task AddClaim(ClaimsPrincipal principal, string claimType, string claimValue, Func<ApplicationUser, Task> processExistingClaims, bool refreshSignin)
        {
            AssertAuthenticated(principal);
            var user = await _userManager.GetUserAsync(principal);
            await processExistingClaims(user);
            var claim = new Claim(claimType, claimValue);
            ClaimsIdentity(principal).AddClaim(claim);
            await _userManager.AddClaimAsync(user, claim);
            // reflect the change in the Identity cookie
            if (refreshSignin)
                await _signInManager.RefreshSignInAsync(user);
        }

        /// <summary>
        /// Due to bugs or as result of debug it can be more than one identity of the same type.
        /// The method removes all the claims of a given type.
        /// </summary>
        private async Task RemoveClaim(ClaimsPrincipal principal, ApplicationUser user, string claimType)
        {
            AssertAuthenticated(principal);
            var identity = ClaimsIdentity(principal);
            var claims = identity.FindAll(claimType).ToArray();
            if (claims.Length > 0)
            {
                await _userManager.RemoveClaimsAsync(user, claims);
                foreach (var c in claims)
                {
                    identity.RemoveClaim(c);
                }
            }
        }

        private static Claim GetClaim(ClaimsPrincipal principal, string claimType)
        {
            return ClaimsIdentity(principal).FindFirst(claimType);    
        }    

        /// <summary>
        /// This kind of bugs has to be found during testing phase
        /// </summary>
        private static void AssertAuthenticated(ClaimsPrincipal principal)
        {
            if (!principal.Identity.IsAuthenticated)
                throw new InvalidOperationException("User should be authenticated in order to update claims");
        }

        private static ClaimsIdentity ClaimsIdentity(ClaimsPrincipal principal)
        {
            return (ClaimsIdentity) principal.Identity;
        }
    }


    public class ClaimCantBeReassignedException : Exception
    {
        public ClaimCantBeReassignedException(string claimType) : base($"{claimType} can not be reassigned")
        {
        }
    }

public class ClaimsPrincipalAccessor
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public ClaimsPrincipalAccessor(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public ClaimsPrincipal ClaimsPrincipal => _httpContextAccessor.HttpContext.User;
}

// to register dependency put this into your Startup.cs and inject ClaimsManager into Controller constructor (or other class) the in same way as you do for other dependencies    
public class Startup
{
    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        services.AddTransient<ClaimsPrincipalAccessor>();
        services.AddTransient<ClaimsManager>();
    }
}

}

HTML 5 Favicon - Support?

No, not all browsers support the sizes attribute:

Note that some platforms define specific sizes:

The model backing the 'ApplicationDbContext' context has changed since the database was created

Just Delete the migration History in _MigrationHistory in your DataBase. It worked for me

Named colors in matplotlib

To get a full list of colors to use in plots:

import matplotlib.colors as colors
colors_list = list(colors._colors_full_map.values())

So, you can use in that way quickly:

scatter(X,Y, color=colors_list[0])
scatter(X,Y, color=colors_list[1])
scatter(X,Y, color=colors_list[2])
...
scatter(X,Y, color=colors_list[-1])

MVC 5 Access Claims Identity User Data

According to the ControllerBase class, you can get the claims for the user executing the action.

enter image description here

here's how you can do it in 1 line.

var claims = User.Claims.ToList();

In Java, can you modify a List while iterating through it?

Use CopyOnWriteArrayList
and if you want to remove it, do the following:

for (Iterator<String> it = userList.iterator(); it.hasNext() ;)
{
    if (wordsToRemove.contains(word))
    {
        it.remove();
    }
}

Download JSON object as a file from browser

This is how I solved it for my application:

HTML: <a id="downloadAnchorElem" style="display:none"></a>

JS (pure JS, not jQuery here):

var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(storageObj));
var dlAnchorElem = document.getElementById('downloadAnchorElem');
dlAnchorElem.setAttribute("href",     dataStr     );
dlAnchorElem.setAttribute("download", "scene.json");
dlAnchorElem.click();

In this case, storageObj is the js object you want to store, and "scene.json" is just an example name for the resulting file.

This approach has the following advantages over other proposed ones:

  • No HTML element needs to be clicked
  • Result will be named as you want it
  • no jQuery needed

I needed this behavior without explicit clicking since I want to trigger the download automatically at some point from js.

JS solution (no HTML required):

  function downloadObjectAsJson(exportObj, exportName){
    var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(exportObj));
    var downloadAnchorNode = document.createElement('a');
    downloadAnchorNode.setAttribute("href",     dataStr);
    downloadAnchorNode.setAttribute("download", exportName + ".json");
    document.body.appendChild(downloadAnchorNode); // required for firefox
    downloadAnchorNode.click();
    downloadAnchorNode.remove();
  }

Detecting IE11 using CSS Capability/Feature Detection

Here's an answer for 2017 on, where you probably only care about distinguishing <=IE11 from >IE11 ("Edge"):

@supports not (old: ie) { /* code for not old IE here */ }

More demonstrative example:

body:before { content: 'old ie'; }
/**/@supports not (old: ie) {
body:before { content: 'not old ie'; }
/**/}

This works because IE11 doesn't actually even support @supports, and all other relevant browser/version combinations do.

stale element reference: element is not attached to the page document

use this code to wait till the element is attached:

boolean breakIt = true;
        while (true) {
        breakIt = true;
        try {
            // write your code here
        } catch (Exception e) {
            if (e.getMessage().contains("element is not attached")) {
                breakIt = false;
            }
        }
        if (breakIt) {
            break;
        }

    }

Run Command Line & Command From VBS

Set oShell = CreateObject ("WScript.Shell") 
oShell.run "cmd.exe /C copy ""S:Claims\Sound.wav"" ""C:\WINDOWS\Media\Sound.wav"" "

How using try catch for exception handling is best practice

Leave blank catch block is the worse thing to do. If there is an error the best way to handle it is to:

  1. Log it into file\database etc..
  2. Try to fix it on the fly (maybe trying alternative way of doing that operation)
  3. If we cannot fix that, notify the user that there is some error and of course abort the operation

Correct MIME Type for favicon.ico?

I have noticed that when using type="image/vnd.microsoft.icon", the favicon fails to appear when the browser is not connected to the internet. But type="image/x-icon" works whether the browser can connect to the internet, or not. When developing, at times I am not connected to the internet.

click command in selenium webdriver does not work

I was working with EasyRepro, and when I debugged my code it was clicking on the element which is visible and enabled, and not navigating as expected. But finally I understood the root cause for the issue.

My Chrome was zoomed out 90%

Once i reset the zoom level, it clicked on the correct element and successfully navigated to next page.

XAMPP PORT 80 is Busy / EasyPHP error in Apache configuration file:

Port 80 might be busy with other application like IIS. If you don't want to stop it, you can change the apache port. Here is the way..

  1. go to the C:\xampp\apache\conf (directory where you installed xampp). Now, locate the httpd.conf.
  2. Open it with any text editor (like notepad) and go the line that says Listen 80
  3. Change this with any other port (like Listen 1234)
  4. Save the file. Restart the server and go ahead.

How can bcrypt have built-in salts?

This is from PasswordEncoder interface documentation from Spring Security,

 * @param rawPassword the raw password to encode and match
 * @param encodedPassword the encoded password from storage to compare with
 * @return true if the raw password, after encoding, matches the encoded password from
 * storage
 */
boolean matches(CharSequence rawPassword, String encodedPassword);

Which means, one will need to match rawPassword that user will enter again upon next login and matches it with Bcrypt encoded password that's stores in database during previous login/registration.

What's the correct way to convert bytes to a hex string in Python 3?

it can been used the format specifier %x02 that format and output a hex value. For example:

>>> foo = b"tC\xfc}\x05i\x8d\x86\x05\xa5\xb4\xd3]Vd\x9cZ\x92~'6"
>>> res = ""
>>> for b in foo:
...     res += "%02x" % b
... 
>>> print(res)
7443fc7d05698d8605a5b4d35d56649c5a927e2736

Best practice: PHP Magic Methods __set and __get

Second code example is much more proper way to do this because you are taking full control of data which are given to class. There are cases in which the __set and __get are useful but not in this case.

Required attribute on multiple checkboxes with the same name?

A little jQuery fix:

$(function(){
    var chbxs = $(':checkbox[required]');
    var namedChbxs = {};
    chbxs.each(function(){
        var name = $(this).attr('name');
        namedChbxs[name] = (namedChbxs[name] || $()).add(this);
    });
    chbxs.change(function(){
        var name = $(this).attr('name');
        var cbx = namedChbxs[name];
        if(cbx.filter(':checked').length>0){
            cbx.removeAttr('required');
        }else{
            cbx.attr('required','required');
        }
    });
});

Spaces in URLs?

A URL must not contain a literal space. It must either be encoded using the percent-encoding or a different encoding that uses URL-safe characters (like application/x-www-form-urlencoded that uses + instead of %20 for spaces).

But whether the statement is right or wrong depends on the interpretation: Syntactically, a URI must not contain a literal space and it must be encoded; semantically, a %20 is not a space (obviously) but it represents a space.

How to change the remote a branch is tracking?

You could either delete your current branch and do:

git branch --track local_branch remote_branch

Or change change remote server to the current one in the config

Case-Insensitive List Search

You're checking if the result of IndexOf is larger or equal 0, meaning whether the match starts anywhere in the string. Try checking if it's equal to 0:

if (testList.FindAll(x => x.IndexOf(keyword, 
                   StringComparison.OrdinalIgnoreCase) >= 0).Count > 0)
   Console.WriteLine("Found in list");

Now "goat" and "oat" won't match, but "goat" and "goa" will. To avoid this, you can compare the lenghts of the two strings.

To avoid all this complication, you can use a dictionary instead of a list. They key would be the lowercase string, and the value would be the real string. This way, performance isn't hurt because you don't have to use ToLower for each comparison, but you can still use Contains.

LINK : fatal error LNK1104: cannot open file 'D:\...\MyProj.exe'

I have just run into the same issue with VS2013, creating device drivers in C++ , and none of the above seemed to fix the issue. However, I have just discovered that in my case the issue appears to have been VMWare-related.

I was running a VMWare workstation client with a shared folder defined on the VM on my entire C: drive. When I disabled the shared folders on the VM Settings, VS2013 was able to happily build my .exe files.

My new process is:

1) Disable the shared folder on the vm (VM Settings | Options | Shared Folders - and uncheck the checkbox) 2) Run the build on the host PC 3) RE-enable the shared folder (and proceed from there)

Hopefully this might help someone else.

(BTW, the errors you receive are that the .exe (or other files) are locked or require Administrator permission, but that is a red herring - It seems to me that the VMWare share is causing those files to appear as locked.)

Python vs Bash - In which kind of tasks each one outruns the other performance-wise?

Developer efficiency matters much more to me in scenarios where both bash and Python are sensible choices.

Some tasks lend themselves well to bash, and others to Python. It also isn't unusual for me to start something as a bash script and change it to Python as it evolves over several weeks.

A big advantage Python has is in corner cases around filename handling, while it has glob, shutil, subprocess, and others for common scripting needs.

How can one develop iPhone apps in Java?

If you plan on integrating app functionality with a website, I'd highly recommend the GWT + PhoneGap model:

http://blog.daniel-kurka.de/2012/02/mgwt-and-phonegap-talk-at-webmontag-in.html http://turbomanage.wordpress.com/2010/09/24/gwt-phonegap-native-mobile-apps-quickly/

Here's my two cents from my own experience: We use the same Java POJOs for our Hibernate database, our REST API, our website, and our iPhone app. The workflow is simple and beautiful:

Database ---1---> REST API ---2---> iPhone App / Website

  • 1: Hibernate
  • 2: GSON Serialization and GWT JSON Deserialization

There is another benefit to this approach as well - any Java code that can be compiled with GWT and any JavaScript library become available for use in your iPhone app.

Testing web application on Mac/Safari when I don't own a Mac

Litmus may help you. It will take screenshots of your webpage(s) in a wide variety of browsers so you can make sure that your site works in all of them. A free alternative (Litmus is a paid service) is Browsershots, but you do get what you pay for. (In some screenshots that Browershots returns, the browser hasn't yet finished loading the webpage...)

Of course, as other people have suggested, buying a Mac is also a good solution (and may be better, depending on the kind of testing you need to do), because then you can test your website yourself in any of the browsers that run under Mac OS X or Windows.

CKEditor instance already exists

Indeed, removing the ".ckeditor" class from your code solves the issue. Most of us followed the jQuery integration example from the ckeditor's documentation:

$('.jquery_ckeditor')
.ckeditor( function() { /* callback code */ }, { skin : 'office2003' } );

and thought "... maybe I can just get rid or the '.jquery_' part".

I've been wasting my time tweaking the callback function (because the {skin:'office2003'} actually worked), while the problem was coming from elsewhere.

I think the documentation should mention that the use of "ckeditor" as a class name is not recommended, because it is a reserved keyword.

Cheers.

Is a Java hashmap search really O(1)?

Of course the performance of the hashmap will depend based on the quality of the hashCode() function for the given object. However, if the function is implemented such that the possibility of collisions is very low, it will have a very good performance (this is not strictly O(1) in every possible case but it is in most cases).

For example the default implementation in the Oracle JRE is to use a random number (which is stored in the object instance so that it doesn't change - but it also disables biased locking, but that's an other discussion) so the chance of collisions is very low.

Changing the current working directory in Java?

It is possible to change the PWD, using JNA/JNI to make calls to libc. The JRuby guys have a handy java library for making POSIX calls called jna-posix Here's the maven info

You can see an example of its use here (Clojure code, sorry). Look at the function chdirToRoot

Performance of Arrays vs. Lists

if you are just getting a single value out of either (not in a loop) then both do bounds checking (you're in managed code remember) it's just the list does it twice. See the notes later for why this is likely not a big deal.

If you are using your own for(int int i = 0; i < x.[Length/Count];i++) then the key difference is as follows:

  • Array:
    • bounds checking is removed
  • Lists
    • bounds checking is performed

If you are using foreach then the key difference is as follows:

  • Array:
    • no object is allocated to manage the iteration
    • bounds checking is removed
  • List via a variable known to be List.
    • the iteration management variable is stack allocated
    • bounds checking is performed
  • List via a variable known to be IList.
    • the iteration management variable is heap allocated
    • bounds checking is performed also Lists values may not be altered during the foreach whereas the array's can be.

The bounds checking is often no big deal (especially if you are on a cpu with a deep pipeline and branch prediction - the norm for most these days) but only your own profiling can tell you if that is an issue. If you are in parts of your code where you are avoiding heap allocations (good examples are libraries or in hashcode implementations) then ensuring the variable is typed as List not IList will avoid that pitfall. As always profile if it matters.

A fatal error has been detected by the Java Runtime Environment: SIGSEGV, libjvm

add new server (tomcat) with different location. if i am not make mistake you are run multiple project with same tomcat and add same tomcat server on same location ..

add new tomcat for each new workspace.

How can I Remove .DS_Store files from a Git repository?

No need to remove .DS_STORE locally

Just add it to .gitignore file

The .gitignore file is just a text file that tells Git which files or folders to ignore in a project.

Commands

  • nano .gitignore
  • Write .DS_Store Then click CTRL+X > y > Hit Return
  • git status To have a last look at your changes
  • git add .gitignore
  • git commit -m 'YOUR COMMIT MESSAGE'
  • git push origin master

Git push error pre-receive hook declined

You need to add your ssh key to your git account,if it throws error then delete previous ssh key and create a new ssh key then add.

How to remove all whitespace from a string?

Use [[:blank:]] to match any kind of horizontal white_space characters.

gsub("[[:blank:]]", "", " xx yy 11 22  33 ")
# [1] "xxyy112233"

How do you determine the ideal buffer size when using FileInputStream?

Yes, it's probably dependent on various things - but I doubt it will make very much difference. I tend to opt for 16K or 32K as a good balance between memory usage and performance.

Note that you should have a try/finally block in the code to make sure the stream is closed even if an exception is thrown.

How do you change the character encoding of a postgres database?

Daniel Kutik's answer is correct, but it can be even more safe, with database renaming.

So, the truly safe way is:

  1. Create new database with the different encoding and name
  2. Dump your database
  3. Restore dump to the new DB
  4. Test that your application runs correctly with the new DB
  5. Rename old DB to something meaningful
  6. Rename new DB
  7. Test application again
  8. Drop the old database

In case of emergency, just rename DBs back

In Perl, how do I create a hash whose keys come from a given array?

@hash{@keys} = undef;

The syntax here where you are referring to the hash with an @ is a hash slice. We're basically saying $hash{$keys[0]} AND $hash{$keys[1]} AND $hash{$keys[2]} ... is a list on the left hand side of the =, an lvalue, and we're assigning to that list, which actually goes into the hash and sets the values for all the named keys. In this case, I only specified one value, so that value goes into $hash{$keys[0]}, and the other hash entries all auto-vivify (come to life) with undefined values. [My original suggestion here was set the expression = 1, which would've set that one key to 1 and the others to undef. I changed it for consistency, but as we'll see below, the exact values do not matter.]

When you realize that the lvalue, the expression on the left hand side of the =, is a list built out of the hash, then it'll start to make some sense why we're using that @. [Except I think this will change in Perl 6.]

The idea here is that you are using the hash as a set. What matters is not the value I am assigning; it's just the existence of the keys. So what you want to do is not something like:

if ($hash{$key} == 1) # then key is in the hash

instead:

if (exists $hash{$key}) # then key is in the set

It's actually more efficient to just run an exists check than to bother with the value in the hash, although to me the important thing here is just the concept that you are representing a set just with the keys of the hash. Also, somebody pointed out that by using undef as the value here, we will consume less storage space than we would assigning a value. (And also generate less confusion, as the value does not matter, and my solution would assign a value only to the first element in the hash and leave the others undef, and some other solutions are turning cartwheels to build an array of values to go into the hash; completely wasted effort).

How do you properly determine the current script directory?

#!/usr/bin/env python
import inspect
import os
import sys

def get_script_dir(follow_symlinks=True):
    if getattr(sys, 'frozen', False): # py2exe, PyInstaller, cx_Freeze
        path = os.path.abspath(sys.executable)
    else:
        path = inspect.getabsfile(get_script_dir)
    if follow_symlinks:
        path = os.path.realpath(path)
    return os.path.dirname(path)

print(get_script_dir())

It works on CPython, Jython, Pypy. It works if the script is executed using execfile() (sys.argv[0] and __file__ -based solutions would fail here). It works if the script is inside an executable zip file (/an egg). It works if the script is "imported" (PYTHONPATH=/path/to/library.zip python -mscript_to_run) from a zip file; it returns the archive path in this case. It works if the script is compiled into a standalone executable (sys.frozen). It works for symlinks (realpath eliminates symbolic links). It works in an interactive interpreter; it returns the current working directory in this case.

How to run a program automatically as admin on Windows 7 at startup?

You can do this by installing the task while running as administrator via the TaskSchedler library. I'm making the assumption here that .NET/C# is a suitable platform/language given your related questions.

This library gives you granular access to the Task Scheduler API, so you can adjust settings that you cannot otherwise set via the command line by calling schtasks, such as the priority of the startup. Being a parental control application, you'll want it to have a startup priority of 0 (maximum), which schtasks will create by default a priority of 7.

Below is a code example of installing a properly configured startup task to run the desired application as administrator indefinitely at logon. This code will install a task for the very process that it's running from.

/*
Copyright © 2017 Jesse Nicholson  
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

/// <summary>
/// Used for synchronization when creating run at startup task.
/// </summary>
private ReaderWriterLockSlim m_runAtStartupLock = new ReaderWriterLockSlim();

public void EnsureStarupTaskExists()
{
    try
    {
        m_runAtStartupLock.EnterWriteLock();


        using(var ts = new Microsoft.Win32.TaskScheduler.TaskService())
        {
            // Start off by deleting existing tasks always. Ensure we have a clean/current install of the task.
            ts.RootFolder.DeleteTask(Process.GetCurrentProcess().ProcessName, false);

            // Create a new task definition and assign properties
            using(var td = ts.NewTask())
            {
                td.Principal.RunLevel = Microsoft.Win32.TaskScheduler.TaskRunLevel.Highest;
                // This is not normally necessary. RealTime is the highest priority that
                // there is.
                td.Settings.Priority = ProcessPriorityClass.RealTime;
                td.Settings.DisallowStartIfOnBatteries = false;
                td.Settings.StopIfGoingOnBatteries = false;
                td.Settings.WakeToRun = false;
                td.Settings.AllowDemandStart = false;
                td.Settings.IdleSettings.RestartOnIdle = false;                    
                td.Settings.IdleSettings.StopOnIdleEnd = false;
                td.Settings.RestartCount = 0;                    
                td.Settings.AllowHardTerminate = false;
                td.Settings.Hidden = true;
                td.Settings.Volatile = false;
                td.Settings.Enabled = true;
                td.Settings.Compatibility = Microsoft.Win32.TaskScheduler.TaskCompatibility.V2;
                td.Settings.ExecutionTimeLimit = TimeSpan.Zero;

                td.RegistrationInfo.Description = "Runs the content filter at startup.";

                // Create a trigger that will fire the task at this time every other day
                var logonTrigger = new Microsoft.Win32.TaskScheduler.LogonTrigger();
                logonTrigger.Enabled = true;                    
                logonTrigger.Repetition.StopAtDurationEnd = false;
                logonTrigger.ExecutionTimeLimit = TimeSpan.Zero;
                td.Triggers.Add(logonTrigger);

                // Create an action that will launch Notepad whenever the trigger fires
                td.Actions.Add(new Microsoft.Win32.TaskScheduler.ExecAction(Process.GetCurrentProcess().MainModule.FileName, "/StartMinimized", null));

                // Register the task in the root folder
                ts.RootFolder.RegisterTaskDefinition(Process.GetCurrentProcess().ProcessName, td);
            }
        }                
    }
    finally
    {
        m_runAtStartupLock.ExitWriteLock();
    }
}

How do you get the magnitude of a vector in Numpy?

Fastest way I found is via inner1d. Here's how it compares to other numpy methods:

import numpy as np
from numpy.core.umath_tests import inner1d

V = np.random.random_sample((10**6,3,)) # 1 million vectors
A = np.sqrt(np.einsum('...i,...i', V, V))
B = np.linalg.norm(V,axis=1)   
C = np.sqrt((V ** 2).sum(-1))
D = np.sqrt((V*V).sum(axis=1))
E = np.sqrt(inner1d(V,V))

print [np.allclose(E,x) for x in [A,B,C,D]] # [True, True, True, True]

import cProfile
cProfile.run("np.sqrt(np.einsum('...i,...i', V, V))") # 3 function calls in 0.013 seconds
cProfile.run('np.linalg.norm(V,axis=1)')              # 9 function calls in 0.029 seconds
cProfile.run('np.sqrt((V ** 2).sum(-1))')             # 5 function calls in 0.028 seconds
cProfile.run('np.sqrt((V*V).sum(axis=1))')            # 5 function calls in 0.027 seconds
cProfile.run('np.sqrt(inner1d(V,V))')                 # 2 function calls in 0.009 seconds

inner1d is ~3x faster than linalg.norm and a hair faster than einsum

How to customise the Jackson JSON mapper implicitly used by Spring Boot?

The right way to add further configurations to the Spring Boot peconfigured ObjectMapper is to define a Jackson2ObjectMapperBuilderCustomizer. Else you are overwriting Springs configuration, which you do not want to lose.

 @Configuration
public class MyJacksonConfigurer implements Jackson2ObjectMapperBuilderCustomizer {
    @Override
    public void customize(Jackson2ObjectMapperBuilder builder) {
        builder.deserializerByType(LocalDate.class, new MyOwnJsonLocalDateTimeDeserializer());
    }
}

Anchor links in Angularjs?

You need to only add target="_self" to your link

ex. <a href="#services" target="_self">Services</a><div id="services"></div>

powershell - extract file name and extension

just do it:

$file=Get-Item "C:\temp\file.htm"
$file.Basename 
$file.Extension

Provide password to ssh command inside bash script, Without the usage of public keys and Expect

AFAIK there is no possibility beside from using keys or expect if you are using the command line version ssh. But there are library bindings for the most programming languages like C, python, php, ... . You could write a program in such a language. This way it would be possible to pass the password automatically. But note this is of course a security problem as the password will be stored in plain text in that program

Double free or corruption after queue::push

You can also try to check null before delete such that

if(myArray) { delete[] myArray; myArray = NULL; }

or you can define all delete operations ina safe manner like this:

#ifndef SAFE_DELETE
#define SAFE_DELETE(p) { if(p) { delete (p); (p) = NULL; } }
#endif

#ifndef SAFE_DELETE_ARRAY
#define SAFE_DELETE_ARRAY(p) { if(p) { delete[] (p); (p) = NULL; } }
#endif

and then use

SAFE_DELETE_ARRAY(myArray);

Getting a map() to return a list in Python 3.x

list(map(chr, [66, 53, 0, 94]))

map(func, *iterables) --> map object Make an iterator that computes the function using arguments from each of the iterables. Stops when the shortest iterable is exhausted.

"Make an iterator"

means it will return an iterator.

"that computes the function using arguments from each of the iterables"

means that the next() function of the iterator will take one value of each iterables and pass each of them to one positional parameter of the function.

So you get an iterator from the map() funtion and jsut pass it to the list() builtin function or use list comprehensions.

How to split a string of space separated numbers into integers?

Use str.split():

>>> "42 0".split()  # or .split(" ")
['42', '0']

Note that str.split(" ") is identical in this case, but would behave differently if there were more than one space in a row. As well, .split() splits on all whitespace, not just spaces.

Using map usually looks cleaner than using list comprehensions when you want to convert the items of iterables to built-ins like int, float, str, etc. In Python 2:

>>> map(int, "42 0".split())
[42, 0]

In Python 3, map will return a lazy object. You can get it into a list with list():

>>> map(int, "42 0".split())
<map object at 0x7f92e07f8940>
>>> list(map(int, "42 0".split()))
[42, 0]

Html.Textbox VS Html.TextboxFor

IMO the main difference is that Textbox is not strongly typed. TextboxFor take a lambda as a parameter that tell the helper the with element of the model to use in a typed view.

You can do the same things with both, but you should use typed views and TextboxFor when possible.

ActiveXObject creation error " Automation server can't create object"

Well you can not run code from notepad so that means you are opening up the page from the file system. aka c:/foo/bar/hello.html

When you run the code from the asp.net page, you are running it from localhost. aka http://loalhost:1234/assdf.html

Each of these run in different security zones on IE.

How to embed fonts in CSS?

I used Ataturk's font like this. I didn't use "TTF" version. I translated orginal font version ("otf" version) to "eot" and "woof" version. Then It works in local but not working when I uploaded the files to server. So I added "TTF" version too like this. Now, It's working on Chrome and Firefox but Internet Explorer still defence. When you installed on your computer "Ataturk" font, then working IE too. But I wanted to use this font without installing.

@font-face {
    font-family: 'Ataturk';
    font-style: normal;
    font-weight: normal;
    src: url('font/ataturk.eot');
    src: local('Ataturk Regular'), url('font/ataturk.ttf') format('truetype'), 
    url('font/ataturk.woff') format('woff');
}

You can see it on my website here: http://www.canotur.com

How to disable mouse right click on a web page?

//Disable right click script via java script code

<script language=JavaScript>
//Disable right click script
var message = "";
///////////////////////////////////
function clickIE() {
    if (document.all) {
        (message);
        return false;
    }
}

function clickNS(e) {
    if (document.layers || (document.getElementById && !document.all)) {
        if (e.which == 2 || e.which == 3) {
            (message);
            return false;
        }
    }
}
if (document.layers) {
    document.captureEvents(Event.MOUSEDOWN);
    document.onmousedown = clickNS;
} else {
    document.onmouseup = clickNS;
    document.oncontextmenu = clickIE;
}

document.oncontextmenu = new Function("return false")
</script>

Click here to see semo

When is TCP option SO_LINGER (0) required?

When linger is on but the timeout is zero the TCP stack doesn't wait for pending data to be sent before closing the connection. Data could be lost due to this but by setting linger this way you're accepting this and asking that the connection be reset straight away rather than closed gracefully. This causes an RST to be sent rather than the usual FIN.

Thanks to EJP for his comment, see here for details.

How to add users to Docker container?

Alternatively you can do like this.

RUN addgroup demo && adduser -DH -G demo demo

First command creates group called demo. Second command creates demo user and adds him to previously created demo group.

Flags stands for:

-G Group
-D Don't assign password
-H Don't create home directory

How to customize an end time for a YouTube video?

I tried the method of @mystic11 ( https://stackoverflow.com/a/11422551/506073 ) and got redirected around. Here is a working example URL:

http://youtube.googleapis.com/v/WA8sLsM3McU?start=15&end=20&version=3

If the version=3 parameter is omitted, the video starts at the correct place but runs all the way to the end. From the documentation for the end parameter I am guessing version=3 asks for the AS3 player to be used. See:

end (supported players: AS3, HTML5)

Additional Experiments

Autoplay

Autoplay of the clipped video portion works:

http://youtube.googleapis.com/v/WA8sLsM3McU?start=15&end=20&version=3&autoplay=1

Looping

Adding looping as per the documentation unfortunately starts the second and subsequent iterations at the beginning of the video: http://youtube.googleapis.com/v/WA8sLsM3McU?start=15&end=20&version=3&loop=1&playlist=WA8sLsM3McU

To do this properly, you probably need to set enablejsapi=1 and use the javascript API.

FYI, the above video looped: http://www.infinitelooper.com/?v=WA8sLsM3McU&p=n#/15;19

Remove Branding and Related Videos

To get rid of the Youtube logo and the list of videos to click on to at the end of playing the video you want to watch, add these (&modestBranding=1&rel=0) parameters:

http://youtube.googleapis.com/v/WA8sLsM3McU?start=15&end=20&version=3&autoplay=1&modestBranding=1&rel=0

Remove the uploader info with showinfo=0:

http://youtube.googleapis.com/v/WA8sLsM3McU?start=15&end=20&version=3&autoplay=1&modestBranding=1&rel=0&showinfo=0

This eliminates the thin strip with video title, up and down thumbs, and info icon at the top of the video. The final version produced is fairly clean and doesn't have the downside of giving your viewers an exit into unproductive clicking around Youtube at the end of watching the video portion that you wanted them to see.

Operator overloading in Java

Operator overloading is used in Java for the concatenation of the String type:

String concat = "one" + "two";

However, you cannot define your own operator overloads.

JAX-RS / Jersey how to customize error handling?

@Provider
public class BadURIExceptionMapper implements ExceptionMapper<NotFoundException> {

public Response toResponse(NotFoundException exception){

    return Response.status(Response.Status.NOT_FOUND).
    entity(new ErrorResponse(exception.getClass().toString(),
                exception.getMessage()) ).
    build();
}
}

Create above class. This will handle 404 (NotFoundException) and here in toResponse method you can give your custom response. Similarly there are ParamException etc. which you would need to map to provide customized responses.

Merge 2 arrays of objects

You could use an object to collect up your properties while replacing duplicates and then expand/flatten that object back to an array. Something like this:

function merge(args) {
    args  = Array.prototype.slice.call(arguments);
    var o = { };
    for(var i = 0; i < args.length; ++i)
        for(var j = 0; j < args[i].length; ++j)
            o[args[i][j].name] = args[i][j].value;
    return o;
}

function expand(o) {
    var a = [ ];
    for(var p in o)
        if(o.hasOwnProperty(p))
            a.push({ name: p, value: o[p]});
    return a;
}

var arr1 = new Array({name: "lang", value: "English"}, {name: "age", value: "18"});
var arr2 = new Array({name : "childs", value: '5'}, {name: "lang", value: "German"});
var arr3 = expand(merge(arr1, arr2));

I don't know if this is the fastest way but it works for any number of input arrays; for example, this:

var a = expand(
    merge(
        [{name: "lang", value: "English"}, {name: "age", value: "18"}],
        [{name: "childs", value: '5'}, {name: "lang", value: "German"}],
        [{name: 'lang', value: 'Pancakes'}]
    )
);

Gives you the same thing in a that was in arr3 with "German" replaced by "Pancakes".

This approach does assume that your objects all have the same {name: ..., value: ...} form of course.

You can see it working here (open your console please): http://jsfiddle.net/ambiguous/UtBbB/

Django ChoiceField

New method in Django 3

you can use Field.choices Enumeration Types new update in django3 like this :

from django.db import models

class Status(models.TextChoices):
    UNPUBLISHED = 'UN', 'Unpublished'
    PUBLISHED = 'PB', 'Published'


class Book(models.Model):
    status = models.CharField(
        max_length=2,
        choices=Status.choices,
        default=Status.UNPUBLISHED,
    )

django docs

How to clear an EditText on click?

@Harris's answer is great, I've implemented it as a separate subclass of EditText, which can make it easier to use if your code already adds TextChangedListeners.

Also, I've tweaked it so that, if you already use any Compound Drawables, it leaves them intact.

Code is here, for anyone who needs it:

package com.companyname.your

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;

public class ClearableEditText extends EditText {

    public String defaultValue = "";
    final Drawable imgX = getResources().getDrawable(android.R.drawable.presence_offline ); // X image


    public ClearableEditText(Context context) {
        super(context);

        init();
    }

    public ClearableEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        init();
    }

    public ClearableEditText(Context context, AttributeSet attrs) {
        super(context, attrs);

        init();
    }


    void init()  {

        // Set bounds of our X button
        imgX.setBounds(0, 0, imgX.getIntrinsicWidth(), imgX.getIntrinsicHeight());      

        // There may be initial text in the field, so we may need to display the button
        manageClearButton();

        this.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                ClearableEditText et = ClearableEditText.this;

                // Is there an X showing?
                if (et.getCompoundDrawables()[2] == null) return false;
                // Only do this for up touches
                if (event.getAction() != MotionEvent.ACTION_UP) return false;
                // Is touch on our clear button?
                if (event.getX() > et.getWidth() - et.getPaddingRight() - imgX.getIntrinsicWidth()) {
                    et.setText("");
                    ClearableEditText.this.removeClearButton();
                }
                return false;
            }
        });

        this.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                ClearableEditText.this.manageClearButton();
            }

            @Override
            public void afterTextChanged(Editable arg0) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
        });
    }

    void manageClearButton() {
        if (this.getText().toString().equals("") )
            removeClearButton();
        else
            addClearButton();
    }
    void addClearButton() {
        this.setCompoundDrawables(this.getCompoundDrawables()[0], 
                this.getCompoundDrawables()[1],
                imgX,
                this.getCompoundDrawables()[3]);
    }
    void removeClearButton() {
        this.setCompoundDrawables(this.getCompoundDrawables()[0], 
                this.getCompoundDrawables()[1],
                null,
                this.getCompoundDrawables()[3]);
    }

}

Execute combine multiple Linux commands in one line

To run them all at once, you can use the pipe line key "|" like so:

$ cd /my_folder | rm *.jar | svn co path to repo | mvn compile package install

Doctrine 2: Update query with query builder

With a small change, it worked fine for me

$qb=$this->dm->createQueryBuilder('AppBundle:CSSDInstrument')
               ->update()
               ->field('status')->set($status)
               ->field('id')->equals($instrumentId)
               ->getQuery()
               ->execute();

How to set tint for an image view programmatically in android?

I found that we can use color selector for tint attr:

mImageView.setEnabled(true);

activity_main.xml:

<ImageView
    android:id="@+id/image_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_arrowup"
    android:tint="@color/section_arrowup_color" />

section_arrowup_color.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@android:color/white" android:state_enabled="true"/>
    <item android:color="@android:color/black" android:state_enabled="false"/>
    <item android:color="@android:color/white"/>
</selector>

how to read xml file from url using php

It is working for me. I think you probably need to use urlencode() on each of the components of $map_url.

How do I create JavaScript array (JSON format) dynamically?

What I do is something just a little bit different from @Chase answer:

var employees = {};

// ...and then:
employees.accounting = new Array();

for (var i = 0; i < someArray.length; i++) {
    var temp_item = someArray[i];

    // Maybe, here make something like:
    // temp_item.name = 'some value'

    employees.accounting.push({
        "firstName" : temp_item.firstName,
        "lastName"  : temp_item.lastName,
        "age"       : temp_item.age
    });
}

And that work form me!

I hope it could be useful for some body else!

Run a mySQL query as a cron job?

This was a very handy page as I have a requirement to DELETE records from a mySQL table where the expiry date is < Today.

I am on a shared host and CRON did not like the suggestion AndrewKDay. it also said (and I agree) that exposing the password in this way could be insecure.

I then tried turning Events ON in phpMyAdmin but again being on a shared host this was a no no. Sorry fancyPants.

So I turned to embedding the SQL script in a PHP file. I used the example [here][1]

[1]: https://www.w3schools.com/php/php_mysql_create_table.asp stored it in a sub folder somewhere safe and added an empty index.php for good measure. I was then able to test that this PHP file (and my SQL script) was working from the browser URL line.

All good so far. On to CRON. Following the above example almost worked. I ended up calling PHP before the path for my *.php file. Otherwise CRON didn't know what to do with the file.

my cron is set to run once per day and looks like this, modified for security.

00 * * * * php mywebsiteurl.com/wp-content/themes/ForteChildTheme/php/DeleteExpiredAssessment.php

For the final testing with CRON I initially set it to run each minute and had email alerts turned on. This quickly confirmed that it was running as planned and I changed it back to once per day.

Hope this helps.

Adding a newline character within a cell (CSV)

I have the same issue, when I try to export the content of email to csv and still keep it break line when importing to excel.

I export the conent as this: ="Line 1"&CHAR(10)&"Line 2"

When I import it to excel(google), excel understand it as string. It still not break new line.

We need to trigger excel to treat it as formula by: Format -> Number | Scientific.

This is not the good way but it resolve my issue.

Increase number of axis ticks

Additionally,

ggplot(dat, aes(x,y)) +
geom_point() +
scale_x_continuous(breaks = seq(min(dat$x), max(dat$x), by = 0.05))

Works for binned or discrete scaled x-axis data (I.e., rounding not necessary).

Opacity CSS not working in IE8

You need to set Opacity first for standards-compliant browsers, then the various versions of IE. See Example:

but this opacity code not work in ie8

.slidedownTrigger
{
    cursor: pointer;
    opacity: .75; /* Standards Compliant Browsers */
    filter: alpha(opacity=75); /* IE 7 and Earlier */
    /* Next 2 lines IE8 */
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=75)";
    filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=75);
}

Note that I eliminated -moz as Firefox is a Standards Compliant browser and that line is no longer necessary. Also, -khtml is depreciated, so I eliminated that style as well.

Furthermore, IE's filters will not validate to w3c standards, so if you want your page to validate, separate your standards stylesheet from your IE stylesheet by using an if IE statement like below:

<!--[if IE]>
<link rel="stylesheet" type="text/css"  href="http://www.mysite.com/css/ie.css" />
<![endif]-->

If you separate the ie quirks, your site will validate just fine.

How to call a vue.js function on page load

you can also do this using mounted

https://vuejs.org/v2/guide/migration.html#ready-replaced

....
methods:{
    getUnits: function() {...}
},
mounted: function(){
    this.$nextTick(this.getUnits)
}
....

check if array is empty (vba excel)

@jeminar has the best solution above.

I cleaned it up a bit though.

I recommend adding this to a FunctionsArray module

  • isInitialised=false is not needed because Booleans are false when created
  • On Error GoTo 0 wrap and indent code inside error blocks similar to with blocks for visibility. these methods should be avoided as much as possible but ... VBA ...
Function isInitialised(ByRef a() As Variant) As Boolean
    On Error Resume Next
    isInitialised = IsNumeric(UBound(a))
    On Error GoTo 0
End Function

How to check Oracle database for long running queries

Try this, it will give you queries currently running for more than 60 seconds. Note that it prints multiple lines per running query if the SQL has multiple lines. Look at the sid,serial# to see what belongs together.

select s.username,s.sid,s.serial#,s.last_call_et/60 mins_running,q.sql_text from v$session s 
join v$sqltext_with_newlines q
on s.sql_address = q.address
 where status='ACTIVE'
and type <>'BACKGROUND'
and last_call_et> 60
order by sid,serial#,q.piece

How to get year and month from a date - PHP

Use strtotime():

$time=strtotime($dateValue);
$month=date("F",$time);
$year=date("Y",$time);

Package signatures do not match the previously installed version

In my case the issue was I had installed an app with the package name let's say com.example.package using android studio on my device. I created another app with the same package name and was trying to install it on my device. That is what was causing the problem. So just check on your device whether another app with the same package name already exists or not.

How can I determine if a date is between two dates in Java?

you can use getTime() and compare the returned long UTC values.

EDIT if you are sure you'll not have to deal with dates before 1970, not sure how it will behave in that case.

Angular File Upload

  1. HTML

    <div class="form-group">
      <label for="file">Choose File</label><br /> <input type="file" id="file" (change)="uploadFiles($event.target.files)">
    </div>

    <button type="button" (click)="RequestUpload()">Ok</button>

  1. ts File
public formData = new FormData();
ReqJson: any = {};

uploadFiles( file ) {
        console.log( 'file', file )
        for ( let i = 0; i < file.length; i++ ) {
            this.formData.append( "file", file[i], file[i]['name'] );
        }
    }

RequestUpload() {
        this.ReqJson["patientId"] = "12"
        this.ReqJson["requesterName"] = "test1"
        this.ReqJson["requestDate"] = "1/1/2019"
        this.ReqJson["location"] = "INDIA"
        this.formData.append( 'Info', JSON.stringify( this.ReqJson ) )
            this.http.post( '/Request', this.formData )
                .subscribe(( ) => {                 
                });     
    }
  1. Backend Spring(java file)

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class Request {
    private static String UPLOADED_FOLDER = "c://temp//";

    @PostMapping("/Request")
    @ResponseBody
    public String uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("Info") String Info) {
        System.out.println("Json is" + Info);
        if (file.isEmpty()) {
            return "No file attached";
        }
        try {
            // Get the file and save it somewhere
            byte[] bytes = file.getBytes();
            Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
            Files.write(path, bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "Succuss";
    }
}

We have to create a folder "temp" in C drive, then this code will print the Json in console and save the uploaded file in the created folder

COALESCE with Hive SQL

Hive supports bigint literal since 0.8 version. So, additional "L" is enough:

COALESCE(column, 0L)

How to set fake GPS location on IOS real device

it seems with XCode 9.2 the way to import .gpx has changed, I tried the ways described here and did not do. The only way worked for me was to drag and drop the file .gpx to the project navigator window on the left. Then I can choose the country in the simulator item.

Hope this helps to someone.

How to play a sound in C#, .NET

I think you must firstly add a .wav file to Resources. For example you have sound file named Sound.wav. After you added the Sound.wav file to Resources, you can use this code:

System.Media.SoundPlayer player = new System.Media.SoundPlayer(Properties.Resources.Sound);
player.Play();

This is another way to play sound.

JavaScript listener, "keypress" doesn't detect backspace?

My numeric control:

function CheckNumeric(event) {
    var _key = (window.Event) ? event.which : event.keyCode;
    if (_key > 95 && _key < 106) {
        return true;
    }
    else if (_key > 47 && _key < 58) {
        return true;
    }
    else {
        return false;
    }
}

<input type="text" onkeydown="return CheckNumerick(event);" />

try it

BackSpace key code is 8

Align Div at bottom on main Div

Please try this:

#b {
display: -webkit-inline-flex;
display: -moz-inline-flex;
display: inline-flex;

-webkit-flex-flow: row nowrap;
-moz-flex-flow: row nowrap;
flex-flow: row nowrap;

-webkit-align-items: flex-end;
-moz-align-items: flex-end;
align-items: flex-end;}

Here's a JSFiddle demo: http://jsfiddle.net/rudiedirkx/7FGKN/.

ORA-12505: TNS:listener does not currently know of SID given in connect descriptor (DBD ERROR: OCIServerAttach)

I have some vague recollections of Oracle databases needing a bit of fiddling when you reboot for the first time after installing the database. However, you haven't given us enough information to work on. To start with:

  • What code are you using to connect to the database?
  • It's not clear whether the database instance has been started. Can you connect to the database using sqlplus / as sysdba from within the VM?
  • What has been written to the listener.log file (in %ORACLE_HOME%\network\log) since the last reboot?

EDIT: I've now been able to come up with a scenario which generates the same error message you got. It looks to me like the database you're attempting to connect to has not been started up. The example I present below uses Oracle XE on Linux, but I don't think this makes a significant difference.

First, let us confirm that the database is shut down:

$ sqlplus / as sysdba

SQL*Plus: Release 10.2.0.1.0 - Production on Sat Jul 17 18:16:43 2010

Copyright (c) 1982, 2005, Oracle.  All rights reserved.

Connected to an idle instance.

It's the text Connected to an idle instance that tells us that the database is shut down.

Using sqlplus / as sysdba connects us to the database as SYS without needing a password, but it only works on the same machine as the database itself. In your case, you'd need to run this inside the virtual machine. SYS has permission to start up and shut down the database, and to connect to it when it is shut down, but normal users don't have these permissions.

Now let us disconnect and try reconnecting as a normal user, one that does not have permission to startup/shutdown the database nor connect to it when it is down:

SQL> exit
Disconnected

$ sqlplus -L "user/pw@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521))(CONNECT_DATA=(SID=XE)))"

SQL*Plus: Release 10.2.0.1.0 - Production on Sat Jul 17 18:16:47 2010                                                                                                               

Copyright (c) 1982, 2005, Oracle.  All rights reserved.

ERROR:
ORA-12505: TNS:listener does not currently know of SID given in connect
descriptor                                                             


SP2-0751: Unable to connect to Oracle.  Exiting SQL*Plus

That's the error message you've been getting.

Now, let's start the database up:

$ sqlplus / as sysdba

SQL*Plus: Release 10.2.0.1.0 - Production on Sat Jul 17 18:17:00 2010

Copyright (c) 1982, 2005, Oracle.  All rights reserved.

Connected to an idle instance.

SQL> startup
ORACLE instance started.

Total System Global Area  805306368 bytes
Fixed Size                  1261444 bytes
Variable Size             209715324 bytes
Database Buffers          591396864 bytes
Redo Buffers                2932736 bytes
Database mounted.
Database opened.
SQL> exit
Disconnected from Oracle Database 10g Express Edition Release 10.2.0.1.0 - Production

Now that the database is up, let's attempt to log in as a normal user:

$ sqlplus -L "user/pw@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521))(CONNECT_DATA=(SID=XE)))"

SQL*Plus: Release 10.2.0.1.0 - Production on Sat Jul 17 18:17:11 2010

Copyright (c) 1982, 2005, Oracle.  All rights reserved.


Connected to:
Oracle Database 10g Express Edition Release 10.2.0.1.0 - Production

SQL> 

We're in.

I hadn't seen an ORA-12505 error before because I don't normally connect to an Oracle database by entering the entire connection string on the command line. This is likely to be similar to how you are attempting to connect to the database. Usually, I either connect to a local database, or connect to a remote database by using a TNS name (these are listed in the tnsnames.ora file, in %ORACLE_HOME%\network\admin). In both of these cases you get a different error message if you attempt to connect to a database that has been shut down.

If the above doesn't help you (in particular, if the database has already been started, or you get errors starting up the database), please let us know.

EDIT 2: it seems the problems you were having were indeed because the database hadn't been started. It also appears that your database isn't configured to start up when the service starts. It is possible to get the database to start up when the service is started, and to shut down when the service is stopped. To do this, use the Oracle Administration Assistant for Windows, see here.

select a value where it doesn't exist in another table

SELECT ID
  FROM A
 WHERE ID NOT IN (
      SELECT ID
        FROM B);

SELECT ID    
  FROM A a
 WHERE NOT EXISTS (
      SELECT 1 
        FROM B b
       WHERE b.ID = a.ID)

         SELECT a.ID 
           FROM A a    
LEFT OUTER JOIN B b 
             ON a.ID = b.ID    
          WHERE b.ID IS NULL

DELETE 
  FROM A 
 WHERE ID NOT IN (
      SELECT ID 
        FROM B) 

How to change collation of database, table, column?

Just run this SQL to convert all database tables at once. Change your COLLATION and databaseName to what you need.

SELECT CONCAT("ALTER TABLE ", TABLE_SCHEMA, '.', TABLE_NAME," COLLATE utf8_general_ci;") AS    ExecuteTheString
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA="databaseName"
AND TABLE_TYPE="BASE TABLE";

How can I fetch all items from a DynamoDB table without specifying the primary key?

A simple code to list all the Items from DynamoDB Table by specifying the region of AWS Service.

import boto3

dynamodb = boto3.resource('dynamodb', region_name='ap-south-1')
table = dynamodb.Table('puppy_store')
response = table.scan()
items = response['Items']

# Prints All the Items at once
print(items)

# Prints Items line by line
for i, j in enumerate(items):
    print(f"Num: {i} --> {j}")

javax vs java package

java.* packages are the core Java language packages, meaning that programmers using the Java language had to use them in order to make any worthwhile use of the java language.

javax.* packages are optional packages, which provides a standard, scalable way to make custom APIs available to all applications running on the Java platform.

Sending emails with Javascript

The problem with the very idea is that the user has to have an email client, which is not the case if he rely on webmails, which is the case for many users. (at least there was no turn-around to redirect to this webmail when I investigated the issue a dozen years ago).

That's why the normal solution is to rely on php mail() for sending emails (server-side, then).

But if nowadays "email client" is always set, automatically, potentially to a webmail client, I'll be happy to know.

mysql -> insert into tbl (select from another table) and some default values

If you want to insert all the columns then

insert into def select * from abc;

here the number of columns in def should be equal to abc.

if you want to insert the subsets of columns then

insert into def (col1,col2, col3 ) select scol1,scol2,scol3 from abc; 

if you want to insert some hardcorded values then

insert into def (col1, col2,col3) select 'hardcoded value',scol2, scol3 from abc;

Refresh Excel VBA Function Results

Okay, found this one myself. You can use Ctrl+Alt+F9 to accomplish this.

Why aren't variable-length arrays part of the C++ standard?

There are situations where allocating heap memory is very expensive compared to the operations performed. An example is matrix math. If you work with smallish matrices say 5 to 10 elements and do a lot of arithmetics the malloc overhead will be really significant. At the same time making the size a compile time constant does seem very wasteful and inflexible.

I think that C++ is so unsafe in itself that the argument to "try to not add more unsafe features" is not very strong. On the other hand, as C++ is arguably the most runtime efficient programming language features which makes it more so are always useful: People who write performance critical programs will to a large extent use C++, and they need as much performance as possible. Moving stuff from heap to stack is one such possibility. Reducing the number of heap blocks is another. Allowing VLAs as object members would one way to achieve this. I'm working on such a suggestion. It is a bit complicated to implement, admittedly, but it seems quite doable.

Delete files older than 10 days using shell script in Unix

If you can afford working via the file data, you can do

find -mmin +14400 -delete

How do I join two SQLite tables in my Android application?

An alternate way is to construct a view which is then queried just like a table. In many database managers using a view can result in better performance.

CREATE VIEW xyz SELECT q.question, a.alternative  
   FROM tbl_question AS q, tbl_alternative AS a
  WHERE q.categoryid = a.categoryid 
    AND q._id = a.questionid;

This is from memory so there may be some syntactic issues. http://www.sqlite.org/lang_createview.html

I mention this approach because then you can use SQLiteQueryBuilder with the view as you implied that it was preferred.

How do I set the path to a DLL file in Visual Studio?

In your Project properties(Right click on project, click on property button) ? Configuration Properties ? Build Events ? Post Build Events ? Command Line.

Edit and add one instruction to command line. for example copy botan.dll from source path to location where is being executed the program.

copy /Y "$(SolutionDir)ProjectDirs\x64\Botan\lib\botan.dll" "$(TargetDir)"

Project Properties

Convert List<T> to ObservableCollection<T> in WP7

Use this:

List<Class1> myList;
ObservableCollection<Class1> myOC = new ObservableCollection<Class1>(myList);

Finding length of char array

If anyone is looking for a quick fix for this, here's how you do it.

while (array[i] != '\0') i++;

The variable i will hold the used length of the array, not the entire initialized array. I know it's a late post, but it may help someone.

How to get unique values in an array

Another thought of this question. Here is what I did to achieve this with fewer code.

_x000D_
_x000D_
var distinctMap = {};_x000D_
var testArray = ['John', 'John', 'Jason', 'Jason'];_x000D_
for (var i = 0; i < testArray.length; i++) {_x000D_
  var value = testArray[i];_x000D_
  distinctMap[value] = '';_x000D_
};_x000D_
var unique_values = Object.keys(distinctMap);_x000D_
_x000D_
console.log(unique_values);
_x000D_
_x000D_
_x000D_

Insert/Update Many to Many Entity Framework . How do I do it?

Try this one for Updating:

[HttpPost]
public ActionResult Edit(Models.MathClass mathClassModel)
{
    //get current entry from db (db is context)
    var item = db.Entry<Models.MathClass>(mathClassModel);

    //change item state to modified
    item.State = System.Data.Entity.EntityState.Modified;

    //load existing items for ManyToMany collection
    item.Collection(i => i.Students).Load();

    //clear Student items          
    mathClassModel.Students.Clear();

    //add Toner items
    foreach (var studentId in mathClassModel.SelectedStudents)
    {
        var student = db.Student.Find(int.Parse(studentId));
        mathClassModel.Students.Add(student);
    }                

    if (ModelState.IsValid)
    {
       db.SaveChanges();
       return RedirectToAction("Index");
    }

    return View(mathClassModel);
}

Can I perform a DNS lookup (hostname to IP address) using client-side Javascript?

There's no notion of hosts or ip-addresses in the javascript standard library. So you'll have to access some external service to look up hostnames for you.

I recommend hosting a cgi-bin which looks up the ip-address of a hostname and access that via javascript.

Specifying content of an iframe instead of the src attribute to a page

You can .write() the content into the iframe document. Example:

<iframe id="FileFrame" src="about:blank"></iframe>

<script type="text/javascript">
   var doc = document.getElementById('FileFrame').contentWindow.document;
   doc.open();
   doc.write('<html><head><title></title></head><body>Hello world.</body></html>');
   doc.close();
</script>

What does axis in pandas mean?

one of easy ways to remember axis 1 (columns), vs axis 0 (rows) is the output you expect.

  • if you expect an output for each row you use axis='columns',
  • on the other hand if you want an output for each column you use axis='rows'.

How to listen state changes in react.js?

I haven't used Angular, but reading the link above, it seems that you're trying to code for something that you don't need to handle. You make changes to state in your React component hierarchy (via this.setState()) and React will cause your component to be re-rendered (effectively 'listening' for changes). If you want to 'listen' from another component in your hierarchy then you have two options:

  1. Pass handlers down (via props) from a common parent and have them update the parent's state, causing the hierarchy below the parent to be re-rendered.
  2. Alternatively, to avoid an explosion of handlers cascading down the hierarchy, you should look at the flux pattern, which moves your state into data stores and allows components to watch them for changes. The Fluxxor plugin is very useful for managing this.

Batch command to move files to a new directory

Something like this might help:

SET Today=%Date:~10,4%%Date:~4,2%%Date:~7,2%
mkdir C:\Test\Backup-%Today%
move C:\Test\Log\*.* C:\Test\Backup-%Today%\
SET Today=

The important part is the first line. It takes the output of the internal DATE value and parses it into an environmental variable named Today, in the format CCYYMMDD, as in '20110407`.

The %Date:~10,4% says to extract a *substring of the Date environmental variable 'Thu 04/07/2011' (built in - type echo %Date% at a command prompt) starting at position 10 for 4 characters (2011). It then concatenates another substring of Date: starting at position 4 for 2 chars (04), and then concats two additional characters starting at position 7 (07).

*The substring value starting points are 0-based.

You may need to adjust these values depending on the date format in your locale, but this should give you a starting point.

Git commit -a "untracked files"?

As the name suggests 'untracked files' are the files which are not being tracked by git. They are not in your staging area, and were not part of any previous commits. If you want them to be versioned (or to be managed by git) you can do so by telling 'git' by using 'git add'. Check this chapter Recording Changes to the Repository in the Progit book which uses a nice visual to provide a good explanation about recording changes to git repo and also explaining the terms 'tracked' and 'untracked'.

Delete directories recursively in Java

Guava provides a one-liner: MoreFiles.deleteRecursively().

Unlike many of the examples shared, it accounts for symbolic links and will not (by default) delete files outside the provided path.

Dynamically Fill Jenkins Choice Parameter With Git Branches In a Specified Repo

We can eliminate the unnecessary file read/write by using text. My complete solution is the following:

proc1 = ['/bin/bash', '-c', 
  "/usr/bin/git ls-remote --heads ssh://repo_url.git"].execute()
proc2 = ['/bin/bash', '-c', 
  "/usr/bin/awk ' { gsub(/refs\\/heads\\//, \"\"); print \$2 }' "].execute()
all = proc1 | proc2

choices = all.text
return choices.split().toList();

ImportError: No module named 'google'

got this from cloud service documentation

pip install --upgrade google-cloud-translate

Worked for me !

How do I compile and run a program in Java on my Mac?

Download and install Eclipse, and you're good to go.
http://www.eclipse.org/downloads/

Apple provides its own version of Java, so make sure it's up-to-date.
http://developer.apple.com/java/download/


Eclipse is an integrated development environment. It has many features, but the ones that are relevant for you at this stage is:

  • The source code editor
    • With syntax highlighting, colors and other visual cues
    • Easy cross-referencing to the documentation to facilitate learning
  • Compiler
    • Run the code with one click
    • Get notified of errors/mistakes as you go

As you gain more experience, you'll start to appreciate the rest of its rich set of features.

Auto-Submit Form using JavaScript

Try using document.getElementById("myForm") instead of document.myForm.

<script>
var auto_refresh = setInterval(function() { submitform(); }, 10000);

function submitform()
{
  alert('test');
  document.getElementById("myForm").submit();
}
</script>

Angular.js directive dynamic templateURL

Thanks to @pgregory, I could resolve my problem using this directive for inline editing

.directive("superEdit", function($compile){
    return{
        link: function(scope, element, attrs){
            var colName = attrs["superEdit"];
            alert(colName);

            scope.getContentUrl = function() {
                if (colName == 'Something') {
                    return 'app/correction/templates/lov-edit.html';
                }else {
                    return 'app/correction/templates/simple-edit.html';
                }
            }

            var template = '<div ng-include="getContentUrl()"></div>';

            var linkFn = $compile(template);
            var content = linkFn(scope);
            element.append(content);
        }
    }
})

How to force two figures to stay on the same page in LaTeX?

Try using the float package and then the [H] option for your figure.

\usepackage{float}

...

\begin{figure}[H]
\centering
\includegraphics{fig1}
\caption{Write some caption here}\label{fig1}
\end{figure}

as already suggested by this insightful answer!

https://tex.stackexchange.com/questions/8625/force-figure-placement-in-text

GROUP_CONCAT comma separator - MySQL

Looks like you're missing the SEPARATOR keyword in the GROUP_CONCAT function.

GROUP_CONCAT(artists.artistname SEPARATOR '----')

The way you've written it, you're concatenating artists.artistname with the '----' string using the default comma separator.

Get full path without filename from path that includes filename

Use GetParent() as shown, works nicely. Add error checking as you need.

var fn = openFileDialogSapTable.FileName;
var currentPath = Path.GetFullPath( fn );
currentPath = Directory.GetParent(currentPath).FullName;

Plotting in a non-blocking way with Matplotlib

The Python package drawnow allows to update a plot in real time in a non blocking way.
It also works with a webcam and OpenCV for example to plot measures for each frame.
See the original post.

CodeIgniter 500 Internal Server Error

I know I am late, but this will help someone.

Check if rewrite engine is enabled.

If not, enable rewrite engine and restart server.

sudo a2enmod rewrite
sudo service apache2 restart

Split an NSString to access one particular piece

Use [myString componentsSeparatedByString:@"/"]

How do you programmatically set an attribute?

Usually, we define classes for this.

class XClass( object ):
   def __init__( self ):
       self.myAttr= None

x= XClass()
x.myAttr= 'magic'
x.myAttr

However, you can, to an extent, do this with the setattr and getattr built-in functions. However, they don't work on instances of object directly.

>>> a= object()
>>> setattr( a, 'hi', 'mom' )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'hi'

They do, however, work on all kinds of simple classes.

class YClass( object ):
    pass

y= YClass()
setattr( y, 'myAttr', 'magic' )
y.myAttr

vim line numbers - how to have them on by default?

If you don't want to add/edit .vimrc, you can start with

vi "+set number" /path/to/file

Undo a Git merge that hasn't been pushed yet

With git reflog check which commit is one prior the merge (git reflog will be a better option than git log). Then you can reset it using:

git reset --hard commit_sha

There's also another way:

git reset --hard HEAD~1

It will get you back 1 commit.

Be aware that any modified and uncommitted/unstashed files will be reset to their unmodified state. To keep them either stash changes away or see --merge option below.


As @Velmont suggested below in his answer, in this direct case using:

git reset --hard ORIG_HEAD

might yield better results, as it should preserve your changes. ORIG_HEAD will point to a commit directly before merge has occurred, so you don't have to hunt for it yourself.


A further tip is to use the --merge switch instead of --hard since it doesn't reset files unnecessarily:

git reset --merge ORIG_HEAD

--merge

Resets the index and updates the files in the working tree that are different between <commit> and HEAD, but keeps those which are different between the index and working tree (i.e. which have changes which have not been added).

What's the best way to iterate an Android Cursor?

The Do/While solution is more elegant, but if you do use just the While solution posted above, without the moveToPosition(-1) you will miss the first element (at least on the Contact query).

I suggest:

if (cursor.getCount() > 0) {
    cursor.moveToPosition(-1);
    while (cursor.moveToNext()) {
          <do stuff>
    }
}

Binding a WPF ComboBox to a custom list

You set the DisplayMemberPath and the SelectedValuePath to "Name", so I assume that you have a class PhoneBookEntry with a public property Name.

Have you set the DataContext to your ConnectionViewModel object?

I copied you code and made some minor modifications, and it seems to work fine. I can set the viewmodels PhoneBookEnty property and the selected item in the combobox changes, and I can change the selected item in the combobox and the view models PhoneBookEntry property is set correctly.

Here is my XAML content:

<Window x:Class="WpfApplication6.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="300" Width="300">
<Grid>
    <StackPanel>
        <Button Click="Button_Click">asdf</Button>
        <ComboBox ItemsSource="{Binding Path=PhonebookEntries}"
                  DisplayMemberPath="Name"
                  SelectedValuePath="Name"
                  SelectedValue="{Binding Path=PhonebookEntry}" />
    </StackPanel>
</Grid>
</Window>

And here is my code-behind:

namespace WpfApplication6
{

    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            ConnectionViewModel vm = new ConnectionViewModel();
            DataContext = vm;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            ((ConnectionViewModel)DataContext).PhonebookEntry = "test";
        }
    }

    public class PhoneBookEntry
    {
        public string Name { get; set; }

        public PhoneBookEntry(string name)
        {
            Name = name;
        }

        public override string ToString()
        {
            return Name;
        }
    }

    public class ConnectionViewModel : INotifyPropertyChanged
    {
        public ConnectionViewModel()
        {
            IList<PhoneBookEntry> list = new List<PhoneBookEntry>();
            list.Add(new PhoneBookEntry("test"));
            list.Add(new PhoneBookEntry("test2"));
            _phonebookEntries = new CollectionView(list);
        }

        private readonly CollectionView _phonebookEntries;
        private string _phonebookEntry;

        public CollectionView PhonebookEntries
        {
            get { return _phonebookEntries; }
        }

        public string PhonebookEntry
        {
            get { return _phonebookEntry; }
            set
            {
                if (_phonebookEntry == value) return;
                _phonebookEntry = value;
                OnPropertyChanged("PhonebookEntry");
            }
        }

        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
        public event PropertyChangedEventHandler PropertyChanged;
    }
}

Edit: Geoffs second example does not seem to work, which seems a bit odd to me. If I change the PhonebookEntries property on the ConnectionViewModel to be of type ReadOnlyCollection, the TwoWay binding of the SelectedValue property on the combobox works fine.

Maybe there is an issue with the CollectionView? I noticed a warning in the output console:

System.Windows.Data Warning: 50 : Using CollectionView directly is not fully supported. The basic features work, although with some inefficiencies, but advanced features may encounter known bugs. Consider using a derived class to avoid these problems.

Edit2 (.NET 4.5): The content of the DropDownList can be based on ToString() and not of DisplayMemberPath, while DisplayMemberPath specifies the member for the selected and displayed item only.

Read String line by line

You can also use the split method of String:

String[] lines = myString.split(System.getProperty("line.separator"));

This gives you all lines in a handy array.

I don't know about the performance of split. It uses regular expressions.

Map.Entry: How to use it?

Map.Entry interface helps us iterating a Map class

Check this simple example:

public class MapDemo {
    public static void main(String[] args) {
     Map<Integer,String> map=new HashMap();
     map.put(1, "Kamran");
        map.put(2, "Ali");
        map.put(3, "From");
        map.put(4, "Dir");
        map.put(5, "Lower");
        for(Map.Entry m:map.entrySet()){
        System.out.println(m.getKey()+"  "+m.getValue());
        }
    }
}

How to use the ProGuard in Android Studio?

Try renaming your 'proguard-rules.txt' file to 'proguard-android.txt' and remove the reference to 'proguard-rules.txt' in your gradle file. The getDefaultProguardFile(...) call references a different default proguard file, one provided by Google and not that in your project. So remove this as well, so that here the gradle file reads:

buildTypes {
    release {
        runProguard true
        proguardFile 'proguard-android.txt'
    }
}

C - casting int to char and append char to char

You can use itoa function to convert the integer to a string.

You can use strcat function to append characters in a string at the end of another string.

If you want to convert a integer to a character, just do the following -

int a = 65;
char c = (char) a;

Note that since characters are smaller in size than integer, this casting may cause a loss of data. It's better to declare the character variable as unsigned in this case (though you may still lose data).

To do a light reading about type conversion, go here.

If you are still having trouble, comment on this answer.

Edit

Go here for a more suitable example of joining characters.

Also some more useful link is given below -

  1. http://www.cplusplus.com/reference/clibrary/cstring/strncat/
  2. http://www.cplusplus.com/reference/clibrary/cstring/strcat/

Second Edit

char msg[200];
int msgLength;
char rankString[200];

........... // Your message has arrived
msgLength = strlen(msg);
itoa(rank, rankString, 10); // I have assumed rank is the integer variable containing the rank id

strncat( msg, rankString, (200 - msgLength) );  // msg now contains previous msg + id

// You may loose some portion of id if message length + id string length is greater than 200

Third Edit

Go to this link. Here you will find an implementation of itoa. Use that instead.

How to download/checkout a project from Google Code in Windows?

If you don't want to install TortoiseSVN, you can simply install 'Subversion for Windows' from here:

http://sourceforge.net/projects/win32svn/

After installing, just open up a command prompt, go the folder you want to download into, then past in the checkout command as indicated on the project's 'source' page. E.g.

svn checkout http://projectname.googlecode.com/svn/trunk/ projectname-read-only

Note the space between the URL and the last string is intentional, the last string is the folder name into which the source will be downloaded.

ERROR 2003 (HY000): Can't connect to MySQL server (111)

Check that your remote host (i.e. the web hosting server you're trying to connect FROM) allows OUTGOING traffic on port 3306.

I saw the (100) error in this situation. I could connect from my PC/Mac, but not from my website. The MySQL instance was accessible via the internet, but my hosting company wasn't allowing my website to connect to the database on port 3306.

Once I asked my hosting company to open my web hosting account up to outgoing traffic on port 3306, my website could connect to my remote database.

Combine hover and click functions (jQuery)?

Use basic programming composition: create a method and pass the same function to click and hover as a callback.

var hoverOrClick = function () {
    // do something common
}
$('#target').click(hoverOrClick).hover(hoverOrClick);

Second way: use bindon:

$('#target').on('click mouseover', function () {
    // Do something for both
});

jQuery('#target').bind('click mouseover', function () {
    // Do something for both
});

Contains case insensitive

To do a better search use the following code,

var myFav   = "javascript";
var theList = "VB.NET, C#, PHP, Python, JavaScript, and Ruby";

// Check for matches with the plain vanilla indexOf() method:
alert( theList.indexOf( myFav ) );

// Now check for matches in lower-cased strings:
alert( theList.toLowerCase().indexOf( myFav.toLowerCase() ) );

In the first alert(), JavaScript returned "-1" - in other words, indexOf() did not find a match: this is simply because "JavaScript" is in lowercase in the first string, and properly capitalized in the second. To perform case-insensitive searches with indexOf(), you can make both strings either uppercase or lowercase. This means that, as in the second alert(), JavaScript will only check for the occurrence of the string you are looking for, capitalization ignored.

Reference, http://freewebdesigntutorials.com/javaScriptTutorials/jsStringObject/indexOfMethod.htm

Read file content from S3 bucket with boto3

When you want to read a file with a different configuration than the default one, feel free to use either mpu.aws.s3_read(s3path) directly or the copy-pasted code:

def s3_read(source, profile_name=None):
    """
    Read a file from an S3 source.

    Parameters
    ----------
    source : str
        Path starting with s3://, e.g. 's3://bucket-name/key/foo.bar'
    profile_name : str, optional
        AWS profile

    Returns
    -------
    content : bytes

    botocore.exceptions.NoCredentialsError
        Botocore is not able to find your credentials. Either specify
        profile_name or add the environment variables AWS_ACCESS_KEY_ID,
        AWS_SECRET_ACCESS_KEY and AWS_SESSION_TOKEN.
        See https://boto3.readthedocs.io/en/latest/guide/configuration.html
    """
    session = boto3.Session(profile_name=profile_name)
    s3 = session.client('s3')
    bucket_name, key = mpu.aws._s3_path_split(source)
    s3_object = s3.get_object(Bucket=bucket_name, Key=key)
    body = s3_object['Body']
    return body.read()

How do I check if file exists in Makefile so I can delete it?

It's strange to see so many people using shell scripting for this. I was looking for a way to use native makefile syntax, because I'm writing this outside of any target. You can use the wildcard function to check if file exists:

 ifeq ($(UNAME),Darwin)
     SHELL := /opt/local/bin/bash
     OS_X  := true
 else ifneq (,$(wildcard /etc/redhat-release))
     OS_RHEL := true
 else
     OS_DEB  := true
     SHELL := /bin/bash
 endif 

Update:

I found a way which is really working for me:

ifneq ("$(wildcard $(PATH_TO_FILE))","")
    FILE_EXISTS = 1
else
    FILE_EXISTS = 0
endif

How do I pass options to the Selenium Chrome driver using Python?

Code which disable chrome extensions for ones, who uses DesiredCapabilities to set browser flags :

desired_capabilities['chromeOptions'] = {
    "args": ["--disable-extensions"],
    "extensions": []
}
webdriver.Chrome(desired_capabilities=desired_capabilities)

Output a NULL cell value in Excel

As you've indicated, you can't output NULL in an excel formula. I think this has to do with the fact that the formula itself causes the cell to not be able to be NULL. "" is the next best thing, but sometimes it's useful to use 0.

--EDIT--

Based on your comment, you might want to check out this link. http://peltiertech.com/WordPress/mind-the-gap-charting-empty-cells/

It goes in depth on the graphing issues and what the various values represent, and how to manipulate their output on a chart.

I'm not familiar with VSTO I'm afraid. So I won't be much help there. But if you are really placing formulas in the cell, then there really is no way. ISBLANK() only tests to see if a cell is blank or not, it doesn't have a way to make it blank. It's possible to write code in VBA (and VSTO I imagine) that would run on a worksheet_change event and update the various values instead of using formulas. But that would be cumbersome and performance would take a hit.

Must JDBC Resultsets and Statements be closed separately although the Connection is closed afterwards?

I'm now using Oracle with Java. Here my point of view :

You should close ResultSet and Statement explicitly because Oracle has problems previously with keeping the cursors open even after closing the connection. If you don't close the ResultSet (cursor) it will throw an error like Maximum open cursors exceeded.

I think you may encounter with the same problem with other databases you use.

Here is tutorial Close ResultSet when finished:

Close ResultSet when finished

Close ResultSet object as soon as you finish working with ResultSet object even though Statement object closes the ResultSet object implicitly when it closes, closing ResultSet explicitly gives chance to garbage collector to recollect memory as early as possible because ResultSet object may occupy lot of memory depending on query.

ResultSet.close();

Delete rows with blank values in one particular column

It is the same construct - simply test for empty strings rather than NA:

Try this:

df <- df[-which(df$start_pc == ""), ]

In fact, looking at your code, you don't need the which, but use the negation instead, so you can simplify it to:

df <- df[!(df$start_pc == ""), ]
df <- df[!is.na(df$start_pc), ]

And, of course, you can combine these two statements as follows:

df <- df[!(df$start_pc == "" | is.na(df$start_pc)), ]

And simplify it even further with with:

df <- with(df, df[!(start_pc == "" | is.na(start_pc)), ])

You can also test for non-zero string length using nzchar.

df <- with(df, df[!(nzchar(start_pc) | is.na(start_pc)), ])

Disclaimer: I didn't test any of this code. Please let me know if there are syntax errors anywhere

What is the equivalent of Select Case in Access SQL?

You could do below:

select
iif ( OpeningBalance>=0 And OpeningBalance<=500 , 20, 

                  iif ( OpeningBalance>=5001 And OpeningBalance<=10000 , 30, 

                       iif ( OpeningBalance>=10001 And OpeningBalance<=20000 , 40, 

50 ) ) ) as commission
from table

Playing .mp3 and .wav in Java?

To give the readers another alternative, I am suggesting JACo MP3 Player library, a cross platform java mp3 player.

Features:

  • very low CPU usage (~2%)
  • incredible small library (~90KB)
  • doesn't need JMF (Java Media Framework)
  • easy to integrate in any application
  • easy to integrate in any web page (as applet).

For a complete list of its methods and attributes you can check its documentation here.

Sample code:

import jaco.mp3.player.MP3Player;
import java.io.File;

public class Example1 {
  public static void main(String[] args) {
    new MP3Player(new File("test.mp3")).play();
  }
}

For more details, I created a simple tutorial here that includes a downloadable sourcecode.

How to scroll to an element?

After reading through manny forums found a really easy solution.

I use redux-form. Urgo mapped redux-from fieldToClass. Upon error I navigate to the first error on the list of syncErrors.

No refs and no third party modules. Just simple querySelector & scrollIntoView

handleToScroll = (field) => {

    const fieldToClass = {
        'vehicleIdentifier': 'VehicleIdentifier',
        'locationTags': 'LocationTags',
        'photos': 'dropzoneContainer',
        'description': 'DescriptionInput',
        'clientId': 'clientId',
        'driverLanguage': 'driverLanguage',
        'deliveryName': 'deliveryName',
        'deliveryPhone': 'deliveryPhone',
        "deliveryEmail": 'deliveryEmail',
        "pickupAndReturn": "PickupAndReturn",
        "payInCash": "payInCash",
    }

document?.querySelector(`.${fieldToClasses[field]}`)
         .scrollIntoView({ behavior: "smooth" })

}

ng-if check if array is empty

In my experience, doing this on the HTML template proved difficult so I decided to use an event to call a function on TS and then check the condition. If true make condition equals to true and then use that variable on the ngIf on HTML

    emptyClause(array:any) {


        if (array.length === 0) {
            // array empty or does not exist

            this.emptyMessage=false;

    }else{

            this.emptyMessage=true;
        }
}

HTML

        <div class="row">

        <form>
            <div class="col-md-1 col-sm-1 col-xs-1"></div>
            <div class="col-md-10 col-sm-10 col-xs-10">
        <div [hidden]="emptyMessage" class="alert alert-danger">

            No Clauses Have Been Identified For the Search Criteria

        </div>
            </div>
            <div class="col-md-1 col-sm-1 col-xs-1"></div>
        </form>

sprintf like functionality in Python

To insert into a very long string it is nice to use names for the different arguments, instead of hoping they are in the right positions. This also makes it easier to replace multiple recurrences.

>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'

Taken from Format examples, where all the other Format-related answers are also shown.

How many characters can a Java String have?

Integer.MAX_VALUE is max size of string + depends of your memory size but the Problem on sphere's online judge you don't have to use those functions

How to do relative imports in Python?

This is unfortunately a sys.path hack, but it works quite well.

I encountered this problem with another layer: I already had a module of the specified name, but it was the wrong module.

what I wanted to do was the following (the module I was working from was module3):

mymodule\
   __init__.py
   mymodule1\
      __init__.py
      mymodule1_1
   mymodule2\
      __init__.py
      mymodule2_1


import mymodule.mymodule1.mymodule1_1  

Note that I have already installed mymodule, but in my installation I do not have "mymodule1"

and I would get an ImportError because it was trying to import from my installed modules.

I tried to do a sys.path.append, and that didn't work. What did work was a sys.path.insert

if __name__ == '__main__':
    sys.path.insert(0, '../..')

So kind of a hack, but got it all to work! So keep in mind, if you want your decision to override other paths then you need to use sys.path.insert(0, pathname) to get it to work! This was a very frustrating sticking point for me, allot of people say to use the "append" function to sys.path, but that doesn't work if you already have a module defined (I find it very strange behavior)

How to group time by hour or by 10 minutes

declare @interval tinyint
set @interval = 30
select dateadd(minute,(datediff(minute,0,[DateInsert])/@interval)*@interval,0), sum(Value_Transaction)
from Transactions
group by dateadd(minute,(datediff(minute,0,[DateInsert])/@interval)*@interval,0)

Improving bulk insert performance in Entity framework

Currently there is no better way, however there may be a marginal improvement by moving SaveChanges inside for loop for probably 10 items.

int i = 0;

foreach (Employees item in sequence)
{
   t = new Employees ();
   t.Text = item.Text;
   dataContext.Employees.AddObject(t);   

   // this will add max 10 items together
   if((i % 10) == 0){
       dataContext.SaveChanges();
       // show some progress to user based on
       // value of i
   }
   i++;
}
dataContext.SaveChanges();

You can adjust 10 to be closer to better performance. It will not greatly improve speed but it will allow you to show some progress to user and make it more user friendly.

Difference between frontend, backend, and middleware in web development

Frontend refers to the client-side, whereas backend refers to the server-side of the application. Both are crucial to web development, but their roles, responsibilities and the environments they work in are totally different. Frontend is basically what users see whereas backend is how everything works

Get div tag scroll position using JavaScript

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function scollPos() {
            var div = document.getElementById("myDiv").scrollTop;
            document.getElementById("pos").innerHTML = div;
        }
    </script>
</head>
<body>
    <form id="form1">
    <div id="pos">
    </div>
    <div id="myDiv" style="overflow: auto; height: 200px; width: 200px;" onscroll="scollPos();">
        Place some large content here
    </div>
    </form>
</body>
</html>

What is the best IDE to develop Android apps in?

I advise Android bundle for TextMate: https://github.com/nesterow/Android.tmbundle It's lightweight and easy to use. There is no intellisense, but actually it just makes you remember namespaces better. :)

jquery beforeunload when closing (not leaving) the page?

You can do this by using JQuery.

For example ,

<a href="your URL" id="navigate"> click here </a>

Your JQuery will be,

$(document).ready(function(){

    $('a').on('mousedown', stopNavigate);

    $('a').on('mouseleave', function () {
           $(window).on('beforeunload', function(){
                  return 'Are you sure you want to leave?';
           });
    });
});

function stopNavigate(){    
    $(window).off('beforeunload');
}

And to get the Leave message alert will be,

$(window).on('beforeunload', function(){
      return 'Are you sure you want to leave?';
});

$(window).on('unload', function(){

         logout();

});

This solution works in all browsers and I have tested it.

how to compare two string dates in javascript?

You can simply compare 2 strings

function isLater(dateString1, dateString2) {
  return dateString1 > dateString2
}

Then

isLater("2012-12-01", "2012-11-01")

returns true while

isLater("2012-12-01", "2013-11-01")

returns false

How to compile and run C in sublime text 3?

try to write a shell script named run.sh in your project foler

#!/bin/bash
./YOUR_EXECUTIVE_FILE
...AND OTHER THING

and make a Build System to compile and execute it:

{
      "shell_cmd": "make all && ./run.sh"
}

don't forget $chmod +x run.sh

do one thing and do it well:)

What is console.log in jQuery?

It has nothing to do with jQuery, it's just a handy js method built into modern browsers.

Think of it as a handy alternative to debugging via window.alert()

Change the mouse cursor on mouse over to anchor-like style

Assuming your div has an id="myDiv", add the following to your CSS. The cursor: pointer specifies that the cursor should be the same hand icon that is use for anchors (hyperlinks):

CSS to Add

#myDiv
{
    cursor: pointer;
}

You can simply add the cursor style to your div's HTML like this:

<div style="cursor: pointer">

</div>

EDIT:

If you are determined to use jQuery for this, then add the following line to your $(document).ready() or body onload: (replace myClass with whatever class all of your divs share)

$('.myClass').css('cursor', 'pointer');

Usage of $broadcast(), $emit() And $on() in AngularJS

$emit

It dispatches an event name upwards through the scope hierarchy and notify to the registered $rootScope.Scope listeners. The event life cycle starts at the scope on which $emit was called. The event traverses upwards toward the root scope and calls all registered listeners along the way. The event will stop propagating if one of the listeners cancels it.

$broadcast

It dispatches an event name downwards to all child scopes (and their children) and notify to the registered $rootScope.Scope listeners. The event life cycle starts at the scope on which $broadcast was called. All listeners for the event on this scope get notified. Afterwards, the event traverses downwards toward the child scopes and calls all registered listeners along the way. The event cannot be canceled.

$on

It listen on events of a given type. It can catch the event dispatched by $broadcast and $emit.


Visual demo:

Demo working code, visually showing scope tree (parent/child relationship):
http://plnkr.co/edit/am6IDw?p=preview

Demonstrates the method calls:

  $scope.$on('eventEmitedName', function(event, data) ...
  $scope.broadcastEvent
  $scope.emitEvent

Watching variables in SSIS during debug

Drag the variable from Variables pane to Watch pane and voila!

ActiveMQ or RabbitMQ or ZeroMQ or

Few applications have as many tuning configurations as ActiveMQ. Some features that make ActiveMQ stand out are:

Configurable Prefetch size. Configurable threading. Configurable failover. Configurable administrative notification to producers. ... details at:

http://activemq.net/blog http://activemq.apache.org

ORA-01031: insufficient privileges when selecting view

If the view is accessed via a stored procedure, the execute grant is insufficient to access the view. You must grant select explicitly.

simply type this

grant all on to public;

Regular Expressions and negating a whole character group

Yes its called negative lookahead. It goes like this - (?!regex here). So abc(?!def) will match abc not followed by def. So it'll match abce, abc, abck, etc.

Similarly there is positive lookahead - (?=regex here). So abc(?=def) will match abc followed by def.

There are also negative and positive lookbehind - (?<!regex here) and (?<=regex here) respectively

One point to note is that the negative lookahead is zero-width. That is, it does not count as having taken any space.

So it may look like a(?=b)c will match "abc" but it won't. It will match 'a', then the positive lookahead with 'b' but it won't move forward into the string. Then it will try to match the 'c' with 'b' which won't work. Similarly ^a(?=b)b$ will match 'ab' and not 'abb' because the lookarounds are zero-width (in most regex implementations).

More information on this page

check if "it's a number" function in Oracle

One additional idea, mentioned here is to use a regular expression to check:

SELECT  foo 
FROM    bar
WHERE   REGEXP_LIKE (foo,'^[[:digit:]]+$');

The nice part is you do not need a separate PL/SQL function. The potentially problematic part is that a regular expression may not be the most efficient method for a large number of rows.

Regex pattern including all special characters

Please don't do that... little Unicode BABY ANGELs like this one are dying! ??? (? these are not images) (nor is the arrow!)

?

And you are killing 20 years of DOS :-) (the last smiley is called WHITE SMILING FACE... Now it's at 263A... But in ancient times it was ALT-1)

and his friend

?

BLACK SMILING FACE... Now it's at 263B... But in ancient times it was ALT-2

Try a negative match:

Pattern regex = Pattern.compile("[^A-Za-z0-9]");

(this will ok only A-Z "standard" letters and "standard" 0-9 digits.)

Calculate median in c#

Below code works: but not very efficient way. :(

static void Main(String[] args) {
        int n = Convert.ToInt32(Console.ReadLine());            
        int[] medList = new int[n];

        for (int x = 0; x < n; x++)
            medList[x] = int.Parse(Console.ReadLine());

        //sort the input array:
        //Array.Sort(medList);            
        for (int x = 0; x < n; x++)
        {
            double[] newArr = new double[x + 1];
            for (int y = 0; y <= x; y++)
                newArr[y] = medList[y];

            Array.Sort(newArr);
            int curInd = x + 1;
            if (curInd % 2 == 0) //even
            {
                int mid = (x / 2) <= 0 ? 0 : (newArr.Length / 2);
                if (mid > 1) mid--;
                double median = (newArr[mid] + newArr[mid+1]) / 2;
                Console.WriteLine("{0:F1}", median);
            }
            else //odd
            {
                int mid = (x / 2) <= 0 ? 0 : (newArr.Length / 2);
                double median = newArr[mid];
                Console.WriteLine("{0:F1}", median);
            }
        }

}

Good ways to sort a queryset? - Django

What about

import operator

auths = Author.objects.order_by('-score')[:30]
ordered = sorted(auths, key=operator.attrgetter('last_name'))

In Django 1.4 and newer you can order by providing multiple fields.
Reference: https://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by

order_by(*fields)

By default, results returned by a QuerySet are ordered by the ordering tuple given by the ordering option in the model’s Meta. You can override this on a per-QuerySet basis by using the order_by method.

Example:

ordered_authors = Author.objects.order_by('-score', 'last_name')[:30]

The result above will be ordered by score descending, then by last_name ascending. The negative sign in front of "-score" indicates descending order. Ascending order is implied.

How can I stage and commit all files, including newly added files, using a single command?

You can write a small script (look at Ian Clelland's answer) called git-commitall which uses several git commands to perform what you want to do.
Place this script in your anywhere in your $PATH. You can call it by git commitall ... very handy!

Found here (question and all answers unfortunately deleted, only visible with high reputation)

Precision String Format Specifier In Swift

I found String.localizedStringWithFormat to work quite well:

Example:

let value: Float = 0.33333
let unit: String = "mph"

yourUILabel.text = String.localizedStringWithFormat("%.2f %@", value, unit)

Split a large pandas dataframe

Use np.array_split:

Docstring:
Split an array into multiple sub-arrays.

Please refer to the ``split`` documentation.  The only difference
between these functions is that ``array_split`` allows
`indices_or_sections` to be an integer that does *not* equally
divide the axis.

In [1]: import pandas as pd

In [2]: df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
   ...:                           'foo', 'bar', 'foo', 'foo'],
   ...:                    'B' : ['one', 'one', 'two', 'three',
   ...:                           'two', 'two', 'one', 'three'],
   ...:                    'C' : randn(8), 'D' : randn(8)})

In [3]: print df
     A      B         C         D
0  foo    one -0.174067 -0.608579
1  bar    one -0.860386 -1.210518
2  foo    two  0.614102  1.689837
3  bar  three -0.284792 -1.071160
4  foo    two  0.843610  0.803712
5  bar    two -1.514722  0.870861
6  foo    one  0.131529 -0.968151
7  foo  three -1.002946 -0.257468

In [4]: import numpy as np
In [5]: np.array_split(df, 3)
Out[5]: 
[     A    B         C         D
0  foo  one -0.174067 -0.608579
1  bar  one -0.860386 -1.210518
2  foo  two  0.614102  1.689837,
      A      B         C         D
3  bar  three -0.284792 -1.071160
4  foo    two  0.843610  0.803712
5  bar    two -1.514722  0.870861,
      A      B         C         D
6  foo    one  0.131529 -0.968151
7  foo  three -1.002946 -0.257468]

How can I convert an Integer to localized month name in Java?

    public static void main(String[] args) {
    SimpleDateFormat format = new SimpleDateFormat("MMMMM", new Locale("en", "US"));
    System.out.println(format.format(new Date()));
}

How to initialize a JavaScript Date to a particular time zone

//For mumbai time diffrence is 5.5 hrs so
// city_time_diff=5.5 (change according to your city) 

let timee= Date.now()
    timee=timee+(3600000*city_time_diff); //Add our city time (in msec) 
    let new_date=new Date(timee)
console.log("My city time is: ",new_date);

An attempt was made to access a socket in a way forbidden by its access permissions

Not surprisingly, this error can arise when another process is listening on the desired port. This happened today when I started an instance of the Apache Web server, listening on its default port (80), having forgotten that I already had IIS 7 running, and listening on that port. This is well explained in Port 80 is being used by SYSTEM (PID 4), what is that? Better yet, that article points to Stop http.sys from listening on port 80 in Windows, which explains a very simple way to resolve it, with just a tad of help from an elevated command prompt and a one-line edit of my hosts file.

Change collations of all columns of all tables in SQL Server

Fixed length problem nvarchar (include max), included text and added NULL/NOT NULL.

USE [put your database name here];

begin tran

DECLARE @collate nvarchar(100);
DECLARE @table nvarchar(255);
DECLARE @column_name nvarchar(255);
DECLARE @column_id int;
DECLARE @data_type nvarchar(255);
DECLARE @max_length int;
DECLARE @max_length_str nvarchar(100);
DECLARE @is_nullable bit;
DECLARE @row_id int;
DECLARE @sql nvarchar(max);
DECLARE @sql_column nvarchar(max);

SET @collate = 'Latin1_General_CI_AS';

DECLARE local_table_cursor CURSOR FOR

SELECT [name]
FROM sysobjects
WHERE OBJECTPROPERTY(id, N'IsUserTable') = 1
ORDER BY [name]

OPEN local_table_cursor
FETCH NEXT FROM local_table_cursor
INTO @table

WHILE @@FETCH_STATUS = 0
BEGIN

    DECLARE local_change_cursor CURSOR FOR

    SELECT ROW_NUMBER() OVER (ORDER BY c.column_id) AS row_id
        , c.name column_name
        , t.Name data_type
        , col.CHARACTER_MAXIMUM_LENGTH
        , c.column_id
        , c.is_nullable
    FROM sys.columns c
    JOIN sys.types t ON c.system_type_id = t.system_type_id
    JOIN INFORMATION_SCHEMA.COLUMNS col on col.COLUMN_NAME = c.name and c.object_id = OBJECT_ID(col.TABLE_NAME)
    LEFT OUTER JOIN sys.index_columns ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id
    LEFT OUTER JOIN sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id
    WHERE c.object_id = OBJECT_ID(@table) AND (t.Name LIKE '%char%' OR t.Name LIKE '%text%') 
    AND c.collation_name <> @collate
    ORDER BY c.column_id

    OPEN local_change_cursor
    FETCH NEXT FROM local_change_cursor
    INTO @row_id, @column_name, @data_type, @max_length, @column_id, @is_nullable

    WHILE @@FETCH_STATUS = 0
    BEGIN

        set @max_length_str = @max_length
        IF (@max_length = -1) SET @max_length_str = 'max'
        IF (@max_length > 4000) SET @max_length_str = '4000'

        BEGIN TRY
            SET @sql =
            CASE 
                WHEN @data_type like '%text%' 
                THEN 'ALTER TABLE ' + @table + ' ALTER COLUMN [' + @column_name + '] ' + @data_type + ' COLLATE ' + @collate + ' ' + CASE WHEN @is_nullable = 0 THEN 'NOT NULL' ELSE 'NULL' END
                ELSE 'ALTER TABLE ' + @table + ' ALTER COLUMN [' + @column_name + '] ' + @data_type + '(' + @max_length_str + ') COLLATE ' + @collate + ' ' + CASE WHEN @is_nullable = 0 THEN 'NOT NULL' ELSE 'NULL' END
            END
            --PRINT @sql
            EXEC sp_executesql @sql
        END TRY
        BEGIN CATCH
          PRINT 'ERROR (' + @table + '): Some index or constraint rely on the column ' + @column_name + '. No conversion possible.'
          --PRINT @sql
        END CATCH

        FETCH NEXT FROM local_change_cursor
        INTO @row_id, @column_name, @data_type, @max_length, @column_id, @is_nullable

    END

    CLOSE local_change_cursor
    DEALLOCATE local_change_cursor

    FETCH NEXT FROM local_table_cursor
    INTO @table

END

CLOSE local_table_cursor
DEALLOCATE local_table_cursor

commit tran

GO

Notice : in case when you just need to change some specific collation use condition like this :

WHERE c.object_id = OBJECT_ID(@table) AND (t.Name LIKE '%char%' OR t.Name LIKE '%text%') 
    AND c.collation_name = 'collation to change'

e.g. NOT the : AND c.collation_name <> @collate

In my case, I had correct / specified collation of some columns and didn't want to change them.

Comparing the contents of two files in Sublime Text

UPDATE
(Given the upvotes, I feel there is a need for a complete step-by-step explanation...)

  1. In the Menu bar click on File->Open Folder...
  2. Select a folder (the actual folder does not really matter, this step is just to make the FOLDERS sidebar available)
  3. If there is no Side Bar shown yet, make it appear via View -> Side Bar -> Show Side Bar
  4. Use this FOLDERS-titled Side Bar to navigate to the first file you want to compare.
  5. Select it (click on it), hold down ctrl and select the second file.
  6. Having two files selected, right click on one of the two and select Diff Files...

There should be a new Tab now showing the comparison.


Original short answer:
Note that:

The "Diff files" only appears with the "folders" sidebar (to open a folder: File->Open Folder) , not with "open files" sidebar.

ViewPager and fragments — what's the right way to store fragment's state?

What is that BasePagerAdapter? You should use one of the standard pager adapters -- either FragmentPagerAdapter or FragmentStatePagerAdapter, depending on whether you want Fragments that are no longer needed by the ViewPager to either be kept around (the former) or have their state saved (the latter) and re-created if needed again.

Sample code for using ViewPager can be found here

It is true that the management of fragments in a view pager across activity instances is a little complicated, because the FragmentManager in the framework takes care of saving the state and restoring any active fragments that the pager has made. All this really means is that the adapter when initializing needs to make sure it re-connects with whatever restored fragments there are. You can look at the code for FragmentPagerAdapter or FragmentStatePagerAdapter to see how this is done.

Google Maps Android API v2 - Interactive InfoWindow (like in original android google maps)

For those who couldn't get choose007's answer up and running

If clickListener is not working properly at all times in chose007's solution, try to implement View.onTouchListener instead of clickListener. Handle touch event using any of the action ACTION_UP or ACTION_DOWN. For some reason, maps infoWindow causes some weird behaviour when dispatching to clickListeners.

infoWindow.findViewById(R.id.my_view).setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
          int action = MotionEventCompat.getActionMasked(event);
          switch (action){
                case MotionEvent.ACTION_UP:
                    Log.d(TAG,"a view in info window clicked" );
                    break;
                }
                return true;
          }

Edit : This is how I did it step by step

First inflate your own infowindow (global variable) somewhere in your activity/fragment. Mine is within fragment. Also insure that root view in your infowindow layout is linearlayout (for some reason relativelayout was taking full width of screen in infowindow)

infoWindow = (ViewGroup) getActivity().getLayoutInflater().inflate(R.layout.info_window, null);
/* Other global variables used in below code*/
private HashMap<Marker,YourData> mMarkerYourDataHashMap = new HashMap<>();
private GoogleMap mMap;
private MapWrapperLayout mapWrapperLayout;

Then in onMapReady callback of google maps android api (follow this if you donot know what onMapReady is Maps > Documentation - Getting Started )

   @Override
    public void onMapReady(GoogleMap googleMap) {
       /*mMap is global GoogleMap variable in activity/fragment*/
        mMap = googleMap;
       /*Some function to set map UI settings*/ 
        setYourMapSettings();

MapWrapperLayout initialization http://stackoverflow.com/questions/14123243/google-maps-android-api-v2- interactive-infowindow-like-in-original-android-go/15040761#15040761 39 - default marker height 20 - offset between the default InfoWindow bottom edge and it's content bottom edge */

        mapWrapperLayout.init(mMap, Utils.getPixelsFromDp(mContext, 39 + 20));

        /*handle marker clicks separately - not necessary*/
       mMap.setOnMarkerClickListener(this);

       mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
                @Override
                public View getInfoWindow(Marker marker) {
                    return null;
                }

            @Override
            public View getInfoContents(Marker marker) {
                YourData data = mMarkerYourDataHashMap.get(marker);
                setInfoWindow(marker,data);
                mapWrapperLayout.setMarkerWithInfoWindow(marker, infoWindow);
                return infoWindow;
            }
        });
    }

SetInfoWindow method

private void setInfoWindow (final Marker marker, YourData data)
            throws NullPointerException{
        if (data.getVehicleNumber()!=null) {
            ((TextView) infoWindow.findViewById(R.id.VehicelNo))
                    .setText(data.getDeviceId().toString());
        }
        if (data.getSpeed()!=null) {
            ((TextView) infoWindow.findViewById(R.id.txtSpeed))
                    .setText(data.getSpeed());
        }

        //handle dispatched touch event for view click
        infoWindow.findViewById(R.id.any_view).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = MotionEventCompat.getActionMasked(event);
                switch (action) {
                    case MotionEvent.ACTION_UP:
                        Log.d(TAG,"any_view clicked" );
                        break;
                }
                return true;
            }
        });

Handle marker click separately

    @Override
    public boolean onMarkerClick(Marker marker) {
        Log.d(TAG,"on Marker Click called");
        marker.showInfoWindow();
        CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(marker.getPosition())      // Sets the center of the map to Mountain View
                .zoom(10)
                .build();
        mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition),1000,null);
        return true;
    }

Python List & for-each access (Find/Replace in built-in list)

Answering this has been good, as the comments have led to an improvement in my own understanding of Python variables.

As noted in the comments, when you loop over a list with something like for member in my_list the member variable is bound to each successive list element. However, re-assigning that variable within the loop doesn't directly affect the list itself. For example, this code won't change the list:

my_list = [1,2,3]
for member in my_list:
    member = 42
print my_list

Output:

[1, 2, 3]

If you want to change a list containing immutable types, you need to do something like:

my_list = [1,2,3]
for ndx, member in enumerate(my_list):
    my_list[ndx] += 42
print my_list

Output:

[43, 44, 45]

If your list contains mutable objects, you can modify the current member object directly:

class C:
    def __init__(self, n):
        self.num = n
    def __repr__(self):
        return str(self.num)

my_list = [C(i) for i in xrange(3)]
for member in my_list:
    member.num += 42
print my_list

[42, 43, 44]

Note that you are still not changing the list, simply modifying the objects in the list.

You might benefit from reading Naming and Binding.

Is it possible to implement a Python for range loop without an iterator variable?

If do_something is a simple function or can be wrapped in one, a simple map() can do_something range(some_number) times:

# Py2 version - map is eager, so it can be used alone
map(do_something, xrange(some_number))

# Py3 version - map is lazy, so it must be consumed to do the work at all;
# wrapping in list() would be equivalent to Py2, but if you don't use the return
# value, it's wastefully creating a temporary, possibly huge, list of junk.
# collections.deque with maxlen 0 can efficiently run a generator to exhaustion without
# storing any of the results; the itertools consume recipe uses it for that purpose.
from collections import deque

deque(map(do_something, range(some_number)), 0)

If you want to pass arguments to do_something, you may also find the itertools repeatfunc recipe reads well:

To pass the same arguments:

from collections import deque
from itertools import repeat, starmap

args = (..., my args here, ...)

# Same as Py3 map above, you must consume starmap (it's a lazy generator, even on Py2)
deque(starmap(do_something, repeat(args, some_number)), 0)

To pass different arguments:

argses = [(1, 2), (3, 4), ...]

deque(starmap(do_something, argses), 0)

Error handling with PHPMailer

You can get more info about the error with the method $mail->ErrorInfo. For example:

if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}

This is an alternative to the exception model that you need to active with new PHPMailer(true). But if can use exception model, use it as @Phil Rykoff answer.

This comes from the main page of PHPMailer on github https://github.com/PHPMailer/PHPMailer.

Get the last inserted row ID (with SQL statement)

You can use:

SELECT IDENT_CURRENT('tablename')

to access the latest identity for a perticular table.

e.g. Considering following code:

INSERT INTO dbo.MyTable(columns....) VALUES(..........)

INSERT INTO dbo.YourTable(columns....) VALUES(..........)

SELECT IDENT_CURRENT('MyTable')

SELECT IDENT_CURRENT('YourTable')

This would yield to correct value for corresponding tables.

It returns the last IDENTITY value produced in a table, regardless of the connection that created the value, and regardless of the scope of the statement that produced the value.

IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope.

How to read file contents into a variable in a batch file?

To get all the lines of the file loaded into the variable, Delayed Expansion is needed, so do the following:

SETLOCAL EnableDelayedExpansion

for /f "Tokens=* Delims=" %%x in (version.txt) do set Build=!Build!%%x

There is a problem with some special characters, though especially ;, % and !

Make Div Draggable using CSS

Only using css techniques this does not seem possible to me. But you could use jqueryui draggable:

$('#drag_me').draggable();

fastest MD5 Implementation in JavaScript

Much faster hashing should be possible by calculating on graphic card (implement hashing algorithm in WebGL), as discussed there about SHA256: Is it possible to calculate sha256 hashes in the browser using the user's video card, eg. by using WebGL or Flash?

String.Format not work in TypeScript

You can declare it yourself quite easily:

interface StringConstructor {
    format: (formatString: string, ...replacement: any[]) => string;
}

String.format('','');

This is assuming that String.format is defined elsewhere. e.g. in Microsoft Ajax Toolkit : http://www.asp.net/ajaxlibrary/Reference.String-format-Function.ashx

How do you list the primary key of a SQL Server table?

Might be lately posted but hopefully this will help someone to see primary key list in sql server by using this t-sql query:

SELECT  schema_name(t.schema_id) AS [schema_name], t.name AS TableName,        
    COL_NAME(ic.OBJECT_ID,ic.column_id) AS PrimaryKeyColumnName,
    i.name AS PrimaryKeyConstraintName
FROM    sys.tables t 
INNER JOIN sys.indexes AS i  on t.object_id=i.object_id 
INNER JOIN  sys.index_columns AS ic ON  i.OBJECT_ID = ic.OBJECT_ID
                            AND i.index_id = ic.index_id 
WHERE OBJECT_NAME(ic.OBJECT_ID) = 'YourTableNameHere'

You can see the list of all foreign keys by using this query if you may want:

SELECT
f.name as ForeignKeyConstraintName
,OBJECT_NAME(f.parent_object_id) AS ReferencingTableName
,COL_NAME(fc.parent_object_id, fc.parent_column_id) AS ReferencingColumnName
,OBJECT_NAME (f.referenced_object_id) AS ReferencedTableName
,COL_NAME(fc.referenced_object_id, fc.referenced_column_id) AS 
 ReferencedColumnName  ,delete_referential_action_desc AS 
DeleteReferentialActionDesc ,update_referential_action_desc AS 
UpdateReferentialActionDesc
FROM sys.foreign_keys AS f
INNER JOIN sys.foreign_key_columns AS fc
ON f.object_id = fc.constraint_object_id
 --WHERE OBJECT_NAME(f.parent_object_id) = 'YourTableNameHere' 
 --If you want to know referecing table details 
 WHERE OBJECT_NAME(f.referenced_object_id) = 'YourTableNameHere' 
 --If you want to know refereced table details 
ORDER BY f.name

How to use UIVisualEffectView to Blur Image?

You can also use the interface builder to create these effects easily for simple situations. Since the z-values of the views will depend on the order they are listed in the Document Outline, you can drag a UIVisualEffectView onto the document outline before the view you want to blur. This automatically creates a nested UIView, which is the contentView property of the given UIVisualEffectView. Nest things within this view that you want to appear on top of the blur.

XCode6 beta5

You can also easily take advantage of the vibrancy UIVisualEffect, which will automatically create another nested UIVisualEffectView in the document outline with vibrancy enabled by default. You can then add a label or text view to the nested UIView (again, the contentView property of the UIVisualEffectView), to achieve the same effect that the "> slide to unlock" UI element.

enter image description here

How to insert values in table with foreign key using MySQL?

Case 1: Insert Row and Query Foreign Key

Here is an alternate syntax I use:

INSERT INTO tab_student 
   SET name_student = 'Bobby Tables',
       id_teacher_fk = (
       SELECT id_teacher
         FROM tab_teacher
        WHERE name_teacher = 'Dr. Smith')

I'm doing this in Excel to import a pivot table to a dimension table and a fact table in SQL so you can import to both department and expenses tables from the following:

enter image description here

Case 2: Insert Row and Then Insert Dependant Row

Luckily, MySQL supports LAST_INSERT_ID() exactly for this purpose.

INSERT INTO tab_teacher
   SET name_teacher = 'Dr. Smith';
INSERT INTO tab_student 
   SET name_student = 'Bobby Tables',
       id_teacher_fk = LAST_INSERT_ID()

commands not found on zsh

In your ~/.zsh config file include the path to your bash path file that contains your aliases. In my case it was including the line "source ~/.bash_profile" inside of ~/.zsh .

Using union and order by clause in mysql

A union query can only have one master ORDER BY clause, IIRC. To get this, in each query making up the greater UNION query, add a field that will be the one field you sort by for the UNION's ORDER BY.

For instance, you might have something like

SELECT field1, field2, '1' AS union_sort
UNION SELECT field1, field2, '2' AS union_sort
UNION SELECT field1, field2, '3' AS union_sort
ORDER BY union_sort

That union_sort field can be anything you may want to sort by. In this example, it just happens to put results from the first table first, second table second, etc.

Big-oh vs big-theta

Because my keyboard has an O key.
It does not have a T or an O key.

I suspect most people are similarly lazy and use O when they mean T because it's easier to type.

NameError: name 'datetime' is not defined

It can also be used as below:

from datetime import datetime
start_date = datetime(2016,3,1)
end_date = datetime(2016,3,10)

The thread has exited with code 0 (0x0) with no unhandled exception

Stop this error you have to follow this simple steps

  1. Open Visual Studio
  2. Select option debug from the top
  3. Select Options
  4. In Option Select debugging under debugging select General
  5. In General Select check box "Automatically close the console when debugging stop"
  6. Save it

Then Run the code by using Shortcut key Ctrl+f5

**Other wise it still show error when you run it direct

How to convert list data into json in java

You can use the following method which uses Jackson library

public static <T> List<T> convertToList(String jsonString, Class<T> target) {
    if(StringUtils.isEmpty(jsonString)) return List.of();

        return new ObjectMapper().readValue(jsonString, new ObjectMapper().getTypeFactory().
                constructCollectionType(List.class, target));
    } catch ( JsonProcessingException | JSONException e) {
        e.printStackTrace();
        return List.of();
    }
}

Jquery UI tooltip does not support html content

another solution will be to grab the text inside the title tag & then use .html() method of jQuery to construct the content of the tooltip.

$(function() {
  $(document).tooltip({
    position: {
      using: function(position, feedback) {
        $(this).css(position);
        var txt = $(this).text();
        $(this).html(txt);
        $("<div>")
          .addClass("arrow")
          .addClass(feedback.vertical)
          .addClass(feedback.horizontal)
          .appendTo(this);
      }
    }
  });
});

Example: http://jsfiddle.net/hamzeen/0qwxfgjo/

Centering a button vertically in table cell, using Twitter Bootstrap

So why is td default set to vertical-align: top;? I really don't know that yet. I would not dare to touch it. Instead add this to your stylesheet. It alters the buttons in the tables.

table .btn{
  vertical-align: top;
}

Aligning text and image on UIButton with imageEdgeInsets and titleEdgeInsets

I'm a little late to this party, but I think I have something useful to add.

Kekoa's answer is great but, as RonLugge mentions, it can make the button no longer respect sizeToFit or, more importantly, can cause the button to clip its content when it is intrinsically sized. Yikes!

First, though,

A brief explanation of how I believe imageEdgeInsets and titleEdgeInsets work:

The docs for imageEdgeInsets have the following to say, in part:

Use this property to resize and reposition the effective drawing rectangle for the button image. You can specify a different value for each of the four insets (top, left, bottom, right). A positive value shrinks, or insets, that edge—moving it closer to the center of the button. A negative value expands, or outsets, that edge.

I believe that this documentation was written imagining that the button has no title, just an image. It makes a lot more sense thought of this way, and behaves how UIEdgeInsets usually do. Basically, the frame of the image (or the title, with titleEdgeInsets) is moved inwards for positive insets and outwards for negative insets.

OK, so what?

I'm getting there! Here's what you have by default, setting an image and a title (the button border is green just to show where it is):

Starting image; no space between title and image.

When you want spacing between an image and a title, without causing either to be crushed, you need to set four different insets, two on each of the image and title. That's because you don't want to change the sizes of those elements' frames, but just their positions. When you start thinking this way, the needed change to Kekoa's excellent category becomes clear:

@implementation UIButton(ImageTitleCentering)

- (void)centerButtonAndImageWithSpacing:(CGFloat)spacing {
    CGFloat insetAmount = spacing / 2.0;
    self.imageEdgeInsets = UIEdgeInsetsMake(0, -insetAmount, 0, insetAmount);
    self.titleEdgeInsets = UIEdgeInsetsMake(0, insetAmount, 0, -insetAmount);
}

@end

But wait, you say, when I do that, I get this:

Spacing is good, but the image and title are outside the view's frame.

Oh yeah! I forgot, the docs warned me about this. They say, in part:

This property is used only for positioning the image during layout. The button does not use this property to determine intrinsicContentSize and sizeThatFits:.

But there is a property that can help, and that's contentEdgeInsets. The docs for that say, in part:

The button uses this property to determine intrinsicContentSize and sizeThatFits:.

That sounds good. So let's tweak the category once more:

@implementation UIButton(ImageTitleCentering)

- (void)centerButtonAndImageWithSpacing:(CGFloat)spacing {
    CGFloat insetAmount = spacing / 2.0;
    self.imageEdgeInsets = UIEdgeInsetsMake(0, -insetAmount, 0, insetAmount);
    self.titleEdgeInsets = UIEdgeInsetsMake(0, insetAmount, 0, -insetAmount);
    self.contentEdgeInsets = UIEdgeInsetsMake(0, insetAmount, 0, insetAmount);
}

@end

And what do you get?

Spacing and frame are now correct.

Looks like a winner to me.


Working in Swift and don't want to do any thinking at all? Here's the final version of the extension in Swift:

extension UIButton {
    func centerTextAndImage(spacing: CGFloat) {
        let insetAmount = spacing / 2
        imageEdgeInsets = UIEdgeInsets(top: 0, left: -insetAmount, bottom: 0, right: insetAmount)
        titleEdgeInsets = UIEdgeInsets(top: 0, left: insetAmount, bottom: 0, right: -insetAmount)
        contentEdgeInsets = UIEdgeInsets(top: 0, left: insetAmount, bottom: 0, right: insetAmount)
    }
}

Python threading. How do I lock a thread?

You can see that your locks are pretty much working as you are using them, if you slow down the process and make them block a bit more. You had the right idea, where you surround critical pieces of code with the lock. Here is a small adjustment to your example to show you how each waits on the other to release the lock.

import threading
import time
import inspect

class Thread(threading.Thread):
    def __init__(self, t, *args):
        threading.Thread.__init__(self, target=t, args=args)
        self.start()

count = 0
lock = threading.Lock()

def incre():
    global count
    caller = inspect.getouterframes(inspect.currentframe())[1][3]
    print "Inside %s()" % caller
    print "Acquiring lock"
    with lock:
        print "Lock Acquired"
        count += 1  
        time.sleep(2)  

def bye():
    while count < 5:
        incre()

def hello_there():
    while count < 5:
        incre()

def main():    
    hello = Thread(hello_there)
    goodbye = Thread(bye)


if __name__ == '__main__':
    main()

Sample output:

...
Inside hello_there()
Acquiring lock
Lock Acquired
Inside bye()
Acquiring lock
Lock Acquired
...

MySQL - Rows to Columns

use subquery

SELECT  hostid, 
    (SELECT VALUE FROM TableTest WHERE ITEMNAME='A' AND hostid = t1.hostid) AS A,
    (SELECT VALUE FROM TableTest WHERE ITEMNAME='B' AND hostid = t1.hostid) AS B,
    (SELECT VALUE FROM TableTest WHERE ITEMNAME='C' AND hostid = t1.hostid) AS C
FROM TableTest AS T1
GROUP BY hostid

but it will be a problem if sub query resulting more than a row, use further aggregate function in the subquery

Moment get current date

Just call moment as a function without any arguments:

moment()

For timezone information with moment, look at the moment-timezone package: http://momentjs.com/timezone/

Difference between two dates in Python

Another short solution:

from datetime import date

def diff_dates(date1, date2):
    return abs(date2-date1).days

def main():
    d1 = date(2013,1,1)
    d2 = date(2013,9,13)
    result1 = diff_dates(d2, d1)
    print '{} days between {} and {}'.format(result1, d1, d2)
    print ("Happy programmer's day!")

main()

Taking inputs with BufferedReader in Java

BufferedReader#read reads single character[0 to 65535 (0x00-0xffff)] from the stream, so it is not possible to read single integer from stream.

            String s= inp.readLine();
            int[] m= new int[2];
            String[] s1 = inp.readLine().split(" ");
            m[0]=Integer.parseInt(s1[0]);
            m[1]=Integer.parseInt(s1[1]);

            // Checking whether I am taking the inputs correctly
            System.out.println(s);
            System.out.println(m[0]);
            System.out.println(m[1]);

You can check also Scanner vs. BufferedReader.

Jquery each - Stop loop and return object

modified $.each function

$.fn.eachReturn = function(arr, callback) {
   var result = null;
   $.each(arr, function(index, value){
       var test = callback(index, value);
       if (test) {
           result = test;
           return false;
       }
   });
   return result ;
}

it will break loop on non-false/non-empty result and return it back, so in your case it would be

return $.eachReturn(someArray, function(i){
    ...

Why do I keep getting 'SVN: Working Copy XXXX locked; try performing 'cleanup'?

After more exploration and testing, it appears that this issue was being caused by debugging the plugin and using breakpoints. SVN/Subclipse apparently didn't like having breakpoints midway through their execution and as a result this lock files were being created. As soon as I started just running the plugin, this issue disappeared.

Printing without newline (print 'a',) prints a space, how to remove?

You can suppress the space by printing an empty string to stdout between the print statements.

>>> import sys
>>> for i in range(20):
...   print 'a',
...   sys.stdout.write('')
... 
aaaaaaaaaaaaaaaaaaaa

However, a cleaner solution is to first build the entire string you'd like to print and then output it with a single print statement.

Intellij JAVA_HOME variable

In my case I needed a lower JRE, so I had to tell IntelliJ to use a different one in "Platform Settings"

  • Platform Settings > SDKs ( +; )
  • Click the + button to add a new SDK (or rename and load an existing one)
  • Choose the /Contents/Home directory from the appropriate SDK
    (i.e. /Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home)

How can I display a messagebox in ASP.NET?

This code will help you add a MsgBox in your asp.net file. You can change the function definition to your requirements. Hope this helps!

protected void Addstaff_Click(object sender, EventArgs e)    
    {   
 if (intClassCapcity < intCurrentstaffNumber)     
                {                  
            MsgBox("Record cannot be added because max seats available for the " + (string)Session["course_name"] + " training has been reached");    
        }    
else    
    {   
            sqlClassList.Insert();    
    }    
}

private void MsgBox(string sMessage)    
    {    
        string msg = "<script language=\"javascript\">";    
        msg += "alert('" + sMessage + "');";    
        msg += "</script>";    
        Response.Write(msg);    
    }

Arrays in type script

A cleaner way to do this:

class Book {
    public Title: string;
    public Price: number;
    public Description: string;

    constructor(public BookId: number, public Author: string){}
}

Then

var bks: Book[] = [
    new Book(1, "vamsee")
];

how to make label visible/invisible?

you could try

if (isValid) {
    document.getElementById("endTimeLabel").style.display = "none";
}else {
    document.getElementById("endTimeLabel").style.display = "block";
}

alone those lines

Pass command parameter to method in ViewModel in WPF?

"ViewModel" implies MVVM. If you're doing MVVM you shouldn't be passing views into your view models. Typically you do something like this in your XAML:

<Button Content="Edit" 
        Command="{Binding EditCommand}"
        CommandParameter="{Binding ViewModelItem}" >

And then this in your view model:

private ViewModelItemType _ViewModelItem;
public ViewModelItemType ViewModelItem
{
    get
    {
        return this._ViewModelItem;
    }
    set
    {
        this._ViewModelItem = value;
        RaisePropertyChanged(() => this.ViewModelItem);
    }
}

public ICommand EditCommand { get { return new RelayCommand<ViewModelItemType>(OnEdit); } }
private void OnEdit(ViewModelItemType itemToEdit)
{
    ... do something here...
}

Obviously this is just to illustrate the point, if you only had one property to edit called ViewModelItem then you wouldn't need to pass it in as a command parameter.

Opening a folder in explorer and selecting a file

Using Process.Start on explorer.exe with the /select argument oddly only works for paths less than 120 characters long.

I had to use a native windows method to get it to work in all cases:

[DllImport("shell32.dll", SetLastError = true)]
public static extern int SHOpenFolderAndSelectItems(IntPtr pidlFolder, uint cidl, [In, MarshalAs(UnmanagedType.LPArray)] IntPtr[] apidl, uint dwFlags);

[DllImport("shell32.dll", SetLastError = true)]
public static extern void SHParseDisplayName([MarshalAs(UnmanagedType.LPWStr)] string name, IntPtr bindingContext, [Out] out IntPtr pidl, uint sfgaoIn, [Out] out uint psfgaoOut);

public static void OpenFolderAndSelectItem(string folderPath, string file)
{
    IntPtr nativeFolder;
    uint psfgaoOut;
    SHParseDisplayName(folderPath, IntPtr.Zero, out nativeFolder, 0, out psfgaoOut);

    if (nativeFolder == IntPtr.Zero)
    {
        // Log error, can't find folder
        return;
    }

    IntPtr nativeFile;
    SHParseDisplayName(Path.Combine(folderPath, file), IntPtr.Zero, out nativeFile, 0, out psfgaoOut);

    IntPtr[] fileArray;
    if (nativeFile == IntPtr.Zero)
    {
        // Open the folder without the file selected if we can't find the file
        fileArray = new IntPtr[0];
    }
    else
    {
        fileArray = new IntPtr[] { nativeFile };
    }

    SHOpenFolderAndSelectItems(nativeFolder, (uint)fileArray.Length, fileArray, 0);

    Marshal.FreeCoTaskMem(nativeFolder);
    if (nativeFile != IntPtr.Zero)
    {
        Marshal.FreeCoTaskMem(nativeFile);
    }
}

How to fix missing dependency warning when using useEffect React Hook?

This article is a good primer on fetching data with hooks: https://www.robinwieruch.de/react-hooks-fetch-data/

Essentially, include the fetch function definition inside useEffect:

useEffect(() => {
  const fetchBusinesses = () => {
    return fetch("theUrl"...
      // ...your fetch implementation
    );
  }

  fetchBusinesses();
}, []);

Writelines writes lines without newline, Just fills the file

The documentation for writelines() states:

writelines() does not add line separators

So you'll need to add them yourself. For example:

    line_list.append(new_line + "\n")

whenever you append a new item to line_list.

git: How to ignore all present untracked files?

-u no doesn't show unstaged files either. -uno works as desired and shows unstaged, but hides untracked.

How to animate GIFs in HTML document?

I just ran into this... my gif didn't run on the server that I was testing on, but when I published the code it ran on my desktop just fine...

Volatile vs Static in Java

In addition to other answers, I would like to add one image for it(pic makes easy to understand)

enter image description here

static variables may be cached for individual threads. In multi-threaded environment if one thread modifies its cached data, that may not reflect for other threads as they have a copy of it.

volatile declaration makes sure that threads won't cache the data and uses the shared copy only.

image source

ASP.NET IIS Web.config [Internal Server Error]

I got similar error when i run legacy application in Visual studio 2013 iis express and solved the issue by following steps 1.Navigate to "Documents\IISExpress\config" 2.Open "applicationhost.config" using notepad or any preferred editor 3.scroll down and find for section name="anonymousAuthentication" under 4. Update overrideModeDefault="Deny" to "Allow" 5. save the config file 6. Run the legacy application and worked fine for me.

What is the difference between Python and IPython?

IPython is a powerful interactive Python interpreter that is more interactive comparing to the standard interpreter.

To get the standard Python interpreter you type python and you will get the >>> prompt from where you can work.

To get IPython interpreter, you need to install it first. pip install ipython. You type ipython and you get In [1]: as a prompt and you get In [2]: for the next command. You can call history to check the list of previous commands, and write %recall 1 to recall the command.

Even you are in Python you can run shell commands directly like !ping www.google.com. Looks like a command line Jupiter notebook if you used that before.

You can use [Tab] to autocomplete as shown in the image. enter image description here

CSS selector - element with a given child

I agree that it is not possible in general.

The only thing CSS3 can do (which helped in my case) is to select elements that have no children:

table td:empty
{
   background-color: white;
}

Or have any children (including text):

table td:not(:empty)
{
   background-color: white;
}

Difference between break and continue in PHP?

'continue' is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.

'break' ends execution of the current for, foreach, while, do-while or switch structure.

break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of.

Check out the following links:

http://www.php.net/manual/en/control-structures.break.php

http://www.php.net/manual/en/control-structures.continue.php

Hope it helps..

What's the best way to limit text length of EditText in Android

use an input filter to limit the max length of a text view.

TextView editEntryView = new TextView(...);
InputFilter[] filterArray = new InputFilter[1];
filterArray[0] = new InputFilter.LengthFilter(8);
editEntryView.setFilters(filterArray);

How to install Anaconda on RaspBerry Pi 3 Model B

I was trying to run this on a pi zero. Turns out the pi zero has an armv6l architecture so the above won't work for pi zero or pi one. Alternatively here I learned that miniconda doesn't have a recent version of miniconda. Instead I used the same instructions posted here to install berryconda3

Conda is now working. Hope this helps those of you interested in running conda on the pi zero!

MVC 4 - Return error message from Controller - Show in View

If you want to do a redirect, you can either:

ViewBag.Error = "error message";

or

TempData["Error"] = "error message";

Parse string to DateTime in C#

var dateStr = @"2011-03-21 13:26";
var dateTime = DateTime.ParseExact(dateStr, "yyyy-MM-dd HH:mm", CultureInfo.CurrentCulture);

Check out this link for other format strings!

Create a File object in memory from a string in Java

No; instances of class File represent a path in a filesystem. Therefore, you can use that function only with a file. But perhaps there is an overload that takes an InputStream instead?

Python requests - print entire http request (raw)?

Here is a code, which makes the same, but with response headers:

import socket
def patch_requests():
    old_readline = socket._fileobject.readline
    if not hasattr(old_readline, 'patched'):
        def new_readline(self, size=-1):
            res = old_readline(self, size)
            print res,
            return res
        new_readline.patched = True
        socket._fileobject.readline = new_readline
patch_requests()

I spent a lot of time searching for this, so I'm leaving it here, if someone needs.

How can I have two fixed width columns with one flexible column in the center?

Despite setting up dimensions for the columns, they still seem to shrink as the window shrinks.

An initial setting of a flex container is flex-shrink: 1. That's why your columns are shrinking.

It doesn't matter what width you specify (it could be width: 10000px), with flex-shrink the specified width can be ignored and flex items are prevented from overflowing the container.

I'm trying to set up a flexbox with 3 columns where the left and right columns have a fixed width...

You will need to disable shrinking. Here are some options:

.left, .right {
     width: 230px;
     flex-shrink: 0;
 }  

OR

.left, .right {
     flex-basis: 230px;
     flex-shrink: 0;
}

OR, as recommended by the spec:

.left, .right {
    flex: 0 0 230px;    /* don't grow, don't shrink, stay fixed at 230px */
}

7.2. Components of Flexibility

Authors are encouraged to control flexibility using the flex shorthand rather than with its longhand properties directly, as the shorthand correctly resets any unspecified components to accommodate common uses.

More details here: What are the differences between flex-basis and width?

An additional thing I need to do is hide the right column based on user interaction, in which case the left column would still keep its fixed width, but the center column would fill the rest of the space.

Try this:

.center { flex: 1; }

This will allow the center column to consume available space, including the space of its siblings when they are removed.

Revised Fiddle

Uncaught SyntaxError: Invalid or unexpected token

I also had an issue with multiline strings in this scenario. @Iman's backtick(`) solution worked great in the modern browsers but caused an invalid character error in Internet Explorer. I had to use the following:

'@item.MultiLineString.Replace(Environment.NewLine, "<br />")'

Then I had to put the carriage returns back again in the js function. Had to use RegEx to handle multiple carriage returns.

// This will work for the following:
// "hello\nworld"
// "hello<br>world"
// "hello<br />world"
$("#MyTextArea").val(multiLineString.replace(/\n|<br\s*\/?>/gi, "\r"));

How to make a div with no content have a width?

If you set display: to inline-block, block, flex, ..., on the element with no content, then

For min-width to take effect on a tag with no content, you only need to apply padding for either top or bot.

For min-height to take effect on a tag with no content, you only need to apply padding for left or right.

This example showcases it; here I only sat the padding-left for the min-width to take effect on an empty span tag

Change <select>'s option and trigger events with JavaScript

html using Razor:

 @Html.DropDownList("test1", Model.SelectOptionList, new { id = "test1", onchange = "myFunction()" })

JS Code:

function myFunction() {

            var value = document.getElementById('test1').value;

            console.log("it has been changed! to " + value );
        }

find all the name using mysql query which start with the letter 'a'

try using CHARLIST as shown below:

select distinct name from artists where name RLIKE '^[abc]';

use distinct only if you want distinct values only. To read about it Click here.

How to get different colored lines for different plots in a single figure?

Matplotlib does this by default.

E.g.:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

plt.plot(x, x)
plt.plot(x, 2 * x)
plt.plot(x, 3 * x)
plt.plot(x, 4 * x)
plt.show()

Basic plot demonstrating color cycling

And, as you may already know, you can easily add a legend:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

plt.plot(x, x)
plt.plot(x, 2 * x)
plt.plot(x, 3 * x)
plt.plot(x, 4 * x)

plt.legend(['y = x', 'y = 2x', 'y = 3x', 'y = 4x'], loc='upper left')

plt.show()

Basic plot with legend

If you want to control the colors that will be cycled through:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

plt.gca().set_color_cycle(['red', 'green', 'blue', 'yellow'])

plt.plot(x, x)
plt.plot(x, 2 * x)
plt.plot(x, 3 * x)
plt.plot(x, 4 * x)

plt.legend(['y = x', 'y = 2x', 'y = 3x', 'y = 4x'], loc='upper left')

plt.show()

Plot showing control over default color cycling

If you're unfamiliar with matplotlib, the tutorial is a good place to start.

Edit:

First off, if you have a lot (>5) of things you want to plot on one figure, either:

  1. Put them on different plots (consider using a few subplots on one figure), or
  2. Use something other than color (i.e. marker styles or line thickness) to distinguish between them.

Otherwise, you're going to wind up with a very messy plot! Be nice to who ever is going to read whatever you're doing and don't try to cram 15 different things onto one figure!!

Beyond that, many people are colorblind to varying degrees, and distinguishing between numerous subtly different colors is difficult for more people than you may realize.

That having been said, if you really want to put 20 lines on one axis with 20 relatively distinct colors, here's one way to do it:

import matplotlib.pyplot as plt
import numpy as np

num_plots = 20

# Have a look at the colormaps here and decide which one you'd like:
# http://matplotlib.org/1.2.1/examples/pylab_examples/show_colormaps.html
colormap = plt.cm.gist_ncar
plt.gca().set_prop_cycle(plt.cycler('color', plt.cm.jet(np.linspace(0, 1, num_plots))))

# Plot several different functions...
x = np.arange(10)
labels = []
for i in range(1, num_plots + 1):
    plt.plot(x, i * x + 5 * i)
    labels.append(r'$y = %ix + %i$' % (i, 5*i))

# I'm basically just demonstrating several different legend options here...
plt.legend(labels, ncol=4, loc='upper center', 
           bbox_to_anchor=[0.5, 1.1], 
           columnspacing=1.0, labelspacing=0.0,
           handletextpad=0.0, handlelength=1.5,
           fancybox=True, shadow=True)

plt.show()

Unique colors for 20 lines based on a given colormap

What's the HTML to have a horizontal space between two objects?

Another way you can add horizontal space between elements is to set up labels to preserve spaces in css:

label {
   white-space: pre;
}

..and then add a label with as many spaces as you want:

<label>  </label>