Programs & Examples On #Rsacryptoserviceprovider

The RSACryptoServiceProvider object performs asymmetric encryption and decryption using the implementation of the RSA algorithm provided by the cryptographic service provider (CSP).

How to export non-exportable private key from store

This worked for me on Windows Server 2012 - I needed to export a non-exportable certificate to setup another ADFS server and this did the trick. Remember to use the jailbreak instructions above i.e.:

crypto::certificates /export /systemstore:CERT_SYSTEM_STORE_LOCAL_MACHINE

Use C# HttpWebRequest to send json to web service

First of all you missed ScriptService attribute to add in webservice.

[ScriptService]

After then try following method to call webservice via JSON.

        var webAddr = "http://Domain/VBRService.asmx/callJson";
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
        httpWebRequest.ContentType = "application/json; charset=utf-8";
        httpWebRequest.Method = "POST";            

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = "{\"x\":\"true\"}";

            streamWriter.Write(json);
            streamWriter.Flush();
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            return result;
        }

Git list of staged files

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

git diff --name-only --cached

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

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

And on the example part of the manual:

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

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

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

JavaScript: Collision detection

You can try jquery-collision. Full disclosure: I just wrote this and released it. I didn't find a solution, so I wrote it myself.

It allows you to do:

var hit_list = $("#ball").collision("#someobject0");

which will return all the "#someobject0"'s that overlap with "#ball".

Best way to import Observable from rxjs

One thing I've learnt the hard way is being consistent

Watch out for mixing:

 import { BehaviorSubject } from "rxjs";

with

 import { BehaviorSubject } from "rxjs/BehaviorSubject";

This will probably work just fine UNTIL you try to pass the object to another class (where you did it the other way) and then this can fail

 (myBehaviorSubject instanceof Observable)

It fails because the prototype chain will be different and it will be false.

I can't pretend to understand exactly what is happening but sometimes I run into this and need to change to the longer format.

jquery click event not firing?

Might be useful to some : check for

pointer-events: none;

In the CSS. It prevents clicks from being caught by JS. I think it's relevant because the CSS might be the last place you'd look into in this kind of situation.

How to find/identify large commits in git history?

Step 1 Write all file SHA1s to a text file:

git rev-list --objects --all | sort -k 2 > allfileshas.txt

Step 2 Sort the blobs from biggest to smallest and write results to text file:

git gc && git verify-pack -v .git/objects/pack/pack-*.idx | egrep "^\w+ blob\W+[0-9]+ [0-9]+ [0-9]+$" | sort -k 3 -n -r > bigobjects.txt

Step 3a Combine both text files to get file name/sha1/size information:

for SHA in `cut -f 1 -d\  < bigobjects.txt`; do
echo $(grep $SHA bigobjects.txt) $(grep $SHA allfileshas.txt) | awk '{print $1,$3,$7}' >> bigtosmall.txt
done;

Step 3b If you have file names or path names containing spaces try this variation of Step 3a. It uses cut instead of awk to get the desired columns incl. spaces from column 7 to end of line:

for SHA in `cut -f 1 -d\  < bigobjects.txt`; do
echo $(grep $SHA bigobjects.txt) $(grep $SHA allfileshas.txt) | cut -d ' ' -f'1,3,7-' >> bigtosmall.txt
done;

Now you can look at the file bigtosmall.txt in order to decide which files you want to remove from your Git history.

Step 4 To perform the removal (note this part is slow since it's going to examine every commit in your history for data about the file you identified):

git filter-branch --tree-filter 'rm -f myLargeFile.log' HEAD

Source

Steps 1-3a were copied from Finding and Purging Big Files From Git History

EDIT

The article was deleted sometime in the second half of 2017, but an archived copy of it can still be accessed using the Wayback Machine.

How to go back (ctrl+z) in vi/vim

You can use the u button to undo the last modification. (And Ctrl+R to redo it).

Read more about it at: http://vim.wikia.com/wiki/Undo_and_Redo

What is the difference between static_cast<> and C style casting?

A great post explaining different casts in C/C++, and what C-style cast really does: https://anteru.net/blog/2007/12/18/200/index.html

C-Style casting, using the (type)variable syntax. The worst ever invented. This tries to do the following casts, in this order: (see also C++ Standard, 5.4 expr.cast paragraph 5)

  1. const_cast
  2. static_cast
  3. static_cast followed by const_cast
  4. reinterpret_cast
  5. reinterpret_castfollowed by const_cast

Configure cron job to run every 15 minutes on Jenkins

Your syntax is slightly wrong. Say:

*/15 * * * * command
  |
  |--> `*/15` would imply every 15 minutes.

* indicates that the cron expression matches for all values of the field.

/ describes increments of ranges.

MySQL ON DUPLICATE KEY UPDATE for multiple rows insert in single query

I was looking for the same behavior using jdbi's BindBeanList and found the syntax is exactly the same as Peter Lang's answer above. In case anybody is running into this question, here's my code:

  @SqlUpdate("INSERT INTO table_one (col_one, col_two) VALUES <beans> ON DUPLICATE KEY UPDATE col_one=VALUES(col_one), col_two=VALUES(col_two)")
void insertBeans(@BindBeanList(value = "beans", propertyNames = {"colOne", "colTwo"}) List<Beans> beans);

One key detail to note is that the propertyName you specify within @BindBeanList annotation is not same as the column name you pass into the VALUES() call on update.

How do I start/stop IIS Express Server?

I came across the same issue. My aim is to test PHP scripts with Oracle on Windows 7 Home and without thinking installed IIS7 express and as an afterthought considered Apache as a simpler approach. I will explore IIS express's capabilities seperately.

The challenge was after installing IIS7 express the Apache installation was playing second fiddle to IIS express and bringing up the Microsoft Homepage.

I resolved the port 80 issue by :-

  1. Stopping Microsoft WedMatrix :- net stop was /y
  2. Restarted the Apache Server
  3. Verifying Apache now was listening on the port :- netstat -anop
  4. Clearing out the Browsers caches - Firefox and IE
  5. Running localhost

Python: How to check if keys exists and retrieve value from Dictionary in descending priority

If we encapsulate that in a function we could use recursion and state clearly the purpose by naming the function properly (not sure if getAny is actually a good name):

def getAny(dic, keys, default=None):
    return (keys or default) and dic.get(keys[0], 
                                         getAny( dic, keys[1:], default=default))

or even better, without recursion and more clear:

def getAny(dic, keys, default=None):
    for k in keys: 
        if k in dic:
           return dic[k]
    return default

Then that could be used in a way similar to the dict.get method, like:

getAny(myDict, keySet)

and even have a default result in case of no keys found at all:

getAny(myDict, keySet, "not found")

.NET NewtonSoft JSON deserialize map to a different property name

Adding to Jacks solution. I need to Deserialize using the JsonProperty and Serialize while ignoring the JsonProperty (or vice versa). ReflectionHelper and Attribute Helper are just helper classes that get a list of properties or attributes for a property. I can include if anyone actually cares. Using the example below you can serialize the viewmodel and get "Amount" even though the JsonProperty is "RecurringPrice".

    /// <summary>
    /// Ignore the Json Property attribute. This is usefule when you want to serialize or deserialize differently and not 
    /// let the JsonProperty control everything.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class IgnoreJsonPropertyResolver<T> : DefaultContractResolver
    {
        private Dictionary<string, string> PropertyMappings { get; set; }

        public IgnoreJsonPropertyResolver()
        {
            this.PropertyMappings = new Dictionary<string, string>();
            var properties = ReflectionHelper<T>.GetGetProperties(false)();
            foreach (var propertyInfo in properties)
            {
                var jsonProperty = AttributeHelper.GetAttribute<JsonPropertyAttribute>(propertyInfo);
                if (jsonProperty != null)
                {
                    PropertyMappings.Add(jsonProperty.PropertyName, propertyInfo.Name);
                }
            }
        }

        protected override string ResolvePropertyName(string propertyName)
        {
            string resolvedName = null;
            var resolved = this.PropertyMappings.TryGetValue(propertyName, out resolvedName);
            return (resolved) ? resolvedName : base.ResolvePropertyName(propertyName);
        }
    }

Usage:

        var settings = new JsonSerializerSettings();
        settings.DateFormatString = "YYYY-MM-DD";
        settings.ContractResolver = new IgnoreJsonPropertyResolver<PlanViewModel>();
        var model = new PlanViewModel() {Amount = 100};
        var strModel = JsonConvert.SerializeObject(model,settings);

Model:

public class PlanViewModel
{

    /// <summary>
    ///     The customer is charged an amount over an interval for the subscription.
    /// </summary>
    [JsonProperty(PropertyName = "RecurringPrice")]
    public double Amount { get; set; }

    /// <summary>
    ///     Indicates the number of intervals between each billing. If interval=2, the customer would be billed every two
    ///     months or years depending on the value for interval_unit.
    /// </summary>
    public int Interval { get; set; } = 1;

    /// <summary>
    ///     Number of free trial days that can be granted when a customer is subscribed to this plan.
    /// </summary>
    public int TrialPeriod { get; set; } = 30;

    /// <summary>
    /// This indicates a one-time fee charged upfront while creating a subscription for this plan.
    /// </summary>
    [JsonProperty(PropertyName = "SetupFee")]
    public double SetupAmount { get; set; } = 0;


    /// <summary>
    /// String representing the type id, usually a lookup value, for the record.
    /// </summary>
    [JsonProperty(PropertyName = "TypeId")]
    public string Type { get; set; }

    /// <summary>
    /// Billing Frequency
    /// </summary>
    [JsonProperty(PropertyName = "BillingFrequency")]
    public string Period { get; set; }


    /// <summary>
    /// String representing the type id, usually a lookup value, for the record.
    /// </summary>
    [JsonProperty(PropertyName = "PlanUseType")]
    public string Purpose { get; set; }
}

What is the purpose of a question mark after a type (for example: int? myVariable)?

practical usage:

public string someFunctionThatMayBeCalledWithNullAndReturnsString(int? value)
{
  if (value == null)
  {
    return "bad value";
  }

  return someFunctionThatHandlesIntAndReturnsString(value);
}

c++ compile error: ISO C++ forbids comparison between pointer and integer

You have two ways to fix this. The preferred way is to use:

string answer;

(instead of char). The other possible way to fix it is:

if (answer == 'y') ...

(note single quotes instead of double, representing a char constant).

Convert dd-mm-yyyy string to date

The accepted answer kinda has a bug

var from = $("#datepicker").val().split("-")
var f = new Date(from[2], from[1] - 1, from[0])

Consider if the datepicker contains "77-78-7980" which is obviously not a valid date. This would result in:

var f = new Date(7980, 77, 77);
=> Date 7986-08-15T22:00:00.000Z

Which is probably not the desired result.

The reason for this is explained on the MDN site:

Where Date is called as a constructor with more than one argument, if values are greater than their logical range (e.g. 13 is provided as the month value or 70 for the minute value), the adjacent value will be adjusted. E.g. new Date(2013, 13, 1) is equivalent to new Date(2014, 1, 1).


A better way to solve the problem is:

const stringToDate = function(dateString) {
  const [dd, mm, yyyy] = dateString.split("-");
  return new Date(`${yyyy}-${mm}-${dd}`);
};

console.log(stringToDate('04-04-2019'));
// Date 2019-04-04T00:00:00.000Z

console.log(stringToDate('77-78-7980'));
// Invalid Date

This gives you the possibility to handle invalid input.

For example:

const date = stringToDate("77-78-7980");

if (date === "Invalid Date" || isNaN(date)) {
  console.log("It's all gone bad");
} else {
  // Do something with your valid date here
}

How to trim white spaces of array values in php

function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

function generateRandomSpaces() {
    $output = '';
    $i = rand(1, 10);
    for ($j = 0; $j <= $i; $j++) {
        $output .= " ";
    }   

    return $output;
}

// Generating an array to test
$array = [];
for ($i = 0; $i <= 1000; $i++) {
    $array[] = generateRandomSpaces() . generateRandomString(10) . generateRandomSpaces(); 
}

// ARRAY MAP
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
    $trimmed_array=array_map('trim',$array);
}
$time = (microtime(true) - $start);
echo "Array map: " . $time . " seconds\n";

// ARRAY WALK
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
    array_walk($array, 'trim');
}
$time = (microtime(true) - $start);
echo "Array walk    : " . $time . " seconds\n"; 

// FOREACH
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
    foreach ($array as $index => $elem) {
        $array[$index] = trim($elem);
    }
}
$time = (microtime(true) - $start);
echo "Foreach: " . $time . " seconds\n";

// FOR
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
    for ($j = 0; $j < count($array) - 1; $j++) { 
        $array[$j] = trim($array[$j]);
    }
}
$time = (microtime(true) - $start);
echo "For: " . $time . " seconds\n";

The output of the code above is:

Array map: 8.6775720119476 seconds
Array walk: 10.423238992691 seconds
Foreach: 7.3502039909363 seconds
For: 9.8266389369965 seconds

This values of course may change but I would say foreach is the best option.

What does `void 0` mean?

void is a reserved JavaScript keyword. It evaluates the expression and always returns undefined.

How to fire a button click event from JavaScript in ASP.NET

var clickButton = document.getElementById("<%= btnClearSession.ClientID %>");
clickButton.click();

That solution works for me, but remember it wont work if your asp button has

Visible="False"

To hide button that should be triggered with that script you should hide it with <div hidden></div>

How to install MySQLdb (Python data access library to MySQL) on Mac OS X?

As stated on Installing MySQL-python on mac :

pip uninstall MySQL-python
brew install mysql
pip install MySQL-python

Then test it :

python -c "import MySQLdb"

How to use LogonUser properly to impersonate domain user from workgroup client

Invalid login/password could be also related to issues in your DNS server - that's what happened to me and cost me good 5 hours of my life. See if you can specify ip address instead on domain name.

What is the difference between char, nchar, varchar, and nvarchar in SQL Server?

Just to clear up... or sum up...

  • nchar and nvarchar can store Unicode characters.
  • char and varchar cannot store Unicode characters.
  • char and nchar are fixed-length which will reserve storage space for number of characters you specify even if you don't use up all that space.
  • varchar and nvarchar are variable-length which will only use up spaces for the characters you store. It will not reserve storage like char or nchar.

nchar and nvarchar will take up twice as much storage space, so it may be wise to use them only if you need Unicode support.

Can jQuery get all CSS styles associated with an element?

Two years late, but I have the solution you're looking for. Not intending to take credit form the original author, here's a plugin which I found works exceptionally well for what you need, but gets all possible styles in all browsers, even IE.

Warning: This code generates a lot of output, and should be used sparingly. It not only copies all standard CSS properties, but also all vendor CSS properties for that browser.

jquery.getStyleObject.js:

/*
 * getStyleObject Plugin for jQuery JavaScript Library
 * From: http://upshots.org/?p=112
 */

(function($){
    $.fn.getStyleObject = function(){
        var dom = this.get(0);
        var style;
        var returns = {};
        if(window.getComputedStyle){
            var camelize = function(a,b){
                return b.toUpperCase();
            };
            style = window.getComputedStyle(dom, null);
            for(var i = 0, l = style.length; i < l; i++){
                var prop = style[i];
                var camel = prop.replace(/\-([a-z])/g, camelize);
                var val = style.getPropertyValue(prop);
                returns[camel] = val;
            };
            return returns;
        };
        if(style = dom.currentStyle){
            for(var prop in style){
                returns[prop] = style[prop];
            };
            return returns;
        };
        return this.css();
    }
})(jQuery);

Basic usage is pretty simple, but he's written a function for that as well:

$.fn.copyCSS = function(source){
  var styles = $(source).getStyleObject();
  this.css(styles);
}

Hope that helps.

How can I send the "&" (ampersand) character via AJAX?

Ramil Amr's answer works only for the & character. If you have some other special characters, you should use PHP's htmlspecialchars() and JS's encodeURIComponent().

You can write:

var wysiwyg_clean = encodeURIComponent(wysiwyg);

And on the server side:

htmlspecialchars($_POST['wysiwyg']);

This will make sure that AJAX will pass the data as expected, and that PHP (in case your'e insreting the data to a database) will make sure the data works as expected.

Cancel split window in Vim

To close all splits, I usually place the cursor in the window that shall be the on-ly visible one and then do :on which makes the current window the on-ly visible window. Nice mnemonic to remember.


Edit: :help :on showed me that these commands are the same:

  • :on
  • :only
  • CTRL-w CTRL-o
  • And yes, also CTRL-W o has the same effect (as Nathan answered).

Each of these four closes all windows except the active one.

JQuery find first parent element with specific class prefix

Use .closest() with a selector:

var $div = $('#divid').closest('div[class^="div-a"]');

Testing if a list of integer is odd or even

        #region even and odd numbers
        for (int x = 0; x <= 50; x = x + 2)
        {

            int y = 1;
            y = y + x;
            if (y < 50)
            {
                Console.WriteLine("Odd number is #{" + x + "} : even number is #{" + y + "} order by Asc");
                Console.ReadKey();
            }
            else
            {
                Console.WriteLine("Odd number is #{" + x + "} : even number is #{0} order by Asc");
                Console.ReadKey();
            }

        }

        //order by desc

        for (int z = 50; z >= 0; z = z - 2)
        {
            int w = z;
            w = w - 1;
            if (w > 0)
            {
                Console.WriteLine("odd number is {" + z + "} : even number is {" + w + "} order by desc");
                Console.ReadKey();
            }
            else
            {
                Console.WriteLine("odd number is {" + z + "} : even number is {0} order by desc");
                Console.ReadKey();
            }
        }

In mocha testing while calling asynchronous function how to avoid the timeout Error: timeout of 2000ms exceeded

A little late but someone can use this in future...You can increase your test timeout by updating scripts in your package.json with the following:

"scripts": { "test": "test --timeout 10000" //Adjust to a value you need }

Run your tests using the command test

How do I rewrite URLs in a proxy response in NGINX

You can use the following nginx configuration example:

upstream adminhost {
  server adminhostname:8080;
}

server {
  listen 80;

  location ~ ^/admin/(.*)$ {
    proxy_pass http://adminhost/$1$is_args$args;
    proxy_redirect off;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Host $server_name;
  }
}

What is the best way to programmatically detect porn images?

This is a nudity detector. I haven't tried it. It's the only OSS one I could find.

https://code.google.com/p/nudetech

Could not load file or assembly '' or one of its dependencies

A strange fix for me, but I had just pulled this solution from source control.

Was getting this error, went through most of the answers above, and then deleted the solution and re-pulled the solution from source control.

Worked.

Will only apply to a few, but I guess I was one of the few so there will be more. Not sure what happened the first time, but somehow some assemblies must have had some issues when I pulled them across.

Essentially turn it off and on again.

Setting table row height

I found the best answer for my purposes was to use:

.topics tr { 
    overflow: hidden;
    height: 14px;
    white-space: nowrap;
}

The white-space: nowrap is important as it prevents your row's cells from breaking across multiple lines.

I personally like to add text-overflow: ellipsis to my th and td elements to make the overflowing text look nicer by adding the trailing fullstops, for example Too long gets dots...

Java finished with non-zero exit value 2 - Android Gradle

I didn't know (by then) that "compile fileTree(dir: 'libs', include: ['*.jar'])" compile all that has jar extension on libs folder, so i just comment (or delete) this lines:

//compile 'com.squareup.retrofit:retrofit:1.9.0'
//compile 'com.squareup.okhttp:okhttp-urlconnection:2.2.0'
//compile 'com.squareup.okhttp:okhttp:2.2.0'

//compile files('libs/spotify-web-api-android-master-0.1.0.jar')
//compile files('libs/okio-1.3.0.jar')

and it works fine. Thanks anyway! My bad.

How to do a scatter plot with empty circles in Python?

From the documentation for scatter:

Optional kwargs control the Collection properties; in particular:

    edgecolors:
        The string ‘none’ to plot faces with no outlines
    facecolors:
        The string ‘none’ to plot unfilled outlines

Try the following:

import matplotlib.pyplot as plt 
import numpy as np 

x = np.random.randn(60) 
y = np.random.randn(60)

plt.scatter(x, y, s=80, facecolors='none', edgecolors='r')
plt.show()

example image

Note: For other types of plots see this post on the use of markeredgecolor and markerfacecolor.

Bootstrap: How to center align content inside column?

Want to center an image? Very easy, Bootstrap comes with two classes, .center-block and text-center.

Use the former in the case of your image being a BLOCK element, for example, adding img-responsive class to your img makes the img a block element. You should know this if you know how to navigate in the web console and see applied styles to an element.

Don't want to use a class? No problem, here is the CSS bootstrap uses. You can make a custom class or write a CSS rule for the element to match the Bootstrap class.

 // In case you're dealing with a block element apply this to the element itself 
.center-block {
   margin-left:auto;
   margin-right:auto;
   display:block;
}

// In case you're dealing with a inline element apply this to the parent 
.text-center {
   text-align:center
}

Java 8 lambda get and remove element from list

Consider using vanilla java iterators to perform the task:

public static <T> T findAndRemoveFirst(Iterable<? extends T> collection, Predicate<? super T> test) {
    T value = null;
    for (Iterator<? extends T> it = collection.iterator(); it.hasNext();)
        if (test.test(value = it.next())) {
            it.remove();
            return value;
        }
    return null;
}

Advantages:

  1. It is plain and obvious.
  2. It traverses only once and only up to the matching element.
  3. You can do it on any Iterable even without stream() support (at least those implementing remove() on their iterator).

Disadvantages:

  1. You cannot do it in place as a single expression (auxiliary method or variable required)

As for the

Is it possible to combine get and remove in a lambda expression?

other answers clearly show that it is possible, but you should be aware of

  1. Search and removal may traverse the list twice
  2. ConcurrentModificationException may be thrown when removing element from the list being iterated

What are the differences between B trees and B+ trees?

B+Trees are much easier and higher performing to do a full scan, as in look at every piece of data that the tree indexes, since the terminal nodes form a linked list. To do a full scan with a B-Tree you need to do a full tree traversal to find all the data.

B-Trees on the other hand can be faster when you do a seek (looking for a specific piece of data by key) especially when the tree resides in RAM or other non-block storage. Since you can elevate commonly used nodes in the tree there are less comparisons required to get to the data.

How to assign more memory to docker container

If you want to change the default container and you are using Virtualbox, you can do it via the commandline / CLI:

docker-machine stop
VBoxManage modifyvm default --cpus 2
VBoxManage modifyvm default --memory 4096
docker-machine start

How to resolve a Java Rounding Double issue

See responses to this question. Essentially what you are seeing is a natural consequence of using floating point arithmetic.

You could pick some arbitrary precision (significant digits of your inputs?) and round your result to it, if you feel comfortable doing that.

Rename multiple files in cmd

for /f "delims=" %%i in ('dir /b /a-d *.txt') do ren "%%~i" "%%~ni 1.1%%~xi"

If you use the simple for loop without the /f parameter, already renamed files will be again renamed.

Change the "From:" address in Unix "mail"

On CentOS 5.5, the easiest way I've found to set the default from domain is to modify the hosts file. If your hosts file contains your WAN/public IP address, simply modify the first hostname listed for it. For example, your hosts file may look like:

...
11.22.33.44 localhost default-domain whatever-else.com
...

To make it send from whatever-else.com, simply modify it so that whatever-else.com is listed first, for example:

...
11.22.33.44 whatever-else.com localhost default-domain
...

I can't speak for any other distro (or even version of CentOS) but in my particular case, the above works perfectly.

Converting NSString to NSDate (and back again)

using "10" for representing a year is not good, because it can be 1910, 1810, etc. You probably should use 4 digits for that.

If you can change the date to something like

yyyymmdd

Then you can use:

// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyyMMdd"];
NSDate *date = [dateFormat dateFromString:dateStr];  

// Convert date object to desired output format
[dateFormat setDateFormat:@"EEEE MMMM d, YYYY"];
dateStr = [dateFormat stringFromDate:date];  
[dateFormat release];

Running AngularJS initialization code when view is loaded

Or you can just initialize inline in the controller. If you use an init function internal to the controller, it doesn't need to be defined in the scope. In fact, it can be self executing:

function MyCtrl($scope) {
    $scope.isSaving = false;

    (function() {  // init
        if (true) { // $routeParams.Id) {
            //get an existing object
        } else {
            //create a new object
        }
    })()

    $scope.isClean = function () {
       return $scope.hasChanges() && !$scope.isSaving;
    }

    $scope.hasChanges = function() { return false }
}

How to check if one DateTime is greater than the other in C#

You can use the overloaded < or > operators.

For example:

DateTime d1 = new DateTime(2008, 1, 1);
DateTime d2 = new DateTime(2008, 1, 2);
if (d1 < d2) { ...

How can I pad an int with leading zeros when using cout << operator?

I would use the following function. I don't like sprintf; it doesn't do what I want!!

#define hexchar(x)    ((((x)&0x0F)>9)?((x)+'A'-10):((x)+'0'))
typedef signed long long   Int64;

// Special printf for numbers only
// See formatting information below.
//
//    Print the number "n" in the given "base"
//    using exactly "numDigits".
//    Print +/- if signed flag "isSigned" is TRUE.
//    Use the character specified in "padchar" to pad extra characters.
//
//    Examples:
//    sprintfNum(pszBuffer, 6, 10, 6,  TRUE, ' ',   1234);  -->  " +1234"
//    sprintfNum(pszBuffer, 6, 10, 6, FALSE, '0',   1234);  -->  "001234"
//    sprintfNum(pszBuffer, 6, 16, 6, FALSE, '.', 0x5AA5);  -->  "..5AA5"
void sprintfNum(char *pszBuffer, int size, char base, char numDigits, char isSigned, char padchar, Int64 n)
{
    char *ptr = pszBuffer;

    if (!pszBuffer)
    {
        return;
    }

    char *p, buf[32];
    unsigned long long x;
    unsigned char count;

    // Prepare negative number
    if (isSigned && (n < 0))
    {
        x = -n;
    }
    else
    {
        x = n;
    }

    // Set up small string buffer
    count = (numDigits-1) - (isSigned?1:0);
    p = buf + sizeof (buf);
    *--p = '\0';

    // Force calculation of first digit
    // (to prevent zero from not printing at all!!!)
    *--p = (char)hexchar(x%base);
    x = x / base;

    // Calculate remaining digits
    while(count--)
    {
        if(x != 0)
        {
            // Calculate next digit
            *--p = (char)hexchar(x%base);
            x /= base;
        }
        else
        {
            // No more digits left, pad out to desired length
            *--p = padchar;
        }
    }

    // Apply signed notation if requested
    if (isSigned)
    {
        if (n < 0)
        {
            *--p = '-';
        }
        else if (n > 0)
        {
            *--p = '+';
        }
        else
        {
            *--p = ' ';
        }
    }

    // Print the string right-justified
    count = numDigits;
    while (count--)
    {
        *ptr++ = *p++;
    }
    return;
}

Access index of the parent ng-repeat from child ng-repeat

You can simply use use $parent.$index .where parent will represent object of parent repeating object .

Docker compose port mapping

If you want to access redis from the host (127.0.0.1), you have to use the ports command.

redis:
  build:
    context: .
    dockerfile: Dockerfile-redis
    ports:
    - "6379:6379"

TextFX menu is missing in Notepad++

Plugins -> Plugin Manager -> Show Plugin Manager -> Setting -> Check mark On Force HTTP instead of HTTPS for downloading Plugin List & Use development plugin list (may contain untested, unvalidated or un-installable plugins). -> OK.

how to parse JSONArray in android

getJSONArray(attrname) will get you an array from the object of that given attribute name in your case what is happening is that for

{"abridged_cast":["name": blah...]}
^ its trying to search for a value "characters"

but you need to get into the array and then do a search for "characters"

try this

String json="{'abridged_cast':[{'name':'JeffBridges','id':'162655890','characters':['JackPrescott']},{'name':'CharlesGrodin','id':'162662571','characters':['FredWilson']},{'name':'JessicaLange','id':'162653068','characters':['Dwan']},{'name':'JohnRandolph','id':'162691889','characters':['Capt.Ross']},{'name':'ReneAuberjonois','id':'162718328','characters':['Bagley']}]}";

    JSONObject jsonResponse;
    try {
        ArrayList<String> temp = new ArrayList<String>();
        jsonResponse = new JSONObject(json);
        JSONArray movies = jsonResponse.getJSONArray("abridged_cast");
        for(int i=0;i<movies.length();i++){
            JSONObject movie = movies.getJSONObject(i);
            JSONArray characters = movie.getJSONArray("characters");
            for(int j=0;j<characters.length();j++){
                temp.add(characters.getString(j));
            }
        }
        Toast.makeText(this, "Json: "+temp, Toast.LENGTH_LONG).show();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

checked it :)

The import com.google.android.gms cannot be resolved

I checked off Google API as project build target.

That is irrelevant, as that is for Maps V1, and you are trying to use Maps V2.

I included .jar file for maps by right-clicking on my project, went to build path and added external archive locating it in my SDK: android-sdk-windows\add-ons\addon_google_apis_google_inc_8\libs\maps

This is doubly wrong.

First, never manually modify the build path in an Android project. If you are doing that, at best, you will crash at runtime, because the JAR you think you put in your project (via the manual build path change) is not in your APK. For an ordinary third-party JAR, put it in the libs/ directory of your project, which will add it to your build path automatically and add its contents to your APK file.

However, Maps V2 is not a JAR. It is an Android library project that contains a JAR. You need the whole library project.

You need to import the android-sdk-windows\add-ons\addon_google_apis_google_inc_8 project into Eclipse, then add it to your app as a reference to an Android library project.

Call an angular function inside html

Yep, just add parenthesis (calling the function). Make sure the function is in scope and actually returns something.

<ul class="ui-listview ui-radiobutton" ng-repeat="meter in meters">
  <li class = "ui-divider">
    {{ meter.DESCRIPTION }}
    {{ htmlgeneration() }}
  </li>
</ul>

error LNK2005, already defined?

The linker tells you that you have the variable k defined multiple times. Indeed, you have a definition in A.cpp and another in B.cpp. Both compilation units produce a corresponding object file that the linker uses to create your program. The problem is that in your case the linker does not know whic definition of k to use. In C++ you can have only one defintion of the same construct (variable, type, function).

To fix it, you will have to decide what your goal is

  • If you want to have two variables, both named k, you can use an anonymous namespace in both .cpp files, then refer to k as you are doing now:

.

namespace {
  int k;
}
  • You can rename one of the ks to something else, thus avoiding the duplicate defintion.
  • If you want to have only once definition of k and use that in both .cpp files, you need to declare in one as extern int k;, and leave it as it is in the other. This will tell the linker to use the one definition (the unchanged version) in both cases -- extern implies that the variable is defined in another compilation unit.

Gradle - Move a folder from ABC to XYZ

Your task declaration is incorrectly combining the Copy task type and project.copy method, resulting in a task that has nothing to copy and thus never runs. Besides, Copy isn't the right choice for renaming a directory. There is no Gradle API for renaming, but a bit of Groovy code (leveraging Java's File API) will do. Assuming Project1 is the project directory:

task renABCToXYZ {     doLast {         file("ABC").renameTo(file("XYZ"))     } } 

Looking at the bigger picture, it's probably better to add the renaming logic (i.e. the doLast task action) to the task that produces ABC.

Check for false

If you want an explicit check against false (and not undefined, null and others which I assume as you are using !== instead of !=) then yes, you have to use that.

Also, this is the same in a slightly smaller footprint:

if(borrar() !== !1)

Can I bind an array to an IN() condition?

here is my solution. I have also extended the PDO class:

class Db extends PDO
{

    /**
     * SELECT ... WHERE fieldName IN (:paramName) workaround
     *
     * @param array  $array
     * @param string $prefix
     *
     * @return string
     */
    public function CreateArrayBindParamNames(array $array, $prefix = 'id_')
    {
        $newparams = [];
        foreach ($array as $n => $val)
        {
            $newparams[] = ":".$prefix.$n;
        }
        return implode(", ", $newparams);
    }

    /**
     * Bind every array element to the proper named parameter
     *
     * @param PDOStatement $stmt
     * @param array        $array
     * @param string       $prefix
     */
    public function BindArrayParam(PDOStatement &$stmt, array $array, $prefix = 'id_')
    {
        foreach($array as $n => $val)
        {
            $val = intval($val);
            $stmt -> bindParam(":".$prefix.$n, $val, PDO::PARAM_INT);
        }
    }
}

Here is a sample usage for the above code:

$idList = [1, 2, 3, 4];
$stmt = $this -> db -> prepare("
  SELECT
    `Name`
  FROM
    `User`
  WHERE
    (`ID` IN (".$this -> db -> CreateArrayBindParamNames($idList)."))");
$this -> db -> BindArrayParam($stmt, $idList);
$stmt -> execute();
foreach($stmt as $row)
{
    echo $row['Name'];
}

Let me know what you think

How do I raise an exception in Rails so it behaves like other Rails exceptions?

You don't have to do anything special, it should just be working.

When I have a fresh rails app with this controller:

class FooController < ApplicationController
  def index
    raise "error"
  end
end

and go to http://127.0.0.1:3000/foo/

I am seeing the exception with a stack trace.

You might not see the whole stacktrace in the console log because Rails (since 2.3) filters lines from the stack trace that come from the framework itself.

See config/initializers/backtrace_silencers.rb in your Rails project

Finding Variable Type in JavaScript

Here is the Complete solution.

You can also use it as a Helper class in your Projects.

_x000D_
_x000D_
"use strict";_x000D_
/**_x000D_
 * @description Util file_x000D_
 * @author Tarandeep Singh_x000D_
 * @created 2016-08-09_x000D_
 */_x000D_
_x000D_
window.Sys = {};_x000D_
_x000D_
Sys = {_x000D_
  isEmptyObject: function(val) {_x000D_
    return this.isObject(val) && Object.keys(val).length;_x000D_
  },_x000D_
  /** This Returns Object Type */_x000D_
  getType: function(val) {_x000D_
    return Object.prototype.toString.call(val);_x000D_
  },_x000D_
  /** This Checks and Return if Object is Defined */_x000D_
  isDefined: function(val) {_x000D_
    return val !== void 0 || typeof val !== 'undefined';_x000D_
  },_x000D_
  /** Run a Map on an Array **/_x000D_
  map: function(arr, fn) {_x000D_
    var res = [],_x000D_
      i = 0;_x000D_
    for (; i < arr.length; ++i) {_x000D_
      res.push(fn(arr[i], i));_x000D_
    }_x000D_
    arr = null;_x000D_
    return res;_x000D_
  },_x000D_
  /** Checks and Return if the prop is Objects own Property */_x000D_
  hasOwnProp: function(obj, val) {_x000D_
    return Object.prototype.hasOwnProperty.call(obj, val);_x000D_
  },_x000D_
  /** Extend properties from extending Object to initial Object */_x000D_
  extend: function(newObj, oldObj) {_x000D_
    if (this.isDefined(newObj) && this.isDefined(oldObj)) {_x000D_
      for (var prop in oldObj) {_x000D_
        if (this.hasOwnProp(oldObj, prop)) {_x000D_
          newObj[prop] = oldObj[prop];_x000D_
        }_x000D_
      }_x000D_
      return newObj;_x000D_
    } else {_x000D_
      return newObj || oldObj || {};_x000D_
    }_x000D_
  }_x000D_
};_x000D_
_x000D_
// This Method will create Multiple functions in the Sys object that can be used to test type of_x000D_
['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Object', 'Array', 'Undefined']_x000D_
.forEach(_x000D_
  function(name) {_x000D_
    Sys['is' + name] = function(obj) {_x000D_
      return toString.call(obj) == '[object ' + name + ']';_x000D_
    };_x000D_
  }_x000D_
);
_x000D_
<h1>Use the Helper JavaScript Methods..</h1>_x000D_
<code>use: if(Sys.isDefined(jQuery){console.log("O Yeah... !!");}</code>
_x000D_
_x000D_
_x000D_

For Exportable CommonJs Module or RequireJS Module....

"use strict";

/*** Helper Utils ***/

/**
 * @description Util file :: From Vault
 * @author Tarandeep Singh
 * @created 2016-08-09
 */

var Sys = {};

Sys = {
    isEmptyObject: function(val){
        return this.isObject(val) && Object.keys(val).length;
    },
    /** This Returns Object Type */
    getType: function(val){
        return Object.prototype.toString.call(val);
    },
    /** This Checks and Return if Object is Defined */
    isDefined: function(val){
        return val !== void 0 || typeof val !== 'undefined';
    },
    /** Run a Map on an Array **/
    map: function(arr,fn){
        var res = [], i=0;
        for( ; i<arr.length; ++i){
            res.push(fn(arr[i], i));
        }
        arr = null;
        return res;
    },
    /** Checks and Return if the prop is Objects own Property */
    hasOwnProp: function(obj, val){
        return Object.prototype.hasOwnProperty.call(obj, val);
    },
    /** Extend properties from extending Object to initial Object */
    extend: function(newObj, oldObj){
        if(this.isDefined(newObj) && this.isDefined(oldObj)){
            for(var prop in oldObj){
                if(this.hasOwnProp(oldObj, prop)){
                    newObj[prop] = oldObj[prop];
                }
            }
            return newObj;
        }else {
            return newObj || oldObj || {};
        }
    }
};

/**
 * This isn't Required but just makes WebStorm color Code Better :D
 * */
Sys.isObject
    = Sys.isArguments
    = Sys.isFunction
    = Sys.isString
    = Sys.isArray
    = Sys.isUndefined
    = Sys.isDate
    = Sys.isNumber
    = Sys.isRegExp
    = "";

/** This Method will create Multiple functions in the Sys object that can be used to test type of **/

['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Object', 'Array', 'Undefined']
    .forEach(
        function(name) {
            Sys['is' + name] = function(obj) {
                return toString.call(obj) == '[object ' + name + ']';
            };
        }
    );


module.exports = Sys;

Currently in Use on a public git repo. Github Project

Now you can import this Sys code in a Sys.js file. then you can use this Sys object functions to find out the type of JavaScript Objects

you can also check is Object is Defined or type is Function or the Object is Empty... etc.

  • Sys.isObject
  • Sys.isArguments
  • Sys.isFunction
  • Sys.isString
  • Sys.isArray
  • Sys.isUndefined
  • Sys.isDate
  • Sys.isNumber
  • Sys.isRegExp

For Example

var m = function(){};
Sys.isObject({});
Sys.isFunction(m);
Sys.isString(m);

console.log(Sys.isDefined(jQuery));

PHPExcel set border and format for all sheets in spreadsheet

To answer your extra question:

You can set which rows should be repeated on every page using:

$objPHPExcel->getActiveSheet()->getPageSetup()->setRowsToRepeatAtTopByStartAndEnd(1, 5);

Now, row 1, 2, 3, 4 and 5 will be repeated.

How do I format my oracle queries so the columns don't wrap?

set linesize 3000

set wrap off

set termout off

set pagesize 0 embedded on

set trimspool on

Try with all above values.

How do I get DOUBLE_MAX?

You get the integer limits in <limits.h> or <climits>. Floating point characteristics are defined in <float.h> for C. In C++, the preferred version is usually std::numeric_limits<double>::max() (for which you #include <limits>).

As to your original question, if you want a larger integer type than long, you should probably consider long long. This isn't officially included in C++98 or C++03, but is part of C99 and C++11, so all reasonably current compilers support it.

LDAP server which is my base dn

The base dn is dc=example,dc=com.

I don't know about openca, but I will try this answer since you got very little traffic so far.

A base dn is the point from where a server will search for users. So I would try to simply use admin as a login name.

If openca behaves like most ldap aware applications, this is what is going to happen :

  1. An ldap search for the user admin will be done by the server starting at the base dn (dc=example,dc=com).
  2. When the user is found, the full dn (cn=admin,dc=example,dc=com) will be used to bind with the supplied password.
  3. The ldap server will hash the password and compare with the stored hash value. If it matches, you're in.

Getting step 1 right is the hardest part, but mostly because we don't get to do it often. Things you have to look out for in your configuraiton file are :

  • The dn your application will use to bind to the ldap server. This happens at application startup, before any user comes to authenticate. You will have to supply a full dn, maybe something like cn=admin,dc=example,dc=com.
  • The authentication method. It is usually a "simple bind".
  • The user search filter. Look at the attribute named objectClass for your admin user. It will be either inetOrgPerson or user. There will be others like top, you can ignore them. In your openca configuration, there should be a string like (objectClass=inetOrgPerson). Whatever it is, make sure it matches your admin user's object Class. You can specify two object class with this search filter (|(objectClass=inetOrgPerson)(objectClass=user)).

Download an LDAP Browser, such as Apache's Directory Studio. Connect using your application's credentials, so you will see what your application sees.

Compare if BigDecimal is greater than zero

Use compareTo() function that's built into the class.

How to alias a table in Laravel Eloquent queries (or using Query Builder)?

You can use less code, writing this:

    $users = DB::table('really_long_table_name')
       ->get(array('really_long_table_name.field_very_long_name as short_name'));

And of course if you want to select more fields, just write a "," and add more:

 $users = DB::table('really_long_table_name')
       ->get(array('really_long_table_name.field_very_long_name as short_name', 'really_long_table_name.another_field as other', 'and_another'));

This is very practical when you use a joins complex query

Batchfile to create backup and rename with timestamp

Renames all .pdf files based on current system date. For example a file named Gross Profit.pdf is renamed to Gross Profit 2014-07-31.pdf. If you run it tomorrow, it will rename it to Gross Profit 2014-08-01.pdf.

You could replace the ? with the report name Gross Profit, but it will only rename the one report. The ? renames everything in the Conduit folder. The reason there are so many ?, is that some .pdfs have long names. If you just put 12 ?s, then any name longer than 12 characters will be clipped off at the 13th character. Try it with 1 ?, then try it with many ?s. The ? length should be a little longer or as long as the longest report name.

@ECHO OFF
SET NETWORKSOURCE=\\flcorpfile\shared\"SHORE Reports"\2014\Conduit
REN %NETWORKSOURCE%\*.pdf "????????????????????????????????????????????????? %date:~-4,4%-%date:~-10,2%-%date:~7,2%.pdf"

Operator overloading on class templates

This helped me with the exact same problem.

Solution:

  1. Forward declare the friend function before the definition of the class itself. For example:

       template<typename T> class MyClass;  // pre-declare the template class itself
       template<typename T> std::ostream& operator<< (std::ostream& o, const MyClass <T>& x);
    
  2. Declare your friend function in your class with "<>" appended to the function name.

       friend std::ostream& operator<< <> (std::ostream& o, const Foo<T>& x);
    

Package name does not correspond to the file path - IntelliJ

You should declare in the Project structure(Ctrl+Alt+Shift+s) in the Module section mark your folders which of them are source package(blue one) and which are test ...

Angular2 RC6: '<component> is not a known element'

Ok, let me give the details of code, how to use other module's component.

For example, I have M2 module, M2 module have comp23 component and comp2 component, Now I want to use comp23 and comp2 in app.module, here is how:

this is app.module.ts, see my comment,

 // import this module's ALL component, but not other module's component, only this module
  import { AppComponent } from './app.component';
  import { Comp1Component } from './comp1/comp1.component';

  // import all other module,
 import { SwModule } from './sw/sw.module';
 import { Sw1Module } from './sw1/sw1.module';
 import { M2Module } from './m2/m2.module';

   import { CustomerDashboardModule } from './customer-dashboard/customer-dashboard.module';


 @NgModule({

    // declare only this module's all component, not other module component.  

declarations: [
AppComponent,
Comp1Component,


 ],

 // imports all other module only.
imports: [
BrowserModule,
SwModule,
Sw1Module,
M2Module,
CustomerDashboardModule // add the feature module here
],
 providers: [],
 bootstrap: [AppComponent]
})
export class AppModule { }

this is m2 module:

   import { NgModule } from '@angular/core';
   import { CommonModule } from '@angular/common';

   // must import this module's all component file
   import { Comp2Component } from './comp2/comp2.component';
   import { Comp23Component } from './comp23/comp23.component';

   @NgModule({

   // import all other module here.
     imports: [
       CommonModule
     ],

    // declare only this module's child component. 
     declarations: [Comp2Component, Comp23Component],

   // for other module to use these component, must exports
     exports: [Comp2Component, Comp23Component]
   })
   export class M2Module { }

My commend in code explain what you need to do here.

now in app.component.html, you can use

  <app-comp23></app-comp23>

follow angular doc sample import modul

ng: command not found while creating new project using angular-cli

If you have installed angular cli globally but ng isn't working, just do this:

echo -e "export PATH=$(npm prefix -g)/bin:$PATH" >> ~/.bashrc

source ~/.bashrc

ng --version

Python string to unicode

Decode it with the unicode-escape codec:

>>> a="Hello\u2026"
>>> a.decode('unicode-escape')
u'Hello\u2026'
>>> print _
Hello…

This is because for a non-unicode string the \u2026 is not recognised but is instead treated as a literal series of characters (to put it more clearly, 'Hello\\u2026'). You need to decode the escapes, and the unicode-escape codec can do that for you.

Note that you can get unicode to recognise it in the same way by specifying the codec argument:

>>> unicode(a, 'unicode-escape')
u'Hello\u2026'

But the a.decode() way is nicer.

Xcode 8 shows error that provisioning profile doesn't include signing certificate

Had the same error. Profiles seems renewed, new certificates added, i even checked it when download. Also revoked former developer's certificates, excluded from provision profile. But Xcode still asking me about previous certificates with error:

No certificate for team 'MY_TEAM' matching 'iPhone Developer: FORMER_DEVELOPER' found

so, what I did to fix it:

  1. Go Build Settings -> Signing -> Code Signing Identity
  2. Find all 'FORMER_DEVELOPER' certificates and choose needed.

Hope it will help somebody.

How to access List elements

Learn python the hard way ex 34

try this

animals = ['bear' , 'python' , 'peacock', 'kangaroo' , 'whale' , 'platypus']

# print "The first (1st) animal is at 0 and is a bear." 

for i in range(len(animals)):
    print "The %d animal is at %d and is a %s" % (i+1 ,i, animals[i])

# "The animal at 0 is the 1st animal and is a bear."

for i in range(len(animals)):
    print "The animal at %d is the %d and is a %s " % (i, i+1, animals[i])

Why can't I use the 'await' operator within the body of a lock statement?

This is just an extension to this answer.

using System;
using System.Threading;
using System.Threading.Tasks;

public class SemaphoreLocker
{
    private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);

    public async Task LockAsync(Func<Task> worker)
    {
        await _semaphore.WaitAsync();
        try
        {
            await worker();
        }
        finally
        {
            _semaphore.Release();
        }
    }

    // overloading variant for non-void methods with return type (generic T)
    public async Task<T> LockAsync<T>(Func<Task<T>> worker)
    {
        await _semaphore.WaitAsync();

        T result = default;

        try
        {
            result = await worker();
        }
        finally
        {
            _semaphore.Release();
        }

        return result;
    }
}

Usage:

public class Test
{
    private static readonly SemaphoreLocker _locker = new SemaphoreLocker();

    public async Task DoTest()
    {
        await _locker.LockAsync(async () =>
        {
            // [async] calls can be used within this block 
            // to handle a resource by one thread. 
        });
        // OR
        var result = await _locker.LockAsync(async () =>
        {
            // [async] calls can be used within this block 
            // to handle a resource by one thread. 
        }
    }
}

Gets byte array from a ByteBuffer in java

Note that the bb.array() doesn't honor the byte-buffers position, and might be even worse if the bytebuffer you are working on is a slice of some other buffer.

I.e.

byte[] test = "Hello World".getBytes("Latin1");
ByteBuffer b1 = ByteBuffer.wrap(test);
byte[] hello = new byte[6];
b1.get(hello); // "Hello "
ByteBuffer b2 = b1.slice(); // position = 0, string = "World"
byte[] tooLong = b2.array(); // Will NOT be "World", but will be "Hello World".
byte[] world = new byte[5];
b2.get(world); // world = "World"

Which might not be what you intend to do.

If you really do not want to copy the byte-array, a work-around could be to use the byte-buffer's arrayOffset() + remaining(), but this only works if the application supports index+length of the byte-buffers it needs.

SQL: How to properly check if a record exists

You can use:

SELECT COUNT(1) FROM MyTable WHERE ... 

or

WHERE [NOT] EXISTS 
( SELECT 1 FROM MyTable WHERE ... )

This will be more efficient than SELECT * since you're simply selecting the value 1 for each row, rather than all the fields.

There's also a subtle difference between COUNT(*) and COUNT(column name):

  • COUNT(*) will count all rows, including nulls
  • COUNT(column name) will only count non null occurrences of column name

Calculating frames per second in a game

This is what I have used in many games.

#define MAXSAMPLES 100
int tickindex=0;
int ticksum=0;
int ticklist[MAXSAMPLES];

/* need to zero out the ticklist array before starting */
/* average will ramp up until the buffer is full */
/* returns average ticks per frame over the MAXSAMPLES last frames */

double CalcAverageTick(int newtick)
{
    ticksum-=ticklist[tickindex];  /* subtract value falling off */
    ticksum+=newtick;              /* add new value */
    ticklist[tickindex]=newtick;   /* save new value so it can be subtracted later */
    if(++tickindex==MAXSAMPLES)    /* inc buffer index */
        tickindex=0;

    /* return average */
    return((double)ticksum/MAXSAMPLES);
}

Oracle pl-sql escape character (for a " ' ")

SELECT q'[Alex's Tea Factory]' FROM DUAL

@import vs #import - iOS 7

It's a new feature called Modules or "semantic import". There's more info in the WWDC 2013 videos for Session 205 and 404. It's kind of a better implementation of the pre-compiled headers. You can use modules with any of the system frameworks in iOS 7 and Mavericks. Modules are a packaging together of the framework executable and its headers and are touted as being safer and more efficient than #import.

One of the big advantages of using @import is that you don't need to add the framework in the project settings, it's done automatically. That means that you can skip the step where you click the plus button and search for the framework (golden toolbox), then move it to the "Frameworks" group. It will save many developers from the cryptic "Linker error" messages.

You don't actually need to use the @import keyword. If you opt-in to using modules, all #import and #include directives are mapped to use @import automatically. That means that you don't have to change your source code (or the source code of libraries that you download from elsewhere). Supposedly using modules improves the build performance too, especially if you haven't been using PCHs well or if your project has many small source files.

Modules are pre-built for most Apple frameworks (UIKit, MapKit, GameKit, etc). You can use them with frameworks you create yourself: they are created automatically if you create a Swift framework in Xcode, and you can manually create a ".modulemap" file yourself for any Apple or 3rd-party library.

You can use code-completion to see the list of available frameworks:

enter image description here

Modules are enabled by default in new projects in Xcode 5. To enable them in an older project, go into your project build settings, search for "Modules" and set "Enable Modules" to "YES". The "Link Frameworks" should be "YES" too:

You have to be using Xcode 5 and the iOS 7 or Mavericks SDK, but you can still release for older OSs (say iOS 4.3 or whatever). Modules don't change how your code is built or any of the source code.


From the WWDC slides:

  • Imports complete semantic description of a framework
  • Doesn't need to parse the headers
  • Better way to import a framework’s interface
  • Loads binary representation
  • More flexible than precompiled headers
  • Immune to effects of local macro definitions (e.g. #define readonly 0x01)
  • Enabled for new projects by default

To explicitly use modules:

Replace #import <Cocoa/Cocoa.h> with @import Cocoa;

You can also import just one header with this notation:

@import iAd.ADBannerView;

The submodules autocomplete for you in Xcode.

Why is my JavaScript function sometimes "not defined"?

If you're changing the prototype of the built-in 'function' object it's possible you're running into a browser bug or race condition by modifying a fundamental built-in object.

Test it in multiple browsers to find out.

Request exceeded the limit of 10 internal redirects due to probable configuration error

//Just add 

RewriteBase /
//after 
RewriteEngine On

//and you are done....

//so it should be 

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]

Get the last item in an array

Performance

Today 2020.05.16 I perform tests of chosen solutions on Chrome v81.0, Safari v13.1 and Firefox v76.0 on MacOs High Sierra v10.13.6

Conclusions

  • arr[arr.length-1] (D) is recommended as fastest cross-browser solution
  • mutable solution arr.pop() (A) and immutable _.last(arr) (L) are fast
  • solutions I, J are slow for long strings
  • solutions H, K (jQuery) are slowest on all browsers

enter image description here

Details

I test two cases for solutions:

  • mutable: A, B, C,

  • immutable: D, E, F, G, H, I, J (my),

  • immutable from external libraries: K, L, M,

for two cases

  • short string - 10 characters - you can run test HERE
  • long string - 1M characters - you can run test HERE

_x000D_
_x000D_
function A(arr) {
  return arr.pop();
}

function B(arr) {  
  return arr.splice(-1,1);
}

function C(arr) {  
  return arr.reverse()[0]
}

function D(arr) {
  return arr[arr.length - 1];
}

function E(arr) {
  return arr.slice(-1)[0] ;
}

function F(arr) {
  let [last] = arr.slice(-1);
  return last;
}

function G(arr) {
  return arr.slice(-1).pop();
}

function H(arr) {
  return [...arr].pop();
}

function I(arr) {  
  return arr.reduceRight(a => a);
}

function J(arr) {  
  return arr.find((e,i,a)=> a.length==i+1);
}

function K(arr) {  
  return $(arr).get(-1);
}

function L(arr) {  
  return _.last(arr);
}

function M(arr) {  
  return _.nth(arr, -1);
}






// ----------
// TEST
// ----------

let loc_array=["domain","a","b","c","d","e","f","g","h","file"];

log = (f)=> console.log(`${f.name}: ${f([...loc_array])}`);

[A,B,C,D,E,F,G,H,I,J,K,L,M].forEach(f=> log(f));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js" integrity="sha256-VeNaFBVDhoX3H+gJ37DpT/nTuZTdjYro9yBruHjVmoQ=" crossorigin="anonymous"></script>
_x000D_
_x000D_
_x000D_

Example results for Chrome for short string

enter image description here

MySQL "Group By" and "Order By"

Here's one approach:

SELECT cur.textID, cur.fromEmail, cur.subject, 
     cur.timestamp, cur.read
FROM incomingEmails cur
LEFT JOIN incomingEmails next
    on cur.fromEmail = next.fromEmail
    and cur.timestamp < next.timestamp
WHERE next.timestamp is null
and cur.toUserID = '$userID' 
ORDER BY LOWER(cur.fromEmail)

Basically, you join the table on itself, searching for later rows. In the where clause you state that there cannot be later rows. This gives you only the latest row.

If there can be multiple emails with the same timestamp, this query would need refining. If there's an incremental ID column in the email table, change the JOIN like:

LEFT JOIN incomingEmails next
    on cur.fromEmail = next.fromEmail
    and cur.id < next.id

How can I use Ruby to colorize the text output to a terminal?

Colorize is my favorite gem! :-)

Check it out:

https://github.com/fazibear/colorize

Installation:

gem install colorize

Usage:

require 'colorize'

puts "I am now red".red
puts "I am now blue".blue
puts "Testing".yellow

C# Lambda expressions: Why should I use them?

I found them useful in a situation when I wanted to declare a handler for some control's event, using another control. To do it normally you would have to store controls' references in fields of the class so that you could use them in a different method than they were created.

private ComboBox combo;
private Label label;

public CreateControls()
{
    combo = new ComboBox();
    label = new Label();
    //some initializing code
    combo.SelectedIndexChanged += new EventHandler(combo_SelectedIndexChanged);
}

void combo_SelectedIndexChanged(object sender, EventArgs e)
{
    label.Text = combo.SelectedValue;
}

thanks to lambda expressions you can use it like this:

public CreateControls()
{
    ComboBox combo = new ComboBox();
    Label label = new Label();
    //some initializing code
    combo.SelectedIndexChanged += (s, e) => {label.Text = combo.SelectedValue;};
}

Much easier.

Selecting multiple columns/fields in MySQL subquery

Yes, you can do this. The knack you need is the concept that there are two ways of getting tables out of the table server. One way is ..

FROM TABLE A

The other way is

FROM (SELECT col as name1, col2 as name2 FROM ...) B

Notice that the select clause and the parentheses around it are a table, a virtual table.

So, using your second code example (I am guessing at the columns you are hoping to retrieve here):

SELECT a.attr, b.id, b.trans, b.lang
FROM attribute a
JOIN (
 SELECT at.id AS id, at.translation AS trans, at.language AS lang, a.attribute
 FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)

Notice that your real table attribute is the first table in this join, and that this virtual table I've called b is the second table.

This technique comes in especially handy when the virtual table is a summary table of some kind. e.g.

SELECT a.attr, b.id, b.trans, b.lang, c.langcount
FROM attribute a
JOIN (
 SELECT at.id AS id, at.translation AS trans, at.language AS lang, at.attribute
 FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)
JOIN (
 SELECT count(*) AS langcount,  at.attribute
 FROM attributeTranslation at
 GROUP BY at.attribute
) c ON (a.id = c.attribute)

See how that goes? You've generated a virtual table c containing two columns, joined it to the other two, used one of the columns for the ON clause, and returned the other as a column in your result set.

Detect IE version (prior to v9) in JavaScript

This is my preferred way of doing it. It gives maximum control. (Note: Conditional statements are only supported in IE5 - 9.)

First set up your ie classes correctly

<!DOCTYPE html>
<!--[if lt IE 7]> <html class="lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>    <html class="lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>    <html class="lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html> <!--<![endif]-->    
<head>

Then you can just use CSS to make style exceptions, or, if you require, you can add some simple JavaScript:

(function ($) {
    "use strict";

    // Detecting IE
    var oldIE;
    if ($('html').is('.lt-ie7, .lt-ie8, .lt-ie9')) {
        oldIE = true;
    }

    if (oldIE) {
        // Here's your JS for IE..
    } else {
        // ..And here's the full-fat code for everyone else
    }

}(jQuery));

Thanks to Paul Irish.

window.onload vs document.onload

The general idea is that window.onload fires when the document's window is ready for presentation and document.onload fires when the DOM tree (built from the markup code within the document) is completed.

Ideally, subscribing to DOM-tree events, allows offscreen-manipulations through Javascript, incurring almost no CPU load. Contrarily, window.onload can take a while to fire, when multiple external resources have yet to be requested, parsed and loaded.

?Test scenario:

To observe the difference and how your browser of choice implements the aforementioned event handlers, simply insert the following code within your document's - <body>- tag.

<script language="javascript">
window.tdiff = []; fred = function(a,b){return a-b;};
window.document.onload = function(e){ 
    console.log("document.onload", e, Date.now() ,window.tdiff,  
    (window.tdiff[0] = Date.now()) && window.tdiff.reduce(fred) ); 
}
window.onload = function(e){ 
    console.log("window.onload", e, Date.now() ,window.tdiff, 
    (window.tdiff[1] = Date.now()) && window.tdiff.reduce(fred) ); 
}
</script>

?Result:

Here is the resulting behavior, observable for Chrome v20 (and probably most current browsers).

  • No document.onload event.
  • onload fires twice when declared inside the <body>, once when declared inside the <head> (where the event then acts as document.onload ).
  • counting and acting dependent on the state of the counter allows to emulate both event behaviors.
  • Alternatively declare the window.onload event handler within the confines of the HTML-<head> element.

?Example Project:

The code above is taken from this project's codebase (index.html and keyboarder.js).


For a list of event handlers of the window object, please refer to the MDN documentation.

How do you remove a specific revision in the git history?

I also landed in a similar situation. Use interactive rebase using the command below and while selecting, drop 3rd commit.

git rebase -i remote/branch

App.Config change value

when use "ConfigurationUserLevel.None" your code is right run when you click in nameyourapp.exe in debug folder. .
but when your do developing app on visual stdio not right run!! because "vshost.exe" is run.

following parameter solve this problem : "Application.ExecutablePath"

try this : (Tested in VS 2012 Express For Desktop)

Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
config.AppSettings.Settings["PortName"].Value = "com3";
config.Save(ConfigurationSaveMode.Minimal);

my english not good , i am sorry.

Can't connect to MySQL server on 'localhost' (10061)

run > services.msc > rightclick MySQL57 > properties >set start type option to automatic

after restarting computer

At cmd

cd: C:\

C :\> cd "C:\Program Files\MySQL\MySQL Server 5.7\bin"

it will become

C:\Program Files\MySQL\MySQL Server 5.7\bin>

type mysql -u root -p

ie C:\Program Files\MySQL\MySQL Server 5.7\bin> mysql -u root -p

Enter password: ****

That's all

It will result in

mysql>

How to fix "Your Ruby version is 2.3.0, but your Gemfile specified 2.2.5" while server starting

If you are using rbenv then make sure that you run the "rbenv rehash" command after you set local or global ruby version. It solved the issue for me.

rbenv rehash

How do I change the value of a global variable inside of a function

var a = 10;

myFunction(a);

function myFunction(a){
   window['a'] = 20; // or window.a
}

alert("Value of 'a' outside the function " + a); //outputs 20

With window['variableName'] or window.variableName you can modify the value of a global variable inside a function.

How to load data to hive from HDFS without removing the source file?

An alternative to 'LOAD DATA' is available in which the data will not be moved from your existing source location to hive data warehouse location.

You can use ALTER TABLE command with 'LOCATION' option. Here is below required command

ALTER TABLE table_name ADD PARTITION (date_col='2017-02-07') LOCATION 'hdfs/path/to/location/'

The only condition here is, the location should be a directory instead of file.

Hope this will solve the problem.

Pass request headers in a jQuery AJAX GET call

As of jQuery 1.5, there is a headers hash you can pass in as follows:

$.ajax({
    url: "/test",
    headers: {"X-Test-Header": "test-value"}
});

From http://api.jquery.com/jQuery.ajax:

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

R ggplot2: stat_count() must not be used with a y aesthetic error in Bar graph

I was looking for the same and this may also work

p.Wages.all.A_MEAN <- Wages.all %>%
                  group_by(`Career Cluster`, Year)%>%
                  summarize(ANNUAL.MEAN.WAGE = mean(A_MEAN))

names(p.Wages.all.A_MEAN) [1] "Career Cluster" "Year" "ANNUAL.MEAN.WAGE"

p.Wages.all.a.mean <- ggplot(p.Wages.all.A_MEAN, aes(Year, ANNUAL.MEAN.WAGE , color= `Career Cluster`))+
                  geom_point(aes(col=`Career Cluster` ), pch=15, size=2.75, alpha=1.5/4)+
                  theme(axis.text.x = element_text(color="#993333",  size=10, angle=0)) #face="italic",
p.Wages.all.a.mean

JPA COUNT with composite primary key query not working

Use count(d.ertek) or count(d.id) instead of count(d). This can be happen when you have composite primary key at your entity.

sed: print only matching group

The cut command is designed for this exact situation. It will "cut" on any delimiter and then you can specify which chunks should be output.

For instance: echo "foo bar <foo> bla 1 2 3.4" | cut -d " " -f 6-7

Will result in output of: 2 3.4

-d sets the delimiter

-f selects the range of 'fields' to output, in this case, it's the 6th through 7th chunks of the original string. You can also specify the range as a list, such as 6,7.

python dictionary sorting in descending order based on values

Whenever one has a dictionary where the values are integers, the Counter data structure is often a better choice to represent the data than a dictionary.

If you already have a dictionary, a counter can easily be formed by:

c = Counter(d['123'])

as an example from your data.

The most_common function allows easy access to descending order of the items in the counter

The more complete writeup on the Counter data structure is at https://docs.python.org/2/library/collections.html

How can I change NULL to 0 when getting a single value from a SQL function?

You can use ISNULL().

SELECT ISNULL(SUM(Price), 0) AS TotalPrice 
FROM Inventory
WHERE (DateAdded BETWEEN @StartDate AND @EndDate)

That should do the trick.

How to combine two byte arrays

You're just trying to concatenate the two byte arrays?

byte[] one = getBytesForOne();
byte[] two = getBytesForTwo();
byte[] combined = new byte[one.length + two.length];

for (int i = 0; i < combined.length; ++i)
{
    combined[i] = i < one.length ? one[i] : two[i - one.length];
}

Or you could use System.arraycopy:

byte[] one = getBytesForOne();
byte[] two = getBytesForTwo();
byte[] combined = new byte[one.length + two.length];

System.arraycopy(one,0,combined,0         ,one.length);
System.arraycopy(two,0,combined,one.length,two.length);

Or you could just use a List to do the work:

byte[] one = getBytesForOne();
byte[] two = getBytesForTwo();

List<Byte> list = new ArrayList<Byte>(Arrays.<Byte>asList(one));
list.addAll(Arrays.<Byte>asList(two));

byte[] combined = list.toArray(new byte[list.size()]);

Or you could simply use ByteBuffer with the advantage of adding many arrays.

byte[] allByteArray = new byte[one.length + two.length + three.length];

ByteBuffer buff = ByteBuffer.wrap(allByteArray);
buff.put(one);
buff.put(two);
buff.put(three);

byte[] combined = buff.array();

Start thread with member function

Since you are using C++11, lambda-expression is a nice&clean solution.

class blub {
    void test() {}
  public:
    std::thread spawn() {
      return std::thread( [this] { this->test(); } );
    }
};

since this-> can be omitted, it could be shorten to:

std::thread( [this] { test(); } )

or just (deprecated)

std::thread( [=] { test(); } )

What is the canonical way to check for errors using the CUDA runtime API?

The solution discussed here worked well for me. This solution uses built-in cuda functions and is very simple to implement.

The relevant code is copied below:

#include <stdio.h>
#include <stdlib.h>

__global__ void foo(int *ptr)
{
  *ptr = 7;
}

int main(void)
{
  foo<<<1,1>>>(0);

  // make the host block until the device is finished with foo
  cudaDeviceSynchronize();

  // check for error
  cudaError_t error = cudaGetLastError();
  if(error != cudaSuccess)
  {
    // print the CUDA error message and exit
    printf("CUDA error: %s\n", cudaGetErrorString(error));
    exit(-1);
  }

  return 0;
}

Java Date cut off time information

From java.util.Date JavaDocs:

The class Date represents a specific instant in time, with millisecond precision

and from the java.sql.Date JavaDocs:

To conform with the definition of SQL DATE, the millisecond values wrapped by a java.sql.Date instance must be 'normalized' by setting the hours, minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is associated.

So, the best approach is to use java.sql.Date if you are not in need of the time part

java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(System.currentTimeMillis());

and the output is:

java.util.Date : Thu Apr 26 16:22:53 PST 2012
java.sql.Date  : 2012-04-26

Delete the 'first' record from a table in SQL Server, without a WHERE condition

depends on your DBMS (people don't seem to know what that is nowadays)

-- MYSql:
DELETE FROM table LIMIT 1;
-- Postgres:
DELETE FROM table LIMIT 1;
-- MSSql:
DELETE TOP(1) FROM table;
-- Oracle:
DELETE FROM table WHERE ROWNUM = 1;

Magento: Set LIMIT on collection

You can Implement this also:- setPage(1, n); where, n = any number.

$products = Mage::getResourceModel('catalog/product_collection')
                ->addAttributeToSelect('*')
                ->addAttributeToSelect(array('name', 'price', 'small_image'))
                ->addFieldToFilter('visibility', Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH) //visible only catalog & searchable product
                ->addAttributeToFilter('status', 1) // enabled
                ->setStoreId($storeId)
                ->setOrder('created_at', 'desc')
                ->setPage(1, 6);

Can I give a default value to parameters or optional parameters in C# functions?

This is a feature of C# 4.0, but was not possible without using function overload prior to that version.

AngularJS multiple filter with custom filter function

Try this:

<tr ng-repeat="player in players | filter:{id: player_id, name:player_name} | filter:ageFilter">

$scope.ageFilter = function (player) {
    return (player.age > $scope.min_age && player.age < $scope.max_age);
}

How to force addition instead of concatenation in javascript

The following statement appends the value to the element with the id of response

$('#response').append(total);

This makes it look like you are concatenating the strings, but you aren't, you're actually appending them to the element

change that to

$('#response').text(total);

You need to change the drop event so that it replaces the value of the element with the total, you also need to keep track of what the total is, I suggest something like the following

$(function() {
    var data = [];
    var total = 0;

    $( "#draggable1" ).draggable();
    $( "#draggable2" ).draggable();
    $( "#draggable3" ).draggable();

    $("#droppable_box").droppable({
        drop: function(event, ui) {
        var currentId = $(ui.draggable).attr('id');
        data.push($(ui.draggable).attr('id'));

        if(currentId == "draggable1"){
            var myInt1 = parseFloat($('#MealplanCalsPerServing1').val());
        }
        if(currentId == "draggable2"){
            var myInt2 = parseFloat($('#MealplanCalsPerServing2').val());
        }
        if(currentId == "draggable3"){
            var myInt3 = parseFloat($('#MealplanCalsPerServing3').val());
        }
        if ( typeof myInt1 === 'undefined' || !myInt1 ) {
            myInt1 = parseInt(0);
        }
        if ( typeof myInt2 === 'undefined' || !myInt2){
            myInt2 = parseInt(0);
        }
        if ( typeof myInt3 === 'undefined' || !myInt3){
        myInt3 = parseInt(0);
        }
        total += parseFloat(myInt1 + myInt2 + myInt3);
        $('#response').text(total);
        }
    });

    $('#myId').click(function(event) {
        $.post("process.php", ({ id: data }), function(return_data, status) {
            alert(data);
            //alert(total);
        });
    });
});

I moved the var total = 0; statement out of the drop event and changed the assignment statment from this

total = parseFloat(myInt1 + myInt2 + myInt3);

to this

total += parseFloat(myInt1 + myInt2 + myInt3);

Here is a working example http://jsfiddle.net/axrwkr/RCzGn/

Reverse a string without using reversed() or [::-1]?

def reverse(s):
    return "".join(s[i] for i in range(len(s)-1, -1, -1))

C++ auto keyword. Why is it magic?

The auto keyword is an important and frequently used keyword for C ++.When initializing a variable, auto keyword is used for type inference(also called type deduction).

There are 3 different rules regarding the auto keyword.

First Rule

auto x = expr; ----> No pointer or reference, only variable name. In this case, const and reference are ignored.

int  y = 10;
int& r = y;
auto x = r; // The type of variable x is int. (Reference Ignored)

const int y = 10;
auto x = y; // The type of variable x is int. (Const Ignored)

int y = 10;
const int& r = y;
auto x = r; // The type of variable x is int. (Both const and reference Ignored)

const int a[10] = {};
auto x = a; //  x is const int *. (Array to pointer conversion)

Note : When the name defined by auto is given a value with the name of a function,
       the type inference will be done as a function pointer.

Second Rule

auto& y = expr; or auto* y = expr; ----> Reference or pointer after auto keyword.

Warning : const is not ignored in this rule !!! .

int y = 10;
auto& x = y; // The type of variable x is int&.

Warning : In this rule, array to pointer conversion (array decay) does not occur !!!.

auto& x = "hello"; // The type of variable x is  const char [6].

static int x = 10;
auto y = x; // The variable y is not static.Because the static keyword is not a type. specifier 
            // The type of variable x is int.

Third Rule

auto&& z = expr; ----> This is not a Rvalue reference.

Warning : If the type inference is in question and the && token is used, the names introduced like this are called "Forwarding Reference" (also called Universal Reference).

auto&& r1 = x; // The type of variable r1 is int&.Because x is Lvalue expression. 

auto&& r2 = x+y; // The type of variable r2 is int&&.Because x+y is PRvalue expression. 

ClientAbortException: java.net.SocketException: Connection reset by peer: socket write error

Your log indicates ClientAbortException, which occurs when your HTTP client drops the connection with the server and this happened before server could close the server socket Connection.

"Operation must use an updateable query" error in MS Access

To update records, you need to write changes to .mdb file on disk. If your web/shared application can't write to disk, you can't update existing or add new records. So, enable read/write access in database folder or move database to other folder where your application has write permission....for more detail please check:

http://www.beansoftware.com/ASP.NET-FAQ/Operation-Must-Use-An-Updateable-Query.aspx

Forwarding port 80 to 8080 using NGINX

As simple as like this,

make sure to change example.com to your domain (or IP), and 8080 to your Node.js application port:

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_set_header   X-Forwarded-For $remote_addr;
        proxy_set_header   Host $http_host;
        proxy_pass         "http://127.0.0.1:8080";
    }
}

Source: https://eladnava.com/binding-nodejs-port-80-using-nginx/

How can I let a table's body scroll but keep its head fixed in place?

I do this with javascript (no library) and CSS - the table body scrolls with the page, and the table does not have to be fixed width or height, although each column must have a width. You can also keep sorting functionality.

Basically:

  1. In HTML, create container divs to position the table header row and the table body, also create a "mask" div to hide the table body as it scrolls past the header

  2. In CSS, convert the table parts to blocks

  3. In Javascript, get the table width and match the mask's width... get the height of the page content... measure scroll position... manipulate CSS to set the table header row position and the mask height

Here's the javascript and a jsFiddle DEMO.

// get table width and match the mask width

function setMaskWidth() { 
  if (document.getElementById('mask') !==null) {
    var tableWidth = document.getElementById('theTable').offsetWidth;

    // match elements to the table width
    document.getElementById('mask').style.width = tableWidth + "px";
   }
}

function fixTop() {

  // get height of page content 
  function getScrollY() {
      var y = 0;
      if( typeof ( window.pageYOffset ) == 'number' ) {
        y = window.pageYOffset;
      } else if ( document.body && ( document.body.scrollTop) ) {
        y = document.body.scrollTop;
      } else if ( document.documentElement && ( document.documentElement.scrollTop) ) {
        y = document.documentElement.scrollTop;
      }
      return [y];
  }  

  var y = getScrollY();
  var y = y[0];

  if (document.getElementById('mask') !==null) {
      document.getElementById('mask').style.height = y + "px" ;

      if (document.all && document.querySelector && !document.addEventListener) {
        document.styleSheets[1].rules[0].style.top = y + "px" ;
      } else {
        document.styleSheets[1].cssRules[0].style.top = y + "px" ;
      }
  }

}

window.onscroll = function() {
  setMaskWidth();
  fixTop();
}

m2eclipse not finding maven dependencies, artifacts not found

I had problems with using m2eclipse (i.e. it did not appear to be installed at all) but I develop a project using IAM - maven plugin for eclipse supported by Eclipse Foundation (or hosted or something like that).

I had sometimes problems as sometimes some strange error appeared for project (it couldn't move something) but simple command (run from eclipse as task or from console) + refresh (F5) solved all problems:

mvn clean

However please note that I created project in eclipse. However I modified pom.xml by hand.

Java ArrayList how to add elements at the beginning

you can use this code

private List myList = new ArrayList();
private void addItemToList(Object obj){
    if(myList.size()<10){
      myList.add(0,obj);
    }else{
      myList.add(0,obj);
      myList.remove(10);
    }
}

How to get time difference in minutes in PHP

$date1=date_create("2020-03-15");
$date2=date_create("2020-12-12");
$diff=date_diff($date1,$date2);
echo $diff->format("%R%a days");

For detailed format specifiers, visit the link.

Property 'value' does not exist on type EventTarget in TypeScript

Here's another fix that works for me:

(event.target as HTMLInputElement).value

That should get rid of the error by letting TS know that event.target is an HTMLInputElement, which inherently has a value. Before specifying, TS likely only knew that event alone was an HTMLInputElement, thus according to TS the keyed-in target was some randomly mapped value that could be anything.

How to set selected value of jquery select2?

Set the value and trigger the change event immediately.

$('#selectteam').val([183,182]).trigger('change');

highlight the navigation menu for the current page

I usually use a class to achieve this. It's very simple to implement to anything, navigation links, hyperlinks and etc.

In your CSS document insert:

.current,
nav li a:hover {
   /* styles go here */
   color: #e00122;
   background-color: #fffff;
}

This will make the hover state of the list items have red text and a white background. Attach that class of current to any link on the "current" page and it will display the same styles.

Im your HTML insert:

<nav>
   <ul>
      <li class="current"><a href="#">Nav Item 1</a></li>
      <li><a href="#">Nav Item 2</a></li>
      <li><a href="#">Nav Item 3</a></li>
   </ul>
</nav>

How to change spinner text size and text color?

First we have to create the simple xml resource file for the textview like as below:

<?xml version="1.0" encoding="utf-8"?>

 <TextView  
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" 
    android:layout_height="wrap_content"
    android:textSize="20sp"
    android:gravity="left"  
    android:textColor="#FF0000"         
    android:padding="5dip"
    />   

and save it. after set on your adapterlist.

VBA Excel - Insert row below with same format including borders and frames

well, using the Macro record, and doing it manually, I ended up with this code .. which seems to work .. (although it's not a one liner like yours ;)

lrow = Selection.Row()
Rows(lrow).Select
Selection.Copy
Rows(lrow + 1).Select
Selection.Insert Shift:=xlDown
Application.CutCopyMode = False
Selection.ClearContents

(I put the ClearContents in there because you indicated you wanted format, and I'm assuming you didn't want the data ;) )

GIT fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree

I usually use git on my linux machine, but at work I have to use Windows. I had the same problem when trying to commit the first commit in a Windows environment.

For those still facing this problem, I was able to resolve it as follows:

$ git commit --allow-empty -n -m "Initial commit".

Writing an Excel file in EPPlus

If you have a collection of objects that you load using stored procedure you can also use LoadFromCollection.

using (ExcelPackage package = new ExcelPackage(file))
{
    ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("test");

    worksheet.Cells["A1"].LoadFromCollection(myColl, true, OfficeOpenXml.Table.TableStyles.Medium1);

    package.Save();
}

Function to calculate R2 (R-squared) in R

Not sure why this isn't implemented directly in R, but this answer is essentially the same as Andrii's and Wordsforthewise, I just turned into a function for the sake of convenience if somebody uses it a lot like me.

r2_general <-function(preds,actual){ 
  return(1- sum((preds - actual) ^ 2)/sum((actual - mean(actual))^2))
}

How to configure Chrome's Java plugin so it uses an existing JDK in the machine

Starting with Version 42, released April 14, 2015, Chrome blocks all NPAPI plugins, including Java. Until September 2015 there will be a way around this, by going to chrome://flags/#enable-npapi and clicking on Enable. After that, you will have to use the IE tab extension to run the Direct-X version of the Java plugin.

How can I disable the bootstrap hover color for links?

if anyone cares i ended up with:

a {
    color: inherit;
}

How to download a file over HTTP?

I wanted do download all the files from a webpage. I tried wget but it was failing so I decided for the Python route and I found this thread.

After reading it, I have made a little command line application, soupget, expanding on the excellent answers of PabloG and Stan and adding some useful options.

It uses BeatifulSoup to collect all the URLs of the page and then download the ones with the desired extension(s). Finally it can download multiple files in parallel.

Here it is:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import (division, absolute_import, print_function, unicode_literals)
import sys, os, argparse
from bs4 import BeautifulSoup

# --- insert Stan's script here ---
# if sys.version_info >= (3,): 
#...
#...
# def download_file(url, dest=None): 
#...
#...

# --- new stuff ---
def collect_all_url(page_url, extensions):
    """
    Recovers all links in page_url checking for all the desired extensions
    """
    conn = urllib2.urlopen(page_url)
    html = conn.read()
    soup = BeautifulSoup(html, 'lxml')
    links = soup.find_all('a')

    results = []    
    for tag in links:
        link = tag.get('href', None)
        if link is not None: 
            for e in extensions:
                if e in link:
                    # Fallback for badly defined links
                    # checks for missing scheme or netloc
                    if bool(urlparse.urlparse(link).scheme) and bool(urlparse.urlparse(link).netloc):
                        results.append(link)
                    else:
                        new_url=urlparse.urljoin(page_url,link)                        
                        results.append(new_url)
    return results

if __name__ == "__main__":  # Only run if this file is called directly
    # Command line arguments
    parser = argparse.ArgumentParser(
        description='Download all files from a webpage.')
    parser.add_argument(
        '-u', '--url', 
        help='Page url to request')
    parser.add_argument(
        '-e', '--ext', 
        nargs='+',
        help='Extension(s) to find')    
    parser.add_argument(
        '-d', '--dest', 
        default=None,
        help='Destination where to save the files')
    parser.add_argument(
        '-p', '--par', 
        action='store_true', default=False, 
        help="Turns on parallel download")
    args = parser.parse_args()

    # Recover files to download
    all_links = collect_all_url(args.url, args.ext)

    # Download
    if not args.par:
        for l in all_links:
            try:
                filename = download_file(l, args.dest)
                print(l)
            except Exception as e:
                print("Error while downloading: {}".format(e))
    else:
        from multiprocessing.pool import ThreadPool
        results = ThreadPool(10).imap_unordered(
            lambda x: download_file(x, args.dest), all_links)
        for p in results:
            print(p)

An example of its usage is:

python3 soupget.py -p -e <list of extensions> -d <destination_folder> -u <target_webpage>

And an actual example if you want to see it in action:

python3 soupget.py -p -e .xlsx .pdf .csv -u https://healthdata.gov/dataset/chemicals-cosmetics

$apply already in progress error

At any point in time, there can be only one $digest or $apply operation in progress. This is to prevent very hard to detect bugs from entering your application. The stack trace of this error allows you to trace the origin of the currently executing $apply or $digest call, which caused the error.

More info: https://docs.angularjs.org/error/$rootScope/inprog?p0=$apply

Converting timestamp to time ago in PHP e.g 1 day ago, 2 days ago...

I usually use this to find out difference between current and passed datetime stamp

OUTPUT

//If difference is greater than 7 days
7 June 2019

// if difference is greater than 24 hours and less than 7 days
1 days ago
6 days ago

1 hour ago
23 hours ago

1 minute ago
58 minutes ago

1 second ago
20 seconds ago

CODE

//return current date time
function getCurrentDateTime(){
    //date_default_timezone_set("Asia/Calcutta");
    return date("Y-m-d H:i:s");
}
function getDateString($date){
    $dateArray = date_parse_from_format('Y/m/d', $date);
    $monthName = DateTime::createFromFormat('!m', $dateArray['month'])->format('F');
    return $dateArray['day'] . " " . $monthName  . " " . $dateArray['year'];
}

function getDateTimeDifferenceString($datetime){
    $currentDateTime = new DateTime(getCurrentDateTime());
    $passedDateTime = new DateTime($datetime);
    $interval = $currentDateTime->diff($passedDateTime);
    //$elapsed = $interval->format('%y years %m months %a days %h hours %i minutes %s seconds');
    $day = $interval->format('%a');
    $hour = $interval->format('%h');
    $min = $interval->format('%i');
    $seconds = $interval->format('%s');

    if($day > 7)
        return getDateString($datetime);
    else if($day >= 1 && $day <= 7 ){
        if($day == 1) return $day . " day ago";
        return $day . " days ago";
    }else if($hour >= 1 && $hour <= 24){
        if($hour == 1) return $hour . " hour ago";
        return $hour . " hours ago";
    }else if($min >= 1 && $min <= 60){
        if($min == 1) return $min . " minute ago";
        return $min . " minutes ago";
    }else if($seconds >= 1 && $seconds <= 60){
        if($seconds == 1) return $seconds . " second ago";
        return $seconds . " seconds ago";
    }
}

Radio button validation in javascript

1st: If you know that your code isn't right, you should fix it before do anything!

You could do something like this:

function validateForm() {
    var radios = document.getElementsByName("yesno");
    var formValid = false;

    var i = 0;
    while (!formValid && i < radios.length) {
        if (radios[i].checked) formValid = true;
        i++;        
    }

    if (!formValid) alert("Must check some option!");
    return formValid;
}?

See it in action: http://jsfiddle.net/FhgQS/

Python progression path - From apprentice to guru

Understand Introspection

  • write a dir() equivalent
  • write a type() equivalent
  • figure out how to "monkey-patch"
  • use the dis module to see how various language constructs work

Doing these things will

  • give you some good theoretical knowledge about how python is implemented
  • give you some good practical experience in lower-level programming
  • give you a good intuitive feel for python data structures

minimize app to system tray

don't forget to add icon file to your notifyIcon or it will not appear in the tray.

How to Use Content-disposition for force a file to download to the hard drive?

With recent browsers you can use the HTML5 download attribute as well:

<a download="quot.pdf" href="../doc/quot.pdf">Click here to Download quotation</a>

It is supported by most of the recent browsers except MSIE11. You can use a polyfill, something like this (note that this is for data uri only, but it is a good start):

(function (){

    addEvent(window, "load", function (){
        if (isInternetExplorer())
            polyfillDataUriDownload();
    });

    function polyfillDataUriDownload(){
        var links = document.querySelectorAll('a[download], area[download]');
        for (var index = 0, length = links.length; index<length; ++index) {
            (function (link){
                var dataUri = link.getAttribute("href");
                var fileName = link.getAttribute("download");
                if (dataUri.slice(0,5) != "data:")
                    throw new Error("The XHR part is not implemented here.");
                addEvent(link, "click", function (event){
                    cancelEvent(event);
                    try {
                        var dataBlob = dataUriToBlob(dataUri);
                        forceBlobDownload(dataBlob, fileName);
                    } catch (e) {
                        alert(e)
                    }
                });
            })(links[index]);
        }
    }

    function forceBlobDownload(dataBlob, fileName){
        window.navigator.msSaveBlob(dataBlob, fileName);
    }

    function dataUriToBlob(dataUri) {
        if  (!(/base64/).test(dataUri))
            throw new Error("Supports only base64 encoding.");
        var parts = dataUri.split(/[:;,]/),
            type = parts[1],
            binData = atob(parts.pop()),
            mx = binData.length,
            uiArr = new Uint8Array(mx);
        for(var i = 0; i<mx; ++i)
            uiArr[i] = binData.charCodeAt(i);
        return new Blob([uiArr], {type: type});
    }

    function addEvent(subject, type, listener){
        if (window.addEventListener)
            subject.addEventListener(type, listener, false);
        else if (window.attachEvent)
            subject.attachEvent("on" + type, listener);
    }

    function cancelEvent(event){
        if (event.preventDefault)
            event.preventDefault();
        else
            event.returnValue = false;
    }

    function isInternetExplorer(){
        return /*@cc_on!@*/false || !!document.documentMode;
    }
    
})();

What is a Data Transfer Object (DTO)?

In general Value Objects should be Immutable. Like Integer or String objects in Java. We can use them for transferring data between software layers. If the software layers or services running in different remote nodes like in a microservices environment or in a legacy Java Enterprise App. We must make almost exact copies of two classes. This is the where we met DTOs.

|-----------|                                                   |--------------|
| SERVICE 1 |--> Credentials DTO >--------> Credentials DTO >-- | AUTH SERVICE |
|-----------|                                                   |--------------|

In legacy Java Enterprise Systems DTOs can have various EJB stuff in it.

I do not know this is a best practice or not but I personally use Value Objects in my Spring MVC/Boot Projects like this:

        |------------|         |------------------|                             |------------|
-> Form |            | -> Form |                  | -> Entity                   |            |
        | Controller |         | Service / Facade |                             | Repository |
<- View |            | <- View |                  | <- Entity / Projection View |            |
        |------------|         |------------------|                             |------------|

Controller layer doesn't know what are the entities are. It communicates with Form and View Value Objects. Form Objects has JSR 303 Validation annotations (for instance @NotNull) and View Value Objects have Jackson Annotations for custom serialization. (for instance @JsonIgnore)

Service layer communicates with repository layer via using Entity Objects. Entity objects have JPA/Hibernate/Spring Data annotations on it. Every layer communicates with only the lower layer. The inter-layer communication is prohibited because of circular/cyclic dependency.

User Service ----> XX CANNOT CALL XX ----> Order Service

Some ORM Frameworks have the ability of projection via using additional interfaces or classes. So repositories can return View objects directly. There for you do not need an additional transformation.

For instance this is our User entity:

@Entity
public final class User {
    private String id;
    private String firstname;
    private String lastname;
    private String phone;
    private String fax;
    private String address;
    // Accessors ...
}

But you should return a Paginated list of users that just include id, firstname, lastname. Then you can create a View Value Object for ORM projection.

public final class UserListItemView {
    private String id;
    private String firstname;
    private String lastname;
    // Accessors ...
}

You can easily get the paginated result from repository layer. Thanks to spring you can also use just interfaces for projections.

List<UserListItemView> find(Pageable pageable);

Don't worry for other conversion operations BeanUtils.copy method works just fine.

How can I add an image file into json object?

You will need to read the bytes from that File into a byte[] and put that object into your JSONObject.

You should also have a look at the following posts :

Hope this helps.

What are the different NameID format used for?

1 and 2 are SAML 1.1 because those URIs were part of the OASIS SAML 1.1 standard. Section 8.3 of the linked PDF for the OASIS SAML 2.0 standard explains this:

Where possible an existing URN is used to specify a protocol. In the case of IETF protocols, the URN of the most current RFC that specifies the protocol is used. URI references created specifically for SAML have one of the following stems, according to the specification set version in which they were first introduced:

urn:oasis:names:tc:SAML:1.0:
urn:oasis:names:tc:SAML:1.1:
urn:oasis:names:tc:SAML:2.0:

UnsupportedClassVersionError: JVMCFRE003 bad major version in WebSphere AS 7

If you use maven try to add in the pom.xml

<properties>
    ...
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
    ...
</properties>

Otherwise try to change the compiler version.

Alternative to google finance api

I followed the top answer and started looking at yahoo finance. Their API can be accessed a number of different ways, but I found a nice reference for getting stock info as a CSV here: http://www.jarloo.com/

Using that I wrote this script. I'm not really a ruby guy but this might help you hack something together. I haven't come up with variable names for all the fields yahoo offers yet, so you can fill those in if you need them.

Here's the usage

TICKERS_SP500 = "GICS,CIK,MMM,ABT,ABBV,ACN,ACE,ACT,ADBE,ADT,AES,AET,AFL,AMG,A,GAS,APD,ARG,AKAM,AA,ALXN,ATI,ALLE,ADS,ALL,ALTR,MO,AMZN,AEE,AAL,AEP,AXP,AIG,AMT,AMP,ABC,AME,AMGN,APH,APC,ADI,AON,APA,AIV,AAPL,AMAT,ADM,AIZ,T,ADSK,ADP,AN,AZO,AVGO,AVB,AVY,BHI,BLL,BAC,BK,BCR,BAX,BBT,BDX,BBBY,BBY,BIIB,BLK,HRB,BA,BWA,BXP,BSX,BMY,BRCM,BFB,CHRW,CA,CVC,COG,CAM,CPB,COF,CAH,HSIC,KMX,CCL,CAT,CBG,CBS,CELG,CNP,CTL,CERN,CF,SCHW,CHK,CVX,CMG,CB,CI,XEC,CINF,CTAS,CSCO,C,CTXS,CLX,CME,CMS,COH,KO,CCE,CTSH,CL,CMA,CSC,CAG,COP,CNX,ED,STZ,GLW,COST,CCI,CSX,CMI,CVS,DHI,DHR,DRI,DVA,DE,DLPH,DAL,XRAY,DVN,DO,DTV,DFS,DG,DLTR,D,DOV,DOW,DPS,DTE,DD,DUK,DNB,ETFC,EMN,ETN,EBAY,ECL,EIX,EW,EA,EMC,EMR,ENDP,ESV,ETR,EOG,EQT,EFX,EQIX,EQR,ESS,EL,ES,EXC,EXPE,EXPD,ESRX,XOM,FFIV,FB,FDO,FAST,FDX,FIS,FITB,FSLR,FE,FISV,FLIR,FLS,FLR,FMC,FTI,F,FOSL,BEN,FCX,FTR,GME,GCI,GPS,GRMN,GD,GE,GGP,GIS,GM,GPC,GNW,GILD,GS,GT,GOOG,GWW,HAL,HBI,HOG,HAR,HRS,HIG,HAS,HCA,HCP,HCN,HP,HES,HPQ,HD,HON,HRL,HSP,HST,HCBK,HUM,HBAN,ITW,IR,TEG,INTC,ICE,IBM,IP,IPG,IFF,INTU,ISRG,IVZ,IRM,JEC,JNJ,JCI,JOY,JPM,JNPR,KSU,K,KEY,GMCR,KMB,KIM,KMI,KLAC,KSS,KRFT,KR,LB,LLL,LH,LRCX,LM,LEG,LEN,LVLT,LUK,LLY,LNC,LLTC,LMT,L,LO,LOW,LYB,MTB,MAC,M,MNK,MRO,MPC,MAR,MMC,MLM,MAS,MA,MAT,MKC,MCD,MHFI,MCK,MJN,MWV,MDT,MRK,MET,KORS,MCHP,MU,MSFT,MHK,TAP,MDLZ,MON,MNST,MCO,MS,MOS,MSI,MUR,MYL,NDAQ,NOV,NAVI,NTAP,NFLX,NWL,NFX,NEM,NWSA,NEE,NLSN,NKE,NI,NE,NBL,JWN,NSC,NTRS,NOC,NRG,NUE,NVDA,ORLY,OXY,OMC,OKE,ORCL,OI,PCAR,PLL,PH,PDCO,PAYX,PNR,PBCT,POM,PEP,PKI,PRGO,PFE,PCG,PM,PSX,PNW,PXD,PBI,PCL,PNC,RL,PPG,PPL,PX,PCP,PCLN,PFG,PG,PGR,PLD,PRU,PEG,PSA,PHM,PVH,QEP,PWR,QCOM,DGX,RRC,RTN,RHT,REGN,RF,RSG,RAI,RHI,ROK,COL,ROP,ROST,RCL,R,CRM,SNDK,SCG,SLB,SNI,STX,SEE,SRE,SHW,SIAL,SPG,SWKS,SLG,SJM,SNA,SO,LUV,SWN,SE,STJ,SWK,SPLS,SBUX,HOT,STT,SRCL,SYK,STI,SYMC,SYY,TROW,TGT,TEL,TE,THC,TDC,TSO,TXN,TXT,HSY,TRV,TMO,TIF,TWX,TWC,TJX,TMK,TSS,TSCO,RIG,TRIP,FOXA,TSN,TYC,USB,UA,UNP,UNH,UPS,URI,UTX,UHS,UNM,URBN,VFC,VLO,VAR,VTR,VRSN,VZ,VRTX,VIAB,V,VNO,VMC,WMT,WBA,DIS,WM,WAT,ANTM,WFC,WDC,WU,WY,WHR,WFM,WMB,WIN,WEC,WYN,WYNN,XEL,XRX,XLNX,XL,XYL,YHOO,YUM,ZMH,ZION,ZTS,SAIC,AP"

AllData = loadStockInfo(TICKERS_SP500, allParameters())

SpecificData = loadStockInfo("GOOG,CIK", "ask,dps")

loadStockInfo returns a hash, such that SpecificData["GOOG"]["name"] is "Google Inc."

Finally, the actual code to run that...

require 'net/http'

# Jack Franzen & Garin Bedian
# Based on http://www.jarloo.com/yahoo_finance/

$parametersData = Hash[[

    ["symbol", ["s", "Symbol"]],
    ["ask", ["a", "Ask"]],
    ["divYield", ["y", "Dividend Yield"]],
    ["bid", ["b", "Bid"]],
    ["dps", ["d", "Dividend per Share"]],
    #["noname", ["b2", "Ask (Realtime)"]],
    #["noname", ["r1", "Dividend Pay Date"]],
    #["noname", ["b3", "Bid (Realtime)"]],
    #["noname", ["q", "Ex-Dividend Date"]],
    #["noname", ["p", "Previous Close"]],
    #["noname", ["o", "Open"]],
    #["noname", ["c1", "Change"]],
    #["noname", ["d1", "Last Trade Date"]],
    #["noname", ["c", "Change &amp; Percent Change"]],
    #["noname", ["d2", "Trade Date"]],
    #["noname", ["c6", "Change (Realtime)"]],
    #["noname", ["t1", "Last Trade Time"]],
    #["noname", ["k2", "Change Percent (Realtime)"]],
    #["noname", ["p2", "Change in Percent"]],
    #["noname", ["c8", "After Hours Change (Realtime)"]],
    #["noname", ["m5", "Change From 200 Day Moving Average"]],
    #["noname", ["c3", "Commission"]],
    #["noname", ["m6", "Percent Change From 200 Day Moving Average"]],
    #["noname", ["g", "Day’s Low"]],
    #["noname", ["m7", "Change From 50 Day Moving Average"]],
    #["noname", ["h", "Day’s High"]],
    #["noname", ["m8", "Percent Change From 50 Day Moving Average"]],
    #["noname", ["k1", "Last Trade (Realtime) With Time"]],
    #["noname", ["m3", "50 Day Moving Average"]],
    #["noname", ["l", "Last Trade (With Time)"]],
    #["noname", ["m4", "200 Day Moving Average"]],
    #["noname", ["l1", "Last Trade (Price Only)"]],
    #["noname", ["t8", "1 yr Target Price"]],
    #["noname", ["w1", "Day’s Value Change"]],
    #["noname", ["g1", "Holdings Gain Percent"]],
    #["noname", ["w4", "Day’s Value Change (Realtime)"]],
    #["noname", ["g3", "Annualized Gain"]],
    #["noname", ["p1", "Price Paid"]],
    #["noname", ["g4", "Holdings Gain"]],
    #["noname", ["m", "Day’s Range"]],
    #["noname", ["g5", "Holdings Gain Percent (Realtime)"]],
    #["noname", ["m2", "Day’s Range (Realtime)"]],
    #["noname", ["g6", "Holdings Gain (Realtime)"]],
    #["noname", ["k", "52 Week High"]],
    #["noname", ["v", "More Info"]],
    #["noname", ["j", "52 week Low"]],
    #["noname", ["j1", "Market Capitalization"]],
    #["noname", ["j5", "Change From 52 Week Low"]],
    #["noname", ["j3", "Market Cap (Realtime)"]],
    #["noname", ["k4", "Change From 52 week High"]],
    #["noname", ["f6", "Float Shares"]],
    #["noname", ["j6", "Percent Change From 52 week Low"]],
    ["name", ["n", "Company Name"]],
    #["noname", ["k5", "Percent Change From 52 week High"]],
    #["noname", ["n4", "Notes"]],
    #["noname", ["w", "52 week Range"]],
    #["noname", ["s1", "Shares Owned"]],
    #["noname", ["x", "Stock Exchange"]],
    #["noname", ["j2", "Shares Outstanding"]],
    #["noname", ["v", "Volume"]],
    #["noname", ["a5", "Ask Size"]],
    #["noname", ["b6", "Bid Size"]],
    #["noname", ["k3", "Last Trade Size"]],
    #["noname", ["t7", "Ticker Trend"]],
    #["noname", ["a2", "Average Daily Volume"]],
    #["noname", ["t6", "Trade Links"]],
    #["noname", ["i5", "Order Book (Realtime)"]],
    #["noname", ["l2", "High Limit"]],
    #["noname", ["e", "Earnings per Share"]],
    #["noname", ["l3", "Low Limit"]],
    #["noname", ["e7", "EPS Estimate Current Year"]],
    #["noname", ["v1", "Holdings Value"]],
    #["noname", ["e8", "EPS Estimate Next Year"]],
    #["noname", ["v7", "Holdings Value (Realtime)"]],
    #["noname", ["e9", "EPS Estimate Next Quarter"]],
    #["noname", ["s6", "evenue"]],
    #["noname", ["b4", "Book Value"]],
    #["noname", ["j4", "EBITDA"]],
    #["noname", ["p5", "Price / Sales"]],
    #["noname", ["p6", "Price / Book"]],
    #["noname", ["r", "P/E Ratio"]],
    #["noname", ["r2", "P/E Ratio (Realtime)"]],
    #["noname", ["r5", "PEG Ratio"]],
    #["noname", ["r6", "Price / EPS Estimate Current Year"]],
    #["noname", ["r7", "Price / EPS Estimate Next Year"]],
    #["noname", ["s7", "Short Ratio"]

]]

def replaceCommas(data)
    s = ""
    inQuote = false
    data.split("").each do |a|
        if a=='"'
            inQuote = !inQuote
            s += '"'
        elsif !inQuote && a == ","
            s += "#"
        else
            s += a
        end
    end
    return s
end

def allParameters()
    s = ""
    $parametersData.keys.each do |i|
        s  = s + i + ","
    end
    return s
end

def prepareParameters(parametersText)
    pt = parametersText.split(",")
    if !pt.include? 'symbol'; pt.push("symbol"); end;
    if !pt.include? 'name'; pt.push("name"); end;
    p = []
    pt.each do |i|
        p.push([i, $parametersData[i][0]])
    end
    return p
end

def prepareURL(tickers, parameters)
    urlParameters = ""
    parameters.each do |i|
        urlParameters += i[1]
    end
    s = "http://download.finance.yahoo.com/d/quotes.csv?"
    s = s + "s=" + tickers + "&"
    s = s + "f=" + urlParameters
    return URI(s)
end

def loadStockInfo(tickers, parametersRaw)
    parameters = prepareParameters(parametersRaw)
    url = prepareURL(tickers, parameters)
    data = Net::HTTP.get(url)
    data = replaceCommas(data)
    h = CSVtoObject(data, parameters)
    logStockObjects(h, true)
end

#parse csv
def printCodes(substring, length)

    a = data.index(substring)
    b = data.byteslice(a, 10)
    puts "printing codes of string: "
    puts b
    puts b.split('').map(&:ord).to_s
end

def CSVtoObject(data, parameters)
    rawData = []
    lineBreaks = data.split(10.chr)
    lineBreaks.each_index do |i|
        rawData.push(lineBreaks[i].split("#"))
    end

    #puts "Found " + rawData.length.to_s + " Stocks"
    #puts "   w/ " + rawData[0].length.to_s + " Fields"

    h = Hash.new("MainHash")
    rawData.each_index do |i|
        o = Hash.new("StockObject"+i.to_s)
        #puts "parsing object" + rawData[i][0]
        rawData[i].each_index do |n|
            #puts "parsing parameter" + n.to_s + " " +parameters[n][0]
            o[ parameters[n][0] ] = rawData[i][n].gsub!(/^\"|\"?$/, '')
        end
        h[o["symbol"]] = o;
    end
    return h
end

def logStockObjects(h, concise)
    h.keys.each do |i|
        if concise
            puts "(" + h[i]["symbol"] + ")\t\t" + h[i]["name"]
        else
            puts ""
            puts h[i]["name"]
            h[i].keys.each do |p|
                puts "    " + $parametersData[p][1] + " : " + h[i][p].to_s
            end
        end
    end
end

How to automate browsing using python?

Selenium2 includes webdriver, which has python bindings and allows one to use the headless htmlUnit driver, or switch to firefox or chrome for graphical debugging.

Bootstrap 3: how to make head of dropdown link clickable in navbar

No need of use addition CSS/JS (Tested)

  1. data-toggle="dropdown" - for Clickable (can use Mobile as well web)
  2. data-hover="dropdown" - for Hover (web only, because mobile doesn't have feature HOVER)

Works fine on Mobile as well :)


Code Example for Clickable(data-toggle="dropdown")

_x000D_
_x000D_
/*!
 * this CSS code just  for snippet preview purpose. Please omit when using  it. 
 */

#bs-example-navbar-collapse-1 ul li {
  float: left;
}

#bs-example-navbar-collapse-1 ul li ul li {
  float: none !important;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div id="bs-example-navbar-collapse-1">
  <ul class="nav navbar-nav">
    <li>
      <a class="" href="">Home</a>
    </li>
    <li class="dropdown">
      <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
                subnav1
            </a>
      <ul class="dropdown-menu">
        <li><a href="">Sub1</a></li>
        <li><a href="">Sub2</a></li>
        <li><a href="">Sub3</a></li>
        <li><a href="">Sub4</a></li>
        <li><a href="">Sub5</a></li>
        <li><a href="">Sub6</a></li>
      </ul>
      <div class="clear"></div>
    </li>
    <li class="dropdown">
      <a href="" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="true">
            subnav2
            </a>
      <ul class="dropdown-menu">
        <li><a href="">Sub1</a></li>
        <li><a href="">Sub2</a></li>
        <li><a href="">Sub3</a></li>
        <li><a href="">Sub4</a></li>
        <li><a href="">Sub5</a></li>
        <li><a href="">Sub6</a></li>
      </ul>
      <div class="clear"></div>
    </li>
  </ul>
</div>

<br>
<br>
<p><b>Please Note:</b> added css code not related to Bootstrap navigation. It's just for snippet preview purpose </p>
_x000D_
_x000D_
_x000D_

Output

output enter image description here

using sql count in a case statement

Close... try:

select 
   Sum(case when rsp_ind = 0 then 1 Else 0 End) as 'New',
   Sum(case when rsp_ind = 1 then 1 else 0 end) as 'Accepted'
from tb_a

How do I create a master branch in a bare Git repository?

By default there will be no branches listed and pops up only after some file is placed. You don't have to worry much about it. Just run all your commands like creating folder structures, adding/deleting files, commiting files, pushing it to server or creating branches. It works seamlessly without any issue.

https://git-scm.com/docs

git checkout tag, git pull fails in branch

First, make sure you are on the right branch.
Then (one time only):

git branch --track

After that this works again:

git pull

Check line for unprintable characters while reading text file

Open the file with a FileInputStream, then use an InputStreamReader with the UTF-8 Charset to read characters from the stream, and use a BufferedReader to read lines, e.g. via BufferedReader#readLine, which will give you a string. Once you have the string, you can check for characters that aren't what you consider to be printable.

E.g. (without error checking), using try-with-resources (which is in vaguely modern Java version):

String line;
try (
    InputStream fis = new FileInputStream("the_file_name");
    InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8"));
    BufferedReader br = new BufferedReader(isr);
) {
    while ((line = br.readLine()) != null) {
        // Deal with the line
    }
}

What is the yield keyword used for in C#?

One major point about Yield keyword is Lazy Execution. Now what I mean by Lazy Execution is to execute when needed. A better way to put it is by giving an example

Example: Not using Yield i.e. No Lazy Execution.

public static IEnumerable<int> CreateCollectionWithList()
{
    var list =  new List<int>();
    list.Add(10);
    list.Add(0);
    list.Add(1);
    list.Add(2);
    list.Add(20);

    return list;
}

Example: using Yield i.e. Lazy Execution.

public static IEnumerable<int> CreateCollectionWithYield()
{
    yield return 10;
    for (int i = 0; i < 3; i++) 
    {
        yield return i;
    }

    yield return 20;
}

Now when I call both methods.

var listItems = CreateCollectionWithList();
var yieldedItems = CreateCollectionWithYield();

you will notice listItems will have a 5 items inside it (hover your mouse on listItems while debugging). Whereas yieldItems will just have a reference to the method and not the items. That means it has not executed the process of getting items inside the method. A very efficient a way of getting data only when needed. Actual implementation of yield can seen in ORM like Entity Framework and NHibernate etc.

Best Practices for Custom Helpers in Laravel 5

Best Practice to write custom helpers is

1) Inside the app directory of the project root, create a folder named Helpers (Just to separate and structure the code).

2) Inside the folder write psr-4 files or normal php files

If the PHP files are in the format of psr-4 then it will be auto loaded, else add the following line in the composer.json which is inside the project root directory

Inside the autoload key, create a new key named files to load files at the time of auto load,inside the files object add the path starting from app directory., here is an example.

"autoload": {
    "classmap": [
        "database"
    ],
    "psr-4": {
        "App\\": "app/"
    },
    "files": [
        "app/Helpers/customHelpers.php"
    ]
},
"autoload-dev": {
    "classmap": [
        "tests/TestCase.php"
    ]
},

PS : try running composer dump-autoload if the file dosen't loaded.

How to Truncate a string in PHP to the word closest to a certain number of characters?

Ok so I got another version of this based on the above answers but taking more things in account(utf-8, \n and &nbsp ; ), also a line stripping the wordpress shortcodes commented if used with wp.

function neatest_trim($content, $chars) 
  if (strlen($content) > $chars) 
  {
    $content = str_replace('&nbsp;', ' ', $content);
    $content = str_replace("\n", '', $content);
    // use with wordpress    
    //$content = strip_tags(strip_shortcodes(trim($content)));
    $content = strip_tags(trim($content));
    $content = preg_replace('/\s+?(\S+)?$/', '', mb_substr($content, 0, $chars));

    $content = trim($content) . '...';
    return $content;
  }

Send a ping to each IP on a subnet

#!/bin/sh

COUNTER=$1

while [ $COUNTER -lt 254 ]
do
 echo $COUNTER
 ping -c 1 192.168.1.$COUNTER | grep 'ms'
 COUNTER=$(( $COUNTER + 1 ))
done

#specify start number like this: ./ping.sh 1
#then run another few instances to cover more ground
#aka one at 1, another at 100, another at 200
#this just finds addresses quicker. will only print ttl info when an address resolves

MySQL - ERROR 1045 - Access denied

I had the same error, but it was because password_expired was set to Y. You can fix that issue by following the same approach as the currently accepted answer, but instead executing the MySQL query:

UPDATE mysql.user SET password_expired = 'N' WHERE User='root';

How can I put a database under git (version control)?

What I do in my personal projects is, I store my whole database to dropbox and then point MAMP, WAMP workflow to use it right from there.. That way database is always up-to-date where ever I need to do some developing. But that's just for dev! Live sites is using own server for that off course! :)

Select datatype of the field in postgres

You can use the pg_typeof() function, which also works well for arbitrary values.

SELECT pg_typeof("stu_id"), pg_typeof(100) from student_details limit 1;

selected value get from db into dropdown select box option using php mysql error

USING POD

<?php
$username = "root";
$password = "";
$db = "db_name";

$dns = "mysql:host=localhost;dbname=$db;charset=utf8mb4";
    $conn = new PDO($dns,$username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $sql = "select * from mine where username = ? ";

    $stmt1 = $conn->prepare($sql);
    $stmt1 -> execute(array($_POST['user']));
    $all = $stmt1->fetchAll(); ?>

    <div class="controls">
        <select  data-rel="chosen"  name="degree_id" id="selectError">

                 <?php foreach($all as $nt) { echo "<option value =$nt[id]>$nt[name]</option>";}?>
        </select>

    </div>

What is a lambda (function)?

You can think of it as an anonymous function - here's some more info: Wikipedia - Anonymous Function

Multiple actions were found that match the request in Web Api

In my Case Everything was right

1) Web Config was configured properly 2) Route prefix and Route attributes were proper

Still i was getting the error. In my Case "Route" attribute (by pressing F12) was point to System.Web.MVc but not System.Web.Http which caused the issue.

link_to method and click event in Rails

just use

=link_to "link", "javascript:function()"

How to remove specific object from ArrayList in Java?

For removing the particular object from arrayList there are two ways. Call the function of arrayList.

  1. Removing on the basis of the object.
arrayList.remove(object);

This will remove your object but in most cases when arrayList contains the items of UserDefined DataTypes, this method does not give you the correct result. It works fine only for Primitive DataTypes. Because user want to remove the item on the basis of object field value and that can not be compared by remove function automatically.

  1. Removing on the basis of specified index position of arrayList. The best way to remove any item or object from arrayList. First, find the index of the item which you want to remove. Then call this arrayList method, this method removes the item on index basis. And it will give the correct result.
arrayList.remove(index);  

Multiple files upload (Array) with CodeIgniter 2.0

For CodeIgniter 3

<form action="<?php echo base_url('index.php/TestingController/insertdata') ?>" method="POST"
      enctype="multipart/form-data">
    <div class="form-group">
        <label for="">title</label>
        <input type="text" name="title" id="title" class="form-control">
    </div>
    <div class="form-group">
        <label for="">File</label>
        <input type="file" name="files" id="files" class="form-control">
    </div>
    <input type="submit" value="Submit" class="btn btn-primary">
</form>


public function insertdatanew()
{
    $this->load->library('upload');
    $files = $_FILES;
    $cpt = count($_FILES['filesdua']['name']);

    for ($i = 0; $i < $cpt; $i++) {
        $_FILES['filesdua']['name'] = $files['filesdua']['name'][$i];
        $_FILES['filesdua']['type'] = $files['filesdua']['type'][$i];
        $_FILES['filesdua']['tmp_name'] = $files['filesdua']['tmp_name'][$i];
        $_FILES['filesdua']['error'] = $files['filesdua']['error'][$i];
        $_FILES['filesdua']['size'] = $files['filesdua']['size'][$i];

        // fungsi uploud
        $config['upload_path']          = './uploads/testing/';
        $config['allowed_types']        = '*';
        $config['max_size']             = 0;
        $config['max_width']            = 0;
        $config['max_height']           = 0;
        $this->load->library('upload', $config);
        $this->upload->initialize($config);

        if (!$this->upload->do_upload('filesdua')) {
            $error = array('error' => $this->upload->display_errors());
            var_dump($error);

            // $this->load->view('welcome_message', $error);
        } else {

            // menambil nilai value yang di upload  
            $data = array('upload_data' => $this->upload->data());
            $nilai = $data['upload_data']; 
            $filename = $nilai['file_name'];
            var_dump($filename);

            // $this->load->view('upload_success', $data);
        }
    }
    // var_dump($cpt);
}

expand/collapse table rows with JQuery

The easiest way to achieve this, without changing the HTML table-based structure, is to use a class-name on the tr elements containing a header, such as .header, to give:

<table border="0">
  <tr class="header">
    <td colspan="2">Header</td>
  </tr>
  <tr>
    <td>data</td>
    <td>data</td>
  </tr>
  <tr>
    <td>data</td>
    <td>data</td>
  </tr>
  <tr class="header">
    <td colspan="2">Header</td>
  </tr>
  <tr>
    <td>date</td>
    <td>data</td>
  </tr>
  <tr>
    <td>data</td>
    <td>data</td>
  </tr>
  <tr>
    <td>data</td>
    <td>data</td>
  </tr>
</table>

And the jQuery:

// bind a click-handler to the 'tr' elements with the 'header' class-name:
$('tr.header').click(function(){
    /* get all the subsequent 'tr' elements until the next 'tr.header',
       set the 'display' property to 'none' (if they're visible), to 'table-row'
       if they're not: */
    $(this).nextUntil('tr.header').css('display', function(i,v){
        return this.style.display === 'table-row' ? 'none' : 'table-row';
    });
});

JS Fiddle demo.

In the linked demo I've used CSS to hide the tr elements that don't have the header class-name; in practice though (despite the relative rarity of users with JavaScript disabled) I'd suggest using JavaScript to add the relevant class-names, hiding and showing as appropriate:

// hide all 'tr' elements, then filter them to find...
$('tr').hide().filter(function () {
    // only those 'tr' elements that have 'td' elements with a 'colspan' attribute:
    return $(this).find('td[colspan]').length;
    // add the 'header' class to those found 'tr' elements
}).addClass('header')
    // set the display of those elements to 'table-row':
  .css('display', 'table-row')
    // bind the click-handler (as above)
  .click(function () {
    $(this).nextUntil('tr.header').css('display', function (i, v) {
        return this.style.display === 'table-row' ? 'none' : 'table-row';
    });
});

JS Fiddle demo.

References:

Quicksort with Python

I will do quicksort using numpy library. I think it is really usefull library. They already implemented the quick sort method but you can implment also your custom method.

import numpy
array = [3,4,8,1,2,13,28,11,99,76] #The array what we want to sort

indexes = numpy.argsort( array , None, 'quicksort', None)
index_list = list(indexes)

temp_array = []

for index in index_list:
    temp_array.append( array[index])

array = temp_array

print array #it will show sorted array

CSS :selected pseudo class similar to :checked, but for <select> elements

the :checked pseudo-class initially applies to such elements that have the HTML4 selected and checked attributes

Source: w3.org


So, this CSS works, although styling the color is not possible in every browser:

option:checked { color: red; }

An example of this in action, hiding the currently selected item from the drop down list.

_x000D_
_x000D_
option:checked { display:none; }
_x000D_
<select>_x000D_
    <option>A</option>_x000D_
    <option>B</option>_x000D_
    <option>C</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_


To style the currently selected option in the closed dropdown as well, you could try reversing the logic:

select { color: red; }
option:not(:checked) { color: black; } /* or whatever your default style is */

How to execute Python scripts in Windows?

If that's what I understood, it's like this:

C:\Users\(username)\AppData\Local\Programs\Python\Python(version)

COPY (not delete) python.exe and rename to py.exe and execute:

py filename.py

How to check if a specified key exists in a given S3 bucket using Java

Use ListObjectsRequest setting Prefix as your key.

.NET code:

 public bool Exists(string key)
    {

        using (Amazon.S3.AmazonS3Client client = (Amazon.S3.AmazonS3Client)Amazon.AWSClientFactory.CreateAmazonS3Client(m_accessKey, m_accessSecret))
        {
            ListObjectsRequest request = new ListObjectsRequest();
            request.BucketName = m_bucketName;
            request.Prefix = key;
            using (ListObjectsResponse response = client.ListObjects(request))
            {

                foreach (S3Object o in response.S3Objects)
                {
                    if( o.Key == key )
                        return true;
                }
                return false;
            }
        }
    }.

How do you create a foreign key relationship in a SQL Server CE (Compact Edition) Database?

Visual Studio 2008 does have a designer that allows you to add FK's. Just right-click the table... Table Properties, then go to the "Add Relations" section.

Why is setTimeout(fn, 0) sometimes useful?

The answers about execution loops and rendering the DOM before some other code completes are correct. Zero second timeouts in JavaScript help make the code pseudo-multithreaded, even though it is not.

I want to add that the BEST value for a cross browser / cross platform zero-second timeout in JavaScript is actually about 20 milliseconds instead of 0 (zero), because many mobile browsers can't register timeouts smaller than 20 milliseconds due to clock limitations on AMD chips.

Also, long-running processes that do not involve DOM manipulation should be sent to Web Workers now, as they provide true multithreaded execution of JavaScript.

Linux : Search for a Particular word in a List of files under a directory

This is a very frequent task in linux. I use grep -rn '' . all the time to do this. -r for recursive (folder and subfolders) -n so it gives the line numbers, the dot stands for the current directory.

grep -rn '<word or regex>' <location>

do a

man grep 

for more options

How to submit a form on enter when the textarea has focus?

Why do you want a textarea to submit when you hit enter?

A "text" input will submit by default when you press enter. It is a single line input.

<input type="text" value="...">

A "textarea" will not, as it benefits from multi-line capabilities. Submitting on enter takes away some of this benefit.

<textarea name="area"></textarea>

You can add JavaScript code to detect the enter keypress and auto-submit, but you may be better off using a text input.

phpmyadmin.pma_table_uiprefs doesn't exist

You are missing at least one of the phpMyAdmin configuration storage tables, or the configured table name does not match the actual table name.

See http://docs.phpmyadmin.net/en/latest/setup.html#phpmyadmin-configuration-storage.

A quick summary of what to do can be:

  1. On the shell: locate create_tables.sql.
  2. import /usr/share/doc/phpmyadmin/examples/create_tables.sql.gz using phpMyAdmin.
  3. open /etc/phpmyadmin/config.inc.php and edit lines 81-92: change pma_bookmark to pma__bookmark and so on.

Remove a symlink to a directory

Assuming your setup is something like: ln -s /mnt/bar ~/foo, then you should be able to do a rm foo with no problem. If you can't, make sure you are the owner of the foo and have permission to write/execute the file. Removing foo will not touch bar, unless you do it recursively.

Syntax for a for loop in ruby

limit = array.length;
for counter in 0..limit
 --- make some actions ---
end

the other way to do that is the following

3.times do |n|
  puts n;
end

thats will print 0, 1, 2, so could be used like array iterator also

Think that variant better fit to the author's needs

How to make ConstraintLayout work with percentage values?

With the ConstraintLayout v1.1.2, the dimension should be set to 0dp and then set the layout_constraintWidth_percent or layout_constraintHeight_percent attributes to a value between 0 and 1 like :

<!-- 50% width centered Button -->
<Button
    android:id="@+id/button"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintWidth_percent=".5" />

(You don't need to set app:layout_constraintWidth_default="percent" or app:layout_constraintHeight_default="percent" with ConstraintLayout 1.1.2 and following versions)

How to get the max of two values in MySQL?

To get the maximum value of a column across a set of rows:

SELECT MAX(column1) FROM table; -- expect one result

To get the maximum value of a set of columns, literals, or variables for each row:

SELECT GREATEST(column1, 1, 0, @val) FROM table; -- expect many results

How can I undo git reset --hard HEAD~1?

git reflog

  • Find your commit sha in the list then copy and paste it into this command:

git cherry-pick <the sha>

How to clear radio button in Javascript?

If you do not intend to use jQuery, you can use simple javascript like this

document.querySelector('input[name="Choose"]:checked').checked = false;

Only benefit with this is you don't have to use loops for two radio buttons

Select multiple records based on list of Id's with linq

You can use Contains() for that. It will feel a little backwards when you're really trying to produce an IN clause, but this should do it:

var userProfiles = _dataContext.UserProfile
                               .Where(t => idList.Contains(t.Id));

I'm also assuming that each UserProfile record is going to have an int Id field. If that's not the case you'll have to adjust accordingly.

How can I find the number of years between two dates?

I know you have asked for a clean solution, but here are two dirty once:

        static void diffYears1()
{
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
    Calendar calendar1 = Calendar.getInstance(); // now
    String toDate = dateFormat.format(calendar1.getTime());

    Calendar calendar2 = Calendar.getInstance();
    calendar2.add(Calendar.DAY_OF_YEAR, -7000); // some date in the past
    String fromDate = dateFormat.format(calendar2.getTime());

    // just simply add one year at a time to the earlier date until it becomes later then the other one 
    int years = 0;
    while(true)
    {
        calendar2.add(Calendar.YEAR, 1);
        if(calendar2.getTimeInMillis() < calendar1.getTimeInMillis())
            years++;
        else
            break;
    }

    System.out.println(years + " years between " + fromDate + " and " + toDate);
}

static void diffYears2()
{
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
    Calendar calendar1 = Calendar.getInstance(); // now
    String toDate = dateFormat.format(calendar1.getTime());

    Calendar calendar2 = Calendar.getInstance();
    calendar2.add(Calendar.DAY_OF_YEAR, -7000); // some date in the past
    String fromDate = dateFormat.format(calendar2.getTime());

    // first get the years difference from the dates themselves
    int years = calendar1.get(Calendar.YEAR) - calendar2.get(Calendar.YEAR);
    // now make the earlier date the same year as the later
    calendar2.set(Calendar.YEAR, calendar1.get(Calendar.YEAR));
    // and see if new date become later, if so then one year was not whole, so subtract 1 
    if(calendar2.getTimeInMillis() > calendar1.getTimeInMillis())
        years--;

    System.out.println(years + " years between " + fromDate + " and " + toDate);
}

How to stop text from taking up more than 1 line?

In JSX/ React prevent text from wrapping

<div style={{ whiteSpace: "nowrap", overflow: "hidden" }}>
   Text that will never wrap
</div>

Whoops, looks like something went wrong. Laravel 5.0

Go to project directory then follow below steps.

step 1: rename file .env.example `to .env

mv .env.example .env (for linux)

step 2: php artisan key:generate

Pandas - replacing column values

Can try this too!
Create a dictionary of replacement values.

import pandas as pd
data = pd.DataFrame([[1,0],[0,1],[1,0],[0,1]], columns=["sex", "split"])

enter image description here

replace_dict= {0:'Female',1:'Male'}
print(replace_dict)

enter image description here

Use the map function for replacing values

data['sex']=data['sex'].map(replace_dict)

Output after replacing
enter image description here

C++ compile error: has initializer but incomplete type

You need this include:

#include <sstream>

How to catch SQLServer timeout exceptions

I am not sure but when we have execute time out or command time out The client sends an "ABORT" to SQL Server then simply abandons the query processing. No transaction is rolled back, no locks are released. to solve this problem I Remove transaction in Stored-procedure and use SQL Transaction in my .Net Code To manage sqlException

Why use 'virtual' for class properties in Entity Framework model definitions?

In the context of EF, marking a property as virtual allows EF to use lazy loading to load it. For lazy loading to work EF has to create a proxy object that overrides your virtual properties with an implementation that loads the referenced entity when it is first accessed. If you don't mark the property as virtual then lazy loading won't work with it.

Combining multiple commits before pushing in Git

There are quite a few working answers here, but I found this the easiest. This command will open up an editor, where you can just replace pick with squash in order to remove/merge them into one

git rebase -i HEAD~4

where, 4 is the number of commits you want to squash into one. This is explained here as well.

How to execute XPath one-liners from shell?

Similar to Mike's and clacke's answers, here is the python one-liner (using python >= 2.5) to get the build version from a pom.xml file that gets around the fact that pom.xml files don't normally have a dtd or default namespace, so don't appear well-formed to libxml:

python -c "import xml.etree.ElementTree as ET; \
  print(ET.parse(open('pom.xml')).getroot().find('\
  {http://maven.apache.org/POM/4.0.0}version').text)"

Tested on Mac and Linux, and doesn't require any extra packages to be installed.

Creating a Custom Event

Based on @ionden's answer, the call to the delegate could be simplified using null propagation since C# 6.0.

Your code would simply be:

class MyClass {
    public event EventHandler MyEvent;

    public void Method() {
        MyEvent?.Invoke(this, EventArgs.Empty);
    }
}

Use it like this:

MyClass myObject = new MyClass();
myObject.MyEvent += new EventHandler(myObject_MyEvent);
myObject.Method();

How do you connect to a MySQL database using Oracle SQL Developer?

You may find the following relevant as well:

Oracle SQL Developer connection to Microsoft SQL Server

In my case I had to place the ntlmauth.dll in the sql-developer application directory itself (i.e. sql-developer\jdk\jre\bin). Why this location over the system jre/bin I have no idea. But it worked.

jquery - Check for file extension before uploading

If you don't want to use $(this).val(), you can try:

var file_onchange = function () {
  var input = this; // avoid using 'this' directly

  if (input.files && input.files[0]) {
    var type = input.files[0].type; // image/jpg, image/png, image/jpeg...

    // allow jpg, png, jpeg, bmp, gif, ico
    var type_reg = /^image\/(jpg|png|jpeg|bmp|gif|ico)$/;

    if (type_reg.test(type)) {
      // file is ready to upload
    } else {
      alert('This file type is unsupported.');
    }
  }
};

$('#file').on('change', file_onchange);

Hope this helps!

How can I create a UIColor from a hex string?

Use this Category :

in the file UIColor+Hexadecimal.h

#import <UIKit/UIKit.h>

@interface UIColor(Hexadecimal)

+ (UIColor *)colorWithHexString:(NSString *)hexString;

@end

in the file UIColor+Hexadecimal.m

#import "UIColor+Hexadecimal.h"

@implementation UIColor(Hexadecimal)

+ (UIColor *)colorWithHexString:(NSString *)hexString {
    unsigned rgbValue = 0;
    NSScanner *scanner = [NSScanner scannerWithString:hexString];
    [scanner setScanLocation:1]; // bypass '#' character
    [scanner scanHexInt:&rgbValue];

    return [UIColor colorWithRed:((rgbValue & 0xFF0000) >> 16)/255.0 green:((rgbValue & 0xFF00) >> 8)/255.0 blue:(rgbValue & 0xFF)/255.0 alpha:1.0];
}

@end

In Class you want use it :

#import "UIColor+Hexadecimal.h"

and:

[UIColor colorWithHexString:@"#6e4b4b"];

PHP function overloading

What about this:

function($arg = NULL) {

    if ($arg != NULL) {
        etc.
        etc.
    }
}

Cannot install Aptana Studio 3.6 on Windows

I had the same problem. I solved by installing NodeJS from this link: http://go.aptana.com/installer_nodejs_windows and Git latest version from https://git-scm.com/downloads.

Finally I was able to run the Aptana installer with no problems.

Running SSH Agent when starting Git Bash on Windows

Simple two string solution from this answer:

For sh, bash, etc:

# ~/.profile
if ! pgrep -q -U `whoami` -x 'ssh-agent'; then ssh-agent -s > ~/.ssh-agent.sh; fi
. ~/.ssh-agent.sh

For csh, tcsh, etc:

# ~/.schrc
sh -c 'if ! pgrep -q -U `whoami` -x 'ssh-agent'; then ssh-agent -c > ~/.ssh-agent.tcsh; fi'
eval `cat ~/.ssh-agent.tcsh`

What is the meaning of ToString("X2")?

ToString("X2") prints the input in Hexadecimal

Things possible in IntelliJ that aren't possible in Eclipse?

Don't forget "compare with clipboard".

Something that I use all the time in IntelliJ and which has no equivalent in Eclipse.

How do I define a method which takes a lambda as a parameter in Java 8?

There's a public Web-accessible version of the Lambda-enabled Java 8 JavaDocs, linked from http://lambdafaq.org/lambda-resources. (This should obviously be a comment on Joachim Sauer's answer, but I can't get into my SO account with the reputation points I need to add a comment.) The lambdafaq site (I maintain it) answers this and a lot of other Java-lambda questions.

NB This answer was written before the Java 8 GA documentation became publicly available. I've left in place, though, because the Lambda FAQ might still be useful to people learning about features introduced in Java 8.

Convert integer into byte array (Java)

Simple solution which properly handles ByteOrder:

ByteBuffer.allocate(4).order(ByteOrder.nativeOrder()).putInt(yourInt).array();

How to decode JWT Token?

You need the secret string which was used to generate encrypt token. This code works for me:

protected string GetName(string token)
    {
        string secret = "this is a string used for encrypt and decrypt token"; 
        var key = Encoding.ASCII.GetBytes(secret);
        var handler = new JwtSecurityTokenHandler();
        var validations = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(key),
            ValidateIssuer = false,
            ValidateAudience = false
        };
        var claims = handler.ValidateToken(token, validations, out var tokenSecure);
        return claims.Identity.Name;
    }

Why does writeObject throw java.io.NotSerializableException and how do I fix it?

The fields of your object have in turn their fields, some of which do not implement Serializable. In your case the offending class is TransformGroup. How to solve it?

  • if the class is yours, make it Serializable
  • if the class is 3rd party, but you don't need it in the serialized form, mark the field as transient
  • if you need its data and it's third party, consider other means of serialization, like JSON, XML, BSON, MessagePack, etc. where you can get 3rd party objects serialized without modifying their definitions.

Clear data in MySQL table with PHP?

TRUNCATE TABLE tablename

or

DELETE FROM tablename

The first one is usually the better choice, as DELETE FROM is slow on InnoDB.

Actually, wasn't this already answered in your other question?

How to determine the version of android SDK installed in computer?

Create a Batch file (.bat) in Windows with the following command in it:

%ANDROID_HOME%\tools\bin\sdkmanager.bat --list && pause

NOTE: Using && pause is necessary to be able to review the information, once it is listed. If not used, the batch file will simply run, show the information in just mere few seconds and exit right away.