Programs & Examples On #Social media

How to clear Facebook Sharer cache?

if you are using wordpress with a cache plugin, make sure you clear all your caches. Also make sure the image you are using has the recommended facebook size: 1200(w) x 630(h) or 600 x 315.

Is there a way to run Bash scripts on Windows?

Install Cygwin, which includes Bash among many other GNU and Unix utilities (without whom its unlikely that bash will be very useful anyway).

Another option is MinGW's MSYS which includes bash and a smaller set of the more important utilities such as awk. Personally I would have preferred Cygwin because it includes such heavy lifting tools as Perl and Python which I find I cannot live without, while MSYS skimps on these and assumes you are going to install them yourself.

Updated: If anyone is interested in this answer and is running MS-Windows 10, please note that MS-Windows 10 has a "Windows Subsystem For Linux" feature which - once enabled - allows you to install a user-mode image of Ubuntu and then run Bash on that. This provides 100% compatibility with Ubuntu for debugging and running Bash scripts, but this setup is completely standalone from Windows and you cannot use Bash scripts to interact with Windows features (such as processes and APIs) except for limited access to files through the DrvFS feature.

Use dynamic (variable) string as regex pattern in JavaScript

Using string variable(s) content as part of a more complex composed regex expression (es6|ts)

This example will replace all urls using my-domain.com to my-other-domain (both are variables).

You can do dynamic regexs by combining string values and other regex expressions within a raw string template. Using String.raw will prevent javascript from escaping any character within your string values.

// Strings with some data
const domainStr = 'my-domain.com'
const newDomain = 'my-other-domain.com'

// Make sure your string is regex friendly
// This will replace dots for '\'.
const regexUrl = /\./gm;    
const substr = `\\\.`;
const domain = domainStr.replace(regexUrl, substr);
// domain is a regex friendly string: 'my-domain\.com'
console.log('Regex expresion for domain', domain)

// HERE!!! You can 'assemble a complex regex using string pieces.
const re = new RegExp( String.raw `([\'|\"]https:\/\/)(${domain})(\S+[\'|\"])`, 'gm');

// now I'll use the regex expression groups to replace the domain
const domainSubst = `$1${newDomain}$3`;

// const page contains all the html text
const result = page.replace(re, domainSubst);

note: Don't forget to use regex101.com to create, test and export REGEX code.

Difference between signed / unsigned char

I slightly disagree with the above. The unsigned char simply means: Use the most significant bit instead of treating it as a bit flag for +/- sign when performing arithmetic operations.

It makes significance if you use char as a number for instance:

typedef char BYTE1;
typedef unsigned char BYTE2;

BYTE1 a;
BYTE2 b;

For variable a, only 7 bits are available and its range is (-127 to 127) = (+/-)2^7 -1. For variable b all 8 bits are available and the range is 0 to 255 (2^8 -1).

If you use char as character, "unsigned" is completely ignored by the compiler just as comments are removed from your program.

Eclipse change project files location

Using Neon - just happened to me too. You would have to delete the Eclipse version (not from disk) in your Project Explorer and import the projects as existing projects. Of course, ensure that the project folders as a whole were moved and that the Eclipse meta files are still there as mentioned by @koenpeters.

Refactor does not handle this.

CSS Circular Cropping of Rectangle Image

The approach is wrong, you need to apply the border-radius to the container div instead of the actual image.

This would work:

_x000D_
_x000D_
.image-cropper {
  width: 100px;
  height: 100px;
  position: relative;
  overflow: hidden;
  border-radius: 50%;
}

img {
  display: inline;
  margin: 0 auto;
  height: 100%;
  width: auto;
}
_x000D_
<div class="image-cropper">
  <img src="https://via.placeholder.com/150" class="rounded" />
</div>
_x000D_
_x000D_
_x000D_

WooCommerce - get category for product page

$product->get_categories() is deprecated since version 3.0! Use wc_get_product_category_list instead.

https://docs.woocommerce.com/wc-apidocs/function-wc_get_product_category_list.html

Removing border from table cells

If none of the solutions on this page work and you are having the below issue:

enter image description here

You can simply use this snippet of CSS:

td {
   padding: 0;
}

How to re-index all subarray elements of a multidimensional array?

$array[9] = 'Apple';
$array[12] = 'Orange';
$array[5] = 'Peach';

$array = array_values($array);

through this function you can reset your array

$array[0] = 'Apple';
$array[1] = 'Orange';
$array[2] = 'Peach';

How do I access (read, write) Google Sheets spreadsheets with Python?

You could have a look at Sheetfu. The following is an example from the README. It gives a super easy syntax to interact with spreadsheets as if it was a database table.

from sheetfu import Table

spreadsheet = SpreadsheetApp('path/to/secret.json').open_by_id('<insert spreadsheet id here>')
data_range = spreadsheet.get_sheet_by_name('people').get_data_range()

table = Table(data_range, backgrounds=True)

for item in table:
    if item.get_field_value('name') == 'foo':
        item.set_field_value('surname', 'bar')              # this set the surname field value
    age = item.get_field_value('age')
    item.set_field_value('age', age + 1)
    item.set_field_background('age', '#ff0000')             # this set the field 'age' to red color

# Every set functions are batched for speed performance.
# To send the batch update of every set requests you made,
# you need to commit the table object as follow.
table.commit()

Disclaimer: I'm the author of this library.

Algorithm/Data Structure Design Interview Questions

I like to go over a code the person actually wrote and have them explain it to me.

How to send FormData objects with Ajax-requests in jQuery?

You can use the $.ajax beforeSend event to manipulate the header.

beforeSend: function(xhr) { 
    xhr.setRequestHeader('Content-Type', 'multipart/form-data');
}

See this link for additional information: http://msdn.microsoft.com/en-us/library/ms536752(v=vs.85).aspx

checking if number entered is a digit in jquery

Forget regular expressions. JavaScript has a builtin function for this: isNaN():

isNaN(123)           // false
isNaN(-1.23)         // false
isNaN(5-2)           // false
isNaN(0)             // false
isNaN("100")         // false
isNaN("Hello")       // true
isNaN("2005/12/12")  // true

Just call it like so:

if (isNaN( $("#whatever").val() )) {
    // It isn't a number
} else {
    // It is a number
}

DLL Load Library - Error Code 126

Windows dll error 126 can have many root causes. The most useful methods I have found to debug this are:

  1. Use dependency walker to look for any obvious problems (which you have already done)
  2. Use the sysinternals utility Process Monitor http://technet.microsoft.com/en-us/sysinternals/bb896645 from Microsoft to trace all file access while your dll is trying to load. With this utility, you will see everything that that dll is trying to pull in and usually the problem can be determined from there.

Python 3.4.0 with MySQL database

MySQLdb does not support Python 3 but it is not the only MySQL driver for Python.

mysqlclient is essentially just a fork of MySQLdb with Python 3 support merged in (and a few other improvements).

PyMySQL is a pure python MySQL driver, which means it is slower, but it does not require a compiled C component or MySQL libraries and header files to be installed on client machines. It has Python 3 support.

Another option is simply to use another database system like PostgreSQL.

How to Calculate Jump Target Address and Branch Target Address?

For small functions like this you could just count by hand how many hops it is to the target, from the instruction under the branch instruction. If it branches backwards make that hop number negative. if that number doesn't require all 16 bits, then for every number to the left of the most significant of your hop number, make them 1's, if the hop number is positive make them all 0's Since most branches are close to they're targets, this saves you a lot of extra arithmetic for most cases.

  • chris

Serializing enums with Jackson

In Spring Boot 2, the easiest way is to declare in your application.properties:

spring.jackson.serialization.WRITE_ENUMS_USING_TO_STRING=true
spring.jackson.deserialization.READ_ENUMS_USING_TO_STRING=true

and define the toString() method of your enums.

LaTex left arrow over letter in math mode

Use \overleftarrow to create a long arrow to the left.

\overleftarrow{blahblahblah}

LaTeX output

Connect to mysql on Amazon EC2 from a remote server

There could be one of the following reasons:

  1. You need make an entry in the Amazon Security Group to allow remote access from your machine to Amazon EC2 instance. :- I believe this is done by you as from your question it seems like you already made an entry with 0.0.0.0, which allows everybody to access the machine.
  2. MySQL not allowing user to connect from remote machine:- By default MySql creates root user id with admin access. But root id's access is limited to localhost only. This means that root user id with correct password will not work if you try to access MySql from a remote machine. To solve this problem, you need to allow either the root user or some other DB user to access MySQL from remote machine. I would not recommend allowing root user id accessing DB from remote machine. You can use wildcard character % to specify any remote machine.
  3. Check if machine's local firewall is not enabled. And if its enabled then make sure that port 3306 is open.

Please go through following link: How Do I Enable Remote Access To MySQL Database Server?

Visual C++ executable and missing MSVCR100d.dll

Usually the application that misses the .dll indicates what version you need – if one does not work, simply download the Microsoft visual C++ 2010 x86 or x64 from this link:

For 32 bit OS:Here

For 64 bit OS:Here

Dynamic Web Module 3.0 -- 3.1

I opened the project org.eclipse.wst.common.project.facet.core.xml and first changed then removed line with web module tag. Cleaned project and launched on Tomcat each time but it still didn't run. Returned line (as was) and cleaned project. Opened Tomcat settings in Eclipse and manually added project to Tomcat startup (Right click + Add and Remove). Clicked on project and selected Run on server....and everything was fine.

Importing JSON into an Eclipse project

Download java-json.jar from here, which contains org.json.JSONArray

http://www.java2s.com/Code/JarDownload/java/java-json.jar.zip

nzip and add to your project's library: Project > Build Path > Configure build path> Select Library tab > Add External Libraries > Select the java-json.jar file.

How to plot a 2D FFT in Matlab?

Here is an example from my HOW TO Matlab page:

close all; clear all;

img   = imread('lena.tif','tif');
imagesc(img)
img   = fftshift(img(:,:,2));
F     = fft2(img);

figure;

imagesc(100*log(1+abs(fftshift(F)))); colormap(gray); 
title('magnitude spectrum');

figure;
imagesc(angle(F));  colormap(gray);
title('phase spectrum');

This gives the magnitude spectrum and phase spectrum of the image. I used a color image, but you can easily adjust it to use gray image as well.

ps. I just noticed that on Matlab 2012a the above image is no longer included. So, just replace the first line above with say

img = imread('ngc6543a.jpg');

and it will work. I used an older version of Matlab to make the above example and just copied it here.

On the scaling factor

When we plot the 2D Fourier transform magnitude, we need to scale the pixel values using log transform to expand the range of the dark pixels into the bright region so we can better see the transform. We use a c value in the equation

s = c log(1+r) 

There is no known way to pre detrmine this scale that I know. Just need to try different values to get on you like. I used 100 in the above example.

enter image description here

How to call controller from the button click in asp.net MVC 4

You are mixing razor and aspx syntax,if your view engine is razor just do this:

<button class="btn btn-info" type="button" id="addressSearch"   
          onclick="location.href='@Url.Action("List", "Search")'">

How to hide 'Back' button on navigation bar on iPhone?

In c# or Xamarin.ios, this.NavigationItem.HidesBackButton = true;

standard_init_linux.go:190: exec user process caused "no such file or directory" - Docker

I found a particular edge case where I was using the tini init in an alpine container, but since I was not using the statically linked version, and Alpine uses musl libc rather than GNU LibC library installed by default, it was crashing with the very same error message.

Had I understood this and also taken time to read the documentation properly, I would have found Tini Static, which upon changing to, resolved my problem.

jQuery return ajax result into outside variable

I solved it by doing like that:

var return_first = (function () {
        var tmp = $.ajax({
            'type': "POST",
            'dataType': 'html',
            'url': "ajax.php?first",
            'data': { 'request': "", 'target': arrange_url, 'method': 
                    method_target },
            'success': function (data) {
                tmp = data;
            }
        }).done(function(data){
                return data;
        });
      return tmp;
    });
  • Be careful 'async':fale javascript will be asynchronous.

Horizontal ListView in Android?

For my application, I use a HorizontalScrollView containing LinearLayout inside, which has orientation set to horizontal. In order to add images inside, I create ImageViews inside the activity and add them to my LinearLayout. For example:

<HorizontalScrollView 
        android:id="@+id/photo_scroll"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:scrollbars="horizontal"
        android:visibility="gone">

        <LinearLayout 
            android:id="@+id/imageview_holder"
            android:layout_width="wrap_content"
            android:orientation="horizontal"
            android:layout_height="match_parent">

        </LinearLayout>
    </HorizontalScrollView>

An this works perfectly fine for me. In the activity all I have to do is something like the code below:

LinearLayout imgViewHolder = findViewById(R.id.imageview_holder);
ImageView img1 = new ImageView(getApplicationContext());
//set bitmap
//set img1 layout params
imgViewHolder.add(img1);
ImageView img2 = new ImageView(getApplicationContext());
//set bitmap
//set img2 layout params
imgViewHolder.add(img2); 

As I said that works for me, and I hope it helps somebody looking to achieve this as well.

bypass invalid SSL certificate in .net core

Allowing all certificates is very powerful but it could also be dangerous. If you would like to only allow valid certificates plus some certain certificates it could be done like this.

using (var httpClientHandler = new HttpClientHandler())
{
    httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, sslPolicyErrors) => {
        if (sslPolicyErrors == SslPolicyErrors.None)
        {
            return true;   //Is valid
        }

        if (cert.GetCertHashString() == "99E92D8447AEF30483B1D7527812C9B7B3A915A7")
        {
            return true;
        }
        return false;
    };
    using (var httpClient = new HttpClient(httpClientHandler))
    {
        var httpResponse = httpClient.GetAsync("https://example.com").Result;
    }
}

Original source:

https://stackoverflow.com/a/44140506/3850405

Math.random() explanation

Here's a method which receives boundaries and returns a random integer. It is slightly more advanced (completely universal): boundaries can be both positive and negative, and minimum/maximum boundaries can come in any order.

int myRand(int i_from, int i_to) {
  return (int)(Math.random() * (Math.abs(i_from - i_to) + 1)) + Math.min(i_from, i_to);
}

In general, it finds the absolute distance between the borders, gets relevant random value, and then shifts the answer based on the bottom border.

How to convert ASCII code (0-255) to its corresponding character?

This is an example, which shows that by converting an int to char, one can determine the corresponding character to an ASCII code.

public class sample6
{
    public static void main(String... asf)
    {

        for(int i =0; i<256; i++)
        {
            System.out.println( i + ". " + (char)i);
        }
    }
}

ActivityCompat.requestPermissions not showing dialog box

It could be not a problem with a single line of your code.

On some devices (I don't recall if it is in stock Android) the Permission dialog includes a check box labeled "Never ask again". If you click Deny with the box checked then you won't be prompted again for that permission, it will automatically be denied to the app. To revert this, you have to go into Settings -> App -> Permissions and re--enable that perm for the app. Then turn it off to deny it again. You may have to open the app before turning it off again, not sure.

I don't know if your Nexus has it. Maybe worth a try.

Return different type of data from a method in java?


public ArrayList divineCast(String object) {  
        try
        {
            Integer result = Integer.parseInt(object);
            ArrayList<Integer> generic = new   ArrayList<Integer>();
            generic.add(result);
            return generic;
        }
        catch(Exception e)
        {
            //not a Integer
        }
        try
        {
            Float result = Float.parseFloat(object);
            ArrayList<Float> generic = new   ArrayList<Float>();
            generic.add(result);
            return generic;
        }
        catch(Exception e)
        {
            //not a Float
        }
        try
        {
            Double result = Double.parseDouble(object);
            ArrayList<Double> generic = new   ArrayList<Double>();
            generic.add(result);
            return generic;
        }
        catch(Exception e)
        {
            //not a double
        }
        try
        {
            Boolean result = Boolean.parseBoolean(object);
            ArrayList<Boolean> generic = new   ArrayList<Boolean>();
            generic.add(result);
            return generic;
        }
        catch(Exception e)
        {
            //not a Boolean
        }
        try
        {
            String result = String.valueOf(object);
            ArrayList<String> generic = new   ArrayList<String>();
            generic.add(result);
            return generic;
        }
        catch(Exception e)
        {
            //not a String
        }
        return null;

    }

Then you can call then function as so

String test1 = "0.90854938";
String test2 = "true";
System.out.println(divineCast(test1).get(0));
System.out.println(divineCast(test1).get(0).getClass());
System.out.println(divineCast(test2).get(0));
System.out.println(divineCast(test2).get(0).getClass());

Java doesn't force you to declare the type of ArrayList you are returning in the function declaration, so you can return an ArrayList of any type.

How to align center the text in html table row?

<td align="center"valign="center">textgoeshere</td>

more on valign

How set background drawable programmatically in Android

Inside the app/res/your_xml_layout_file.xml

  1. Assign a name to your parent layout.
  2. Go to your MainActivity and find your RelativeLayout by calling the findViewById(R.id."given_name").
  3. Use the layout as a classic Object, by calling the method setBackgroundColor().

Which SchemaType in Mongoose is Best for Timestamp?

I would like to use this field in order to return all the records that have been updated in the last 5 minutes.

This means you need to update the date to "now" every time you save the object. Maybe you'll find this useful: Moongoose create-modified plugin

jQuery show/hide options from one select drop down, when option on other select dropdown is slected

Try -

$("#column_select").change(function () {
    $("#layout_select").children('option').hide();
    $("#layout_select").children("option[value^=" + $(this).val() + "]").show()
})  

If you were going to use this solution you'd need to hide all of the elements apart from the one with the 'none' value in your document.ready function -

$(document).ready(function() {
    $("#layout_select").children('option:gt(0)').hide();
    $("#column_select").change(function() {
        $("#layout_select").children('option').hide();
        $("#layout_select").children("option[value^=" + $(this).val() + "]").show()
    })
})

Demo - http://jsfiddle.net/Mxkfr/2

EDIT

I might have got a bit carried away with this, but here's a further example that uses a cache of the original select list options to ensure that the 'layout_select' list is completely reset/cleared (including the 'none' option) after the 'column_select' list is changed -

$(document).ready(function() {
    var optarray = $("#layout_select").children('option').map(function() {
        return {
            "value": this.value,
            "option": "<option value='" + this.value + "'>" + this.text + "</option>"
        }
    })

    $("#column_select").change(function() {
        $("#layout_select").children('option').remove();
        var addoptarr = [];
        for (i = 0; i < optarray.length; i++) {
            if (optarray[i].value.indexOf($(this).val()) > -1) {
                addoptarr.push(optarray[i].option);
            }
        }
        $("#layout_select").html(addoptarr.join(''))
    }).change();
})

Demo - http://jsfiddle.net/N7Xpb/1/

date format yyyy-MM-ddTHH:mm:ssZ

Console.WriteLine(DateTime.UtcNow.ToString("o"));  
Console.WriteLine(DateTime.Now.ToString("o"));

Outputs:

2012-07-09T19:22:09.1440844Z  
2012-07-09T12:22:09.1440844-07:00

Regex doesn't work in String.matches()

Welcome to Java's misnamed .matches() method... It tries and matches ALL the input. Unfortunately, other languages have followed suit :(

If you want to see if the regex matches an input text, use a Pattern, a Matcher and the .find() method of the matcher:

Pattern p = Pattern.compile("[a-z]");
Matcher m = p.matcher(inputstring);
if (m.find())
    // match

If what you want is indeed to see if an input only has lowercase letters, you can use .matches(), but you need to match one or more characters: append a + to your character class, as in [a-z]+. Or use ^[a-z]+$ and .find().

How to center an element in the middle of the browser window?

<div align="center">

or

<div style="margin: 0 auto;">

Rotate an image in image source in html

You can do this:

<img src="your image" style="transform:rotate(90deg);">

it is much easier.

Javascript array search and remove string?

use:

array.splice(2, 1);

This removes one item from the array, starting at index 2 (3rd item)

How to iterate using ngFor loop Map containing key as string and values as map iteration

Angular’s keyvalue pipe can be used, but unfortunately it sorts by key. Maps already have an order and it would be great to be able to keep it!

We can define out own pipe mapkeyvalue which preserves the order of items in the map:

import { Pipe, PipeTransform } from '@angular/core';

// Holds a weak reference to its key (here a map), so if it is no longer referenced its value can be garbage collected.
const cache = new WeakMap<ReadonlyMap<any, any>, Array<{ key: any; value: any }>>();

@Pipe({ name: 'mapkeyvalue', pure: true })
export class MapKeyValuePipe implements PipeTransform {
  transform<K, V>(input: ReadonlyMap<K, V>): Iterable<{ key: K; value: V }> {
    const existing = cache.get(input);
    if (existing !== undefined) {
      return existing;
    }

    const iterable = Array.from(input, ([key, value]) => ({ key, value }));
    cache.set(input, iterable);
    return iterable;
  }
}

It can be used like so:

<mat-select>
  <mat-option *ngFor="let choice of choicesMap | mapkeyvalue" [value]="choice.key">
    {{ choice.value }}
  </mat-option>
</mat-select>

How to mock private method for testing using PowerMock?

I don't see a problem here. With the following code using the Mockito API, I managed to do just that :

public class CodeWithPrivateMethod {

    public void meaningfulPublicApi() {
        if (doTheGamble("Whatever", 1 << 3)) {
            throw new RuntimeException("boom");
        }
    }

    private boolean doTheGamble(String whatever, int binary) {
        Random random = new Random(System.nanoTime());
        boolean gamble = random.nextBoolean();
        return gamble;
    }
}

And here's the JUnit test :

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.powermock.api.mockito.PowerMockito.when;
import static org.powermock.api.support.membermodification.MemberMatcher.method;

@RunWith(PowerMockRunner.class)
@PrepareForTest(CodeWithPrivateMethod.class)
public class CodeWithPrivateMethodTest {

    @Test(expected = RuntimeException.class)
    public void when_gambling_is_true_then_always_explode() throws Exception {
        CodeWithPrivateMethod spy = PowerMockito.spy(new CodeWithPrivateMethod());

        when(spy, method(CodeWithPrivateMethod.class, "doTheGamble", String.class, int.class))
                .withArguments(anyString(), anyInt())
                .thenReturn(true);

        spy.meaningfulPublicApi();
    }
}

Detect whether there is an Internet connection available on Android

Probably I have found myself:

ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
return connectivityManager.getActiveNetworkInfo().isConnectedOrConnecting();

Unable to import path from django.urls

Python 2 doesn't support Django 2. On a Mac once you've installed Python 3 and Django 2 run the following command from shell to run your app while keeping path:

python3 manage.py runserver

Even if you have upgraded and are on a mac you will, by default, run Python 2 if you're entering the following command:

python manage.py runserver

The version of Django will then be wrong and you will see import errors for path

What are unit tests, integration tests, smoke tests, and regression tests?

  • Integration testing: Integration testing is the integrate another element
  • Smoke testing: Smoke testing is also known as build version testing. Smoke testing is the initial testing process exercised to check whether the software under test is ready/stable for further testing.
  • Regression testing: Regression testing is repeated testing. Whether new software is effected in another module or not.
  • Unit testing: It is a white box testing. Only developers involve in it

Write objects into file with Node.js

Building on what deb2fast said I would also pass in a couple of extra parameters to JSON.stringify() to get it to pretty format:

fs.writeFileSync('./data.json', JSON.stringify(obj, null, 2) , 'utf-8');

The second param is an optional replacer function which you don't need in this case so null works.

The third param is the number of spaces to use for indentation. 2 and 4 seem to be popular choices.

Interview question: Check if one string is a rotation of other string

Whoa, whoa... why is everyone so thrilled with an O(n^2) answer? I'm positive that we can do better here. THE answer above includes an O(n) operation in an O(n) loop (the substring/indexOf call). Even with a more efficient search algorithm; say Boyer-Moore or KMP, the worst-case is still O(n^2) with duplicates.

A O(n) randomized answer is straightforward; take a hash (like a Rabin fingerprint) that supports an O(1) sliding window; hash string 1, then hash string 2, and proceed to move the window for hash 1 around the string and see if the hash functions collide.

If we imagine the worst case being something like "scanning two strands of DNA", then the probability of collisions goes up, and this probably degenerates to something like O(n^(1+e)) or something (just guessing here).

Finally, there's a deterministic O(nlogn) solution that has a very big constant outside. Basically, the idea is to take a convolution of the two strings. The max value of the convolution will be the rotation difference (if they are rotated); an O(n) check confirms. The nice thing is that if there are two equal max values, then they are both also valid solutions. You can do the convolution with two FFT's and a dot product, and an iFFT, so nlogn + nlogn + n + nlogn + n == O(nlogn).

Since you can't pad with zeroes, and you can't guarantee that the strings are of 2^n length, the FFTs won't be the fast ones; they'll be the slow ones, still O(nlogn) but a much bigger constant than the CT algorithm.

All that said, I'm absolutely, 100% positive that there is a deterministic O(n) solution here, but darned if I can find it.

jQuery find events handlers registered with an object

You can do it by crawling the events (as of jQuery 1.8+), like this:

$.each($._data($("#id")[0], "events"), function(i, event) {
  // i is the event type, like "click"
  $.each(event, function(j, h) {
    // h.handler is the function being called
  });
});

Here's an example you can play with:

_x000D_
_x000D_
$(function() {_x000D_
  $("#el").click(function(){ alert("click"); });_x000D_
  $("#el").mouseover(function(){ alert("mouseover"); });_x000D_
_x000D_
  $.each($._data($("#el")[0], "events"), function(i, event) {_x000D_
    output(i);_x000D_
    $.each(event, function(j, h) {_x000D_
        output("- " + h.handler);_x000D_
    });_x000D_
  });_x000D_
});_x000D_
_x000D_
function output(text) {_x000D_
    $("#output").html(function(i, h) {_x000D_
        return h + text + "<br />";_x000D_
    });_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="el">Test</div>_x000D_
<code>_x000D_
    <span id="output"></span>_x000D_
</code>
_x000D_
_x000D_
_x000D_

List(of String) or Array or ArrayList

You can use IList(Of String) in the function :

Private Function getWriteBits() As IList(Of String)


Dim temp1 As String
Dim temp2 As Boolean
Dim temp3 As Boolean


'Pallet Destination Unique
Dim temp4 As Boolean
Dim temp5 As Boolean
Dim temp6 As Boolean

Dim lstWriteBits As Ilist = {temp1, temp2, temp3, temp4, temp5, temp6}

Return lstWriteBits
End Function

use list1.AddRange(list2) to add lists

Hope it helps.

Npm Please try using this command again as root/administrator

Try following steps

1. Run this command on Terminal or CMD - npm cache clean

2. Go to this folder on windows %APPDATA%\npm-cache And delete folder which you want to install module (Ex:- laravel-elixir) or if you are using PowerShell, $env:APPDATA\npm-cache

3. Then Run your command EX:- npm install laravel-elixir

How to select a record and update it, with a single queryset in Django?

Use the queryset object update method:

MyModel.objects.filter(pk=some_value).update(field1='some value')

C++ printing spaces or tabs given a user input integer

Simply add spaces for { 2 3 4 5 6 } like these:

cout<<"{";

for(){
    cout<<" "<<n;    //n is the element to print !
}

cout<<" }";

MAX() and MAX() OVER PARTITION BY produces error 3504 in Teradata Query

SELECT employee_number, course_code, MAX(course_completion_date) AS max_date
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code

HTML5 and frameborder

HTML 5 doesn't support attributes such as frameborder, scrolling, marginwidth, and marginheight (which were supported in HTML 4.01). Instead, the HTML 5 specification has introduced the seamless attribute. The seamless attribute allows the inline frame to appear as though it is being rendered as part of the containing document. For example, borders and scrollbars will not appear.

According to MDN

frameborder Obsolete since HTML5

The value 1 (the default) draws a border around this frame. The value 0 removes the border around this frame, but you should instead use the CSS property border to control borders.

Like the quote above says, you should remove the border with CSS;
either inline (style="border: none;") or in your stylesheet (iframe { border: none; }).

That being said, there doesn't seem to be a single iframe provider that doesn't use frameborder="0". Even YouTube still uses the attribute and doesn't even provide a style attribute to make iframes backwards compatible for when frameborder isn't supported anymore. It's safe to say that the attribute isn't going anywhere soon. This leaves you with 3 options:

  1. Keep using frameborder, just to be sure it works (for now)
  2. Use CSS, to do the "right" thing
  3. Use both. Although this doesn't resolve the incompatibility problem (just like option 1), it does and will work in every browser that has been and will be

As for the previous state of this decade-old answer:

The seamless attribute has been supported for such a short time (or not at all by some browsers), that MDN doesn't even list it as a deprecated feature. Don't use it and don't get confused by the comments below.

Run automatically program on startup under linux ubuntu

sudo mv /filename /etc/init.d/
sudo chmod +x /etc/init.d/filename 
sudo update-rc.d filename defaults 

Script should now start on boot. Note that this method also works with both hard links and symbolic links (ln).

Edit

At this point in the boot process PATH isn't set yet, so it is critical that absolute paths are used throughout. BUT, as pointed out in the comments by Steve HHH, explicitly declaring the full file path (/etc/init.d/filename) for the update-rc.d command is not valid in most versions of Linux. Per the manpage for update-rc.d, the second parameter is a script located in /etc/init.d/*. Updated above code to reflect this.

Another Edit

Also as pointed out in the comments (by Charles Brandt), /filename must be an init style script. A good template was also provided - https://github.com/fhd/init-script-template.

Another link to another article just to avoid possible link rot (although it would be saddening if GitHub died) - http://www.linux.com/learn/tutorials/442412-managing-linux-daemons-with-init-scripts

yetAnother Edit

As pointed out in the comments (by Russell Yan), This works only on default mode of update-rc.d.

According to manual of update-rc.d, it can run on two modes, "the machines using the legacy mode will have a file /etc/init.d/.legacy-bootordering", in which case you have to pass sequence and runlevel configuration through command line arguments.

The equivalent argument set for the above example is

sudo update-rc.d filename start 20 2 3 4 5 . stop 20 0 1 6 .

Remove Backslashes from Json Data in JavaScript

You need to deserialize the JSON once before returning it as response. Please refer below code. This works for me:

JavaScriptSerializer jss = new JavaScriptSerializer();
Object finalData = jss.DeserializeObject(str);

List of foreign keys and the tables they reference in Oracle DB

Try this:

select * from all_constraints where r_constraint_name in (select constraint_name 
from all_constraints where table_name='YOUR_TABLE_NAME');

if-else statement inside jsx: ReactJS

You can do this. Just don't forget to put "return" before your JSX component.

Example:

render() {
    if(this.state.page === 'news') {
        return <Text>This is news page</Text>;
    } else {
        return <Text>This is another page</Text>;
    }
}

Example to fetch data from internet:

import React, { Component } from 'react';
import {
    View,
    Text
} from 'react-native';

export default class Test extends Component {
    constructor(props) {
        super(props);

        this.state = {
            bodyText: ''
        }
    }

    fetchData() {
        fetch('https://example.com').then((resp) => {
            this.setState({
                bodyText: resp._bodyText
            });
        });
    }

    componentDidMount() {
        this.fetchData();
    }

    render() {
        return <View style={{ flex: 1 }}>
            <Text>{this.state.bodyText}</Text>
        </View>
    }
}

Check whether a string contains a substring

To find out if a string contains substring you can use the index function:

if (index($str, $substr) != -1) {
    print "$str contains $substr\n";
} 

It will return the position of the first occurrence of $substr in $str, or -1 if the substring is not found.

MySQL : ERROR 1215 (HY000): Cannot add foreign key constraint

Below code worked for me

set @@foreign_key_checks=0;
ALTER TABLE  `table1` ADD CONSTRAINT `table1_fk1` FOREIGN KEY (`coloumn`) REFERENCES `table2` (`id`) ON DELETE CASCADE;

How to Replace dot (.) in a string in Java

If you want to replace a simple string and you don't need the abilities of regular expressions, you can just use replace, not replaceAll.

replace replaces each matching substring but does not interpret its argument as a regular expression.

str = xpath.replace(".", "/*/");

What is the difference between server side cookie and client side cookie?

What is the difference between creating cookies on the server and on the client?

What you are referring to are the 2 ways in which cookies can be directed to be set on the client, which are:

  • By server
  • By client ( browser in most cases )

By server: The Set-cookie response header from the server directs the client to set a cookie on that particular domain. The implementation to actually create and store the cookie lies in the browser. For subsequent requests to the same domain, the browser automatically sets the Cookie request header for each request, thereby letting the server have some state to an otherwise stateless HTTP protocol. The Domain and Path cookie attributes are used by the browser to determine which cookies are to be sent to a server. The server only receives name=value pairs, and nothing more.

By Client: One can create a cookie on the browser using document.cookie = cookiename=cookievalue. However, if the server does not intend to respond to any random cookie a user creates, then such a cookie serves no purpose.

Are these called server side cookies and client side cookies?

Cookies always belong to the client. There is no such thing as server side cookie.

Is there a way to create cookies that can only be read on the server or on the client?

Since reading cookie values are upto the server and client, it depends if either one needs to read the cookie at all. On the client side, by setting the HttpOnly attribute of the cookie, it is possible to prevent scripts ( mostly Javscript ) from reading your cookies , thereby acting as a defence mechanism against Cookie theft through XSS, but sends the cookie to the intended server only.

Therefore, in most of the cases since cookies are used to bring 'state' ( memory of past user events ), creating cookies on client side does not add much value, unless one is aware of the cookies the server uses / responds to.

References: Wikipedia

ProgressDialog in AsyncTask

This question is already answered and most of the answers here are correct but they don't solve one major issue with config changes. Have a look at this article https://androidresearch.wordpress.com/2013/05/10/dealing-with-asynctask-and-screen-orientation/ if you would like to write a async task in a better way.

How to define a variable in a Dockerfile?

If the variable is re-used within the same RUN instruction, one could simply set a shell variable. I really like how they approached this with the official Ruby Dockerfile.

Select only rows if its value in a particular column is less than the value in the other column

df[df$aged <= df$laclen, ] 

Should do the trick. The square brackets allow you to index based on a logical expression.

Declaring variables inside or outside of a loop

I compared the byte code of those two (similar) examples:

Let's look at 1. example:

package inside;

public class Test {
    public static void main(String[] args) {
        while(true){
            String str = String.valueOf(System.currentTimeMillis());
            System.out.println(str);
        }
    }
}

after javac Test.java, javap -c Test you'll get:

public class inside.Test extends java.lang.Object{
public inside.Test();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return

public static void main(java.lang.String[]);
  Code:
   0:   invokestatic    #2; //Method java/lang/System.currentTimeMillis:()J
   3:   invokestatic    #3; //Method java/lang/String.valueOf:(J)Ljava/lang/String;
   6:   astore_1
   7:   getstatic       #4; //Field java/lang/System.out:Ljava/io/PrintStream;
   10:  aload_1
   11:  invokevirtual   #5; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
   14:  goto    0

}

Let's look at 2. example:

package outside;

public class Test {
    public static void main(String[] args) {
        String str;
        while(true){
            str =  String.valueOf(System.currentTimeMillis());
            System.out.println(str);
        }
    }
}

after javac Test.java, javap -c Test you'll get:

public class outside.Test extends java.lang.Object{
public outside.Test();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return

public static void main(java.lang.String[]);
  Code:
   0:   invokestatic    #2; //Method java/lang/System.currentTimeMillis:()J
   3:   invokestatic    #3; //Method java/lang/String.valueOf:(J)Ljava/lang/String;
   6:   astore_1
   7:   getstatic       #4; //Field java/lang/System.out:Ljava/io/PrintStream;
   10:  aload_1
   11:  invokevirtual   #5; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
   14:  goto    0

}

The observations shows that there is no difference among those two examples. It's the result of JVM specifications...

But in the name of best coding practice it is recommended to declare the variable in the smallest possible scope (in this example it is inside the loop, as this is the only place where the variable is used).

Truncate Two decimal places without rounding

Would ((long)(3.4679 * 100)) / 100.0 give what you want?

Differentiate between function overloading and function overriding

Function overloading - functions with same name, but different number of arguments

Function overriding - concept of inheritance. Functions with same name and same number of arguments. Here the second function is said to have overridden the first

Why does range(start, end) not include end?

Although there are some useful algorithmic explanations here, I think it may help to add some simple 'real life' reasoning as to why it works this way, which I have found useful when introducing the subject to young newcomers:

With something like 'range(1,10)' confusion can arise from thinking that pair of parameters represents the "start and end".

It is actually start and "stop".

Now, if it were the "end" value then, yes, you might expect that number would be included as the final entry in the sequence. But it is not the "end".

Others mistakenly call that parameter "count" because if you only ever use 'range(n)' then it does, of course, iterate 'n' times. This logic breaks down when you add the start parameter.

So the key point is to remember its name: "stop". That means it is the point at which, when reached, iteration will stop immediately. Not after that point.

So, while "start" does indeed represent the first value to be included, on reaching the "stop" value it 'breaks' rather than continuing to process 'that one as well' before stopping.

One analogy that I have used in explaining this to kids is that, ironically, it is better behaved than kids! It doesn't stop after it supposed to - it stops immediately without finishing what it was doing. (They get this ;) )

Another analogy - when you drive a car you don't pass a stop/yield/'give way' sign and end up with it sitting somewhere next to, or behind, your car. Technically you still haven't reached it when you do stop. It is not included in the 'things you passed on your journey'.

I hope some of that helps in explaining to Pythonitos/Pythonitas!

How to write a CSS hack for IE 11?

I have been writing these and contributing them to BrowserHacks.com since the fall of 2013 -- this one I wrote is very simple and only supported by IE 11.

<style type="text/css">
_:-ms-fullscreen, :root .msie11 { color: blue; }
</style>

and of course the div...

<div class="msie11">
    This is an Internet Explorer 11 CSS Hack
<div>

So the text shows up in blue with internet explorer 11. Have fun with it.

-

More IE and other browser CSS hacks on my live test site here:

UPDATED: http://browserstrangeness.bitbucket.io/css_hacks.html

MIRROR: http://browserstrangeness.github.io/css_hacks.html

(If you are also looking for MS Edge CSS Hacks, that is where to go.)

How to detect page zoom level in all modern browsers?

You can try

var browserZoomLevel = Math.round(window.devicePixelRatio * 100);

This will give you browser zoom percentage level on non-retina displays. For high DPI/retina displays, it would yield different values (e.g., 200 for Chrome and Safari, 140 for Firefox).

To catch zoom event you can use

$(window).resize(function() { 
// your code 
});

How can I mock requests and the response?

this is how you mock requests.post, change it to your http method

@patch.object(requests, 'post')
def your_test_method(self, mockpost):
    mockresponse = Mock()
    mockpost.return_value = mockresponse
    mockresponse.text = 'mock return'

    #call your target method now

How to fill Dataset with multiple tables?

It is an old topic, but for some people it might be useful:

        DataSet someDataSet = new DataSet();
        SqlDataAdapter adapt = new SqlDataAdapter();

        using(SqlConnection connection = new SqlConnection(ConnString))
        {
            connection.Open();
            SqlCommand comm1 = new SqlCommand("SELECT * FROM whateverTable", connection);
            SqlCommand comm2g = new SqlCommand("SELECT * FROM whateverTable WHERE condition = @0", connection);
            commProcessing.Parameters.AddWithValue("@0", "value");
            someDataSet.Tables.Add("Table1");
            someDataSet.Tables.Add("Table2");

            adapt.SelectCommand = comm1;
            adapt.Fill(someDataSet.Tables["Table1"]);
            adapt.SelectCommand = comm2;
            adapt.Fill(someDataSet.Tables["Table2"]);
        }

Hexadecimal To Decimal in Shell Script

The error as reported appears when the variables are null (or empty):

$ unset var3 var4; var5=$(($var4-$var3))
bash: -: syntax error: operand expected (error token is "-")

That could happen because the value given to bc was incorrect. That might well be that bc needs UPPERcase values. It needs BFCA3000, not bfca3000. That is easily fixed in bash, just use the ^^ expansion:

var3=bfca3000; var3=`echo "ibase=16; ${var1^^}" | bc`

That will change the script to this:

#!/bin/bash

var1="bfca3000"
var2="efca3250"

var3="$(echo "ibase=16; ${var1^^}" | bc)"
var4="$(echo "ibase=16; ${var2^^}" | bc)"

var5="$(($var4-$var3))"

echo "Diference $var5"

But there is no need to use bc [1], as bash could perform the translation and substraction directly:

#!/bin/bash

var1="bfca3000"
var2="efca3250"

var5="$(( 16#$var2 - 16#$var1 ))"

echo "Diference $var5"

[1]Note: I am assuming the values could be represented in 64 bit math, as the difference was calculated in bash in your original script. Bash is limited to integers less than ((2**63)-1) if compiled in 64 bits. That will be the only difference with bc which does not have such limit.

Differences between utf8 and latin1

In latin1 each character is exactly one byte long. In utf8 a character can consist of more than one byte. Consequently utf8 has more characters than latin1 (and the characters they do have in common aren't necessarily represented by the same byte/bytesequence).

smtpclient " failure sending mail"

This error can appear when the web server can't access the mail server. Make sure the web server can reach the mail server, for instance pinging it.

What is the HTML unicode character for a "tall" right chevron?

Use '›'

&rsaquo; -> single right angle quote. For single left angle quote, use &lsaquo;

Pandas: sum DataFrame rows for given columns

If you have just a few columns to sum, you can write:

df['e'] = df['a'] + df['b'] + df['d']

This creates new column e with the values:

   a  b   c  d   e
0  1  2  dd  5   8
1  2  3  ee  9  14
2  3  4  ff  1   8

For longer lists of columns, EdChum's answer is preferred.

What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?

As all of the other answers have already said, it's part of ES2015 arrow function syntax. More specifically, it's not an operator, it's a punctuator token that separates the parameters from the body: ArrowFunction : ArrowParameters => ConciseBody. E.g. (params) => { /* body */ }.

How to set up Android emulator proxy settings

For setting proxy server we need to set APNS setting. To do this:

  1. Go to Setting

  2. Go to wireless and networks

  3. Go to mobile networks

  4. Go to access point names. Use menu to add new apns

    Set Proxy = localhost

    Set Port = port that you are using to make proxy server, in my case it is 8989

    For setting Name and apn here is the link:

    According to your sim card you can see the table

Uncaught TypeError: Cannot set property 'value' of null

guys This error because of Element Id not Visible from js Try to inspect element from UI and paste it on javascript file:

before :

document.getElementById('form:salesoverviewform:ticketstatusid').value =topping;

After :

document.getElementById('form:salesoverviewform:j_idt190:ticketstatusid').value =topping;

Credits to Divya Akka .... :)

How do I prevent DIV tag starting a new line?

use float:left on the div and the link, or use a span.

How do you check "if not null" with Eloquent?

If you want to search deleted record (Soft Deleted Record), do't user Eloquent Model Query. Instead use Db::table query e.g Instead of using Below:

$stu = Student::where('rollNum', '=', $rollNum . '-' . $nursery)->first();

Use:

$stu = DB::table('students')->where('rollNum', '=', $newRollNo)->first();

<hr> tag in Twitter Bootstrap not functioning correctly?

By default, the hr element in Twitter Bootstrap CSS file has a top and bottom margin of 18px. That's what creates a gap. If you want the gap to be smaller you'll need to adjust margin property of the hr element.

In your example, do something like this:

.container hr {
margin: 2px 0;
}

How to format time since xxx e.g. “4 minutes ago” similar to Stack Exchange sites

A shorter version as used by Lokely:

const intervals = [
  { label: 'year', seconds: 31536000 },
  { label: 'month', seconds: 2592000 },
  { label: 'day', seconds: 86400 },
  { label: 'hour', seconds: 3600 },
  { label: 'minute', seconds: 60 },
  { label: 'second', seconds: 0 }
];

function timeSince(date) {
  const seconds = Math.floor((Date.now() - date.getTime()) / 1000);
  const interval = intervals.find(i => i.seconds < seconds);
  const count = Math.floor(seconds / interval.seconds);
  return `${count} ${interval.label}${count !== 1 ? 's' : ''} ago`;
}

How to enable TLS 1.2 support in an Android application (running on Android 4.1 JB)

@Inherently Curious - thanks for posting this. You are almost there - you have to add two more params to SSLContext.init() method.

TrustManager[] trustManagers = new TrustManager[] { new TrustManagerManipulator() };
sc.init(null, trustManagers, new SecureRandom());

it will start working. Again thank you very much for posting this. I solved this/my issue with your code.

How to unlock android phone through ADB

Slightly modifying answer by @Yogeesh Seralathan. His answer works perfectly, just run these commands at once.

adb shell input keyevent 26 && adb shell input touchscreen swipe 930 880 930 380 && adb shell input text XXXX && adb shell input keyevent 66

String.Format for Hex

Translate composed UInt32 color Value to CSS in .NET

I know the question applies to 3 input values (red green blue). But there may be the situation where you already have a composed 32bit Value. It looks like you want to send the data to some HTML CSS renderer (because of the #HEX format). Actually CSS wants you to print 6 or at least 3 zero filled hex digits here. so #{0:X06} or #{0:X03} would be required. Due to some strange behaviour, this always prints 8 digits instead of 6.

Solve this by:

String.Format("#{0:X02}{1:X02}{2:X02}", (Value & 0x00FF0000) >> 16, (Value & 0x0000FF00) >> 8, (Value & 0x000000FF) >> 0)

Match multiline text using regular expression

str.matches(regex) behaves like Pattern.matches(regex, str) which attempts to match the entire input sequence against the pattern and returns

true if, and only if, the entire input sequence matches this matcher's pattern

Whereas matcher.find() attempts to find the next subsequence of the input sequence that matches the pattern and returns

true if, and only if, a subsequence of the input sequence matches this matcher's pattern

Thus the problem is with the regex. Try the following.

String test = "User Comments: This is \t a\ta \ntest\n\n message \n";

String pattern1 = "User Comments: [\\s\\S]*^test$[\\s\\S]*";
Pattern p = Pattern.compile(pattern1, Pattern.MULTILINE);
System.out.println(p.matcher(test).find());  //true

String pattern2 = "(?m)User Comments: [\\s\\S]*^test$[\\s\\S]*";
System.out.println(test.matches(pattern2));  //true

Thus in short, the (\\W)*(\\S)* portion in your first regex matches an empty string as * means zero or more occurrences and the real matched string is User Comments: and not the whole string as you'd expect. The second one fails as it tries to match the whole string but it can't as \\W matches a non word character, ie [^a-zA-Z0-9_] and the first character is T, a word character.

How can I run an EXE program from a Windows Service using C#?

You can execute an .exe from a Windows service very well in Windows XP. I have done it myself in the past.

You need to make sure you had checked the option "Allow to interact with the Desktop" in the Windows service properties. If that is not done, it will not execute.

I need to check in Windows 7 or Vista as these versions requires additional security privileges so it may throw an error, but I am quite sure it can be achieved either directly or indirectly. For XP I am certain as I had done it myself.

Ignoring SSL certificate in Apache HttpClient 4.3

class ApacheHttpClient {

    /***
     * This is a https get request that bypasses certificate checking and hostname verifier.
     * It uses basis authentication method.
     * It is tested with Apache httpclient-4.4.
     * It dumps the contents of a https page on the console output.
     * It is very similar to http get request, but with the additional customization of
     *   - credential provider, and
     *   - SSLConnectionSocketFactory to bypass certification checking and hostname verifier.
     * @param path String
     * @param username String
     * @param password String
     * @throws IOException
     */
    public void get(String path, String username, String password) throws IOException {
        final CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultCredentialsProvider(createCredsProvider(username, password))
                .setSSLSocketFactory(createGenerousSSLSocketFactory())
                .build();

        final CloseableHttpResponse response = httpClient.execute(new HttpGet(path));
        try {
            HttpEntity entity = response.getEntity();
            if (entity == null)
                return;
            System.out.println(EntityUtils.toString(entity));
        } finally {
            response.close();
            httpClient.close();
        }
    }

    private CredentialsProvider createCredsProvider(String username, String password) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
                AuthScope.ANY,
                new UsernamePasswordCredentials(username, password));
        return credsProvider;
    }

    /***
     * 
     * @return SSLConnectionSocketFactory that bypass certificate check and bypass HostnameVerifier
     */
    private SSLConnectionSocketFactory createGenerousSSLSocketFactory() {
        SSLContext sslContext;
        try {
            sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, new TrustManager[]{createGenerousTrustManager()}, new SecureRandom());
        } catch (KeyManagementException | NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
        return new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
    }

    private X509TrustManager createGenerousTrustManager() {
        return new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] cert, String s) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] cert, String s) throws CertificateException {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
    }
}

Confirm deletion using Bootstrap 3 modal box

I've the same problem just today. This is my solution (which I think is better and simpler):

<!-- Modal dialog -->
<div class="modal fade" id="frmPrenotazione" tabindex="-1">
    <!-- CUTTED -->
    <div id="step1" class="modal-footer">
      <button type="button" class="glyphicon glyphicon-erase btn btn-default" id="btnDelete"> Delete</button>
    </div>
</div>

<!-- Modal confirm -->
<div class="modal" id="confirmModal" style="display: none; z-index: 1050;">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-body" id="confirmMessage">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" id="confirmOk">Ok</button>
                <button type="button" class="btn btn-default" id="confirmCancel">Cancel</button>
            </div>
        </div>
    </div>
</div>

And in my .js:

$('#btnDelete').on('click', function(e){
    confirmDialog(YOUR_MESSAGE_STRING_CONST, function(){
        //My code to delete
    });
});

function confirmDialog(message, onConfirm){
    var fClose = function(){
        modal.modal("hide");
    };
    var modal = $("#confirmModal");
    modal.modal("show");
    $("#confirmMessage").empty().append(message);
    $("#confirmOk").unbind().one('click', onConfirm).one('click', fClose);
    $("#confirmCancel").unbind().one("click", fClose);
}

Using unbind before the one prevents that the removal function is invoked at the next opening of the dialog.

I hope this could be helpful.

Follow a complete example:

_x000D_
_x000D_
var YOUR_MESSAGE_STRING_CONST = "Your confirm message?";_x000D_
      $('#btnDelete').on('click', function(e){_x000D_
      confirmDialog(YOUR_MESSAGE_STRING_CONST, function(){_x000D_
       //My code to delete_x000D_
          console.log("deleted!");_x000D_
      });_x000D_
     });_x000D_
_x000D_
        function confirmDialog(message, onConfirm){_x000D_
         var fClose = function(){_x000D_
         modal.modal("hide");_x000D_
         };_x000D_
         var modal = $("#confirmModal");_x000D_
         modal.modal("show");_x000D_
         $("#confirmMessage").empty().append(message);_x000D_
         $("#confirmOk").unbind().one('click', onConfirm).one('click', fClose);_x000D_
         $("#confirmCancel").unbind().one("click", fClose);_x000D_
        }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<!-- Modal dialog -->_x000D_
<div id="frmTest" tabindex="-1">_x000D_
    <!-- CUTTED -->_x000D_
      <div id="step1" class="modal-footer">_x000D_
    <button type="button" class="glyphicon glyphicon-erase btn btn-default" id="btnDelete"> Delete</button>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
  <!-- Modal confirm -->_x000D_
<div class="modal" id="confirmModal" style="display: none; z-index: 1050;">_x000D_
  <div class="modal-dialog">_x000D_
    <div class="modal-content">_x000D_
      <div class="modal-body" id="confirmMessage">_x000D_
      </div>_x000D_
      <div class="modal-footer">_x000D_
        <button type="button" class="btn btn-default" id="confirmOk">Ok</button>_x000D_
            <button type="button" class="btn btn-default" id="confirmCancel">Cancel</button>_x000D_
          </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to use color picker (eye dropper)?

Currently, the eyedropper tool is not working in my version of Chrome (as described above), though it worked for me in the past. I hear it is being updated in the latest version of Chrome.

However, I'm able to grab colors easily in Firefox.

  1. Open page in Firefox
  2. Hamburger Menu -> Web Developer -> Eyedropper
  3. Drag eyedropper tool over the image... Click.
    Color is copied to your clipboard, and eyedropper tool goes away.
  4. Paste color code

In case you cannot get the eyedropper tool to work in Chrome, this is a good work around.
I also find it easier to access :-)

Excel VBA - Pass a Row of Cell Values to an Array and then Paste that Array to a Relative Reference of Cells

You are off slightly on a few things here, so hopefully the following helps.

Firstly, you don't need to select ranges to access their properties, you can just specify their address etc. Secondly, unless you are manipulating the values within the range, you don't actually need to set them to a variant. If you do want to manipulate the values, you can leave out the bounds of the array as it will be set when you define the range.

It's also good practice to use Option Explicit at the top of your modules to force variable declaration.

The following will do what you are after:

Sub ARRAYER()
    Dim Number_of_Sims As Integer, i As Integer

    Number_of_Sims = 10

    For i = 1 To Number_of_Sims
       'Do your calculation here to update C4 to G4
       Range(Cells(4 + i, "C"), Cells(4 + i, "G")).Value = Range("C4:G4").Value
    Next
End Sub

If you do want to manipulate the values within the array then do this:

Sub ARRAYER()
    Dim Number_of_Sims As Integer, i As Integer
    Dim anARRAY as Variant

    Number_of_Sims = 10

    For i = 1 To Number_of_Sims
       'Do your calculation here to update C4 to G4
       anARRAY= Range("C4:G4").Value

       'You can loop through the array and manipulate it here

       Range(Cells(4 + i, "C"), Cells(4 + i, "G")).Value = anARRAY
    Next
End Sub

How to get std::vector pointer to the raw data?

something.data() will return a pointer to the data space of the vector.

What are some good SSH Servers for windows?

You can run OpenSSH on Cygwin, and even install it as a Windows service.

I once used it this way to easily add backups of a Unix system - it would rsync a bunch of files onto the Windows server, and the Windows server had full tape backups.

How can I rename column in laravel using migration?

first thing you want to do is to create your migration file.

Type in your command line

php artisan make:migration rename_stk_column --table="YOUR TABLE" --create

After creating the file. Open the new created migration file in your app folder under database/migrations.

In your up method insert this:

Schema::table('stnk', function(Blueprint $table)
    {
        $table->renameColumn('id', 'id_stnk');
    });
}

and in your down method:

    Schema::table('stnk', function(Blueprint $table)
    {
        $table->renameColumn('id_stnk', 'id);
    });
}

then in your command line just type

php artisan migrate

Then wollah! you have just renamed id to id_stnk. BTW you can use

php artisan migrate:rollback

to undo the changes. Goodluck

Regular expression field validation in jQuery

I'm using jQuery and JavaScript and it works fine for me:

var rege = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if(rege.test($('#uemail').val())){ //do something }

GET URL parameter in PHP

$_GET is not a function or language construct—it's just a variable (an array). Try:

<?php
echo $_GET['link'];

In particular, it's a superglobal: a built-in variable that's populated by PHP and is available in all scopes (you can use it from inside a function without the global keyword).

Since the variable might not exist, you could (and should) ensure your code does not trigger notices with:

<?php
if (isset($_GET['link'])) {
    echo $_GET['link'];
} else {
    // Fallback behaviour goes here
}

Alternatively, if you want to skip manual index checks and maybe add further validations you can use the filter extension:

<?php
echo filter_input(INPUT_GET, 'link', FILTER_SANITIZE_URL);

Last but not least, you can use the null coalescing operator (available since PHP/7.0) to handle missing parameters:

echo $_GET['link'] ?? 'Fallback value';

How to check the first character in a string in Bash or UNIX shell?

Consider the case statement as well which is compatible with most sh-based shells:

case $str in
/*)
    echo 1
    ;;
*)
    echo 0
    ;;
esac

How do I fix MSB3073 error in my post-build event?

In my case, the dll I was creating by building the project was still in use in the background. I killed the application and then xcopy worked fine as expected.

Force table column widths to always be fixed regardless of contents

Try looking into the following CSS:

word-wrap:break-word;

Web browsers should not break-up "words" by default so what you are experiencing is normal behaviour of a browser. However you can override this with the word-wrap CSS directive.

You would need to set a width on the overall table then a width on the columns. "width:100%;" should also be OK depending on your requirements.

Using word-wrap may not be what you want however it is useful for showing all of the data without deforming the layout.

java.io.IOException: Broken pipe

The most common reason I've had for a "broken pipe" is that one machine (of a pair communicating via socket) has shut down its end of the socket before communication was complete. About half of those were because the program communicating on that socket had terminated.

If the program sending bytes sends them out and immediately shuts down the socket or terminates itself, it is possible for the socket to cease functioning before the bytes have been transmitted and read.

Try putting pauses anywhere you are shutting down the socket and before you allow the program to terminate to see if that helps.

FYI: "pipe" and "socket" are terms that get used interchangeably sometimes.

What is the syntax for Typescript arrow functions with generics?

The language specification says on p.64f

A construct of the form < T > ( ... ) => { ... } could be parsed as an arrow function expression with a type parameter or a type assertion applied to an arrow function with no type parameter. It is resolved as the former[..]

example:

// helper function needed because Backbone-couchdb's sync does not return a jqxhr
let fetched = <
           R extends Backbone.Collection<any> >(c:R) => {
               return new Promise(function (fulfill, reject) {
                   c.fetch({reset: true, success: fulfill, error: reject})
               });
           };

How to get item's position in a list?

[x for x in range(len(testlist)) if testlist[x]==1]

How to get object length

Can be done easily with $.map():

var len = $.map(a, function(n, i) { return i; }).length;

What is the simplest way to SSH using Python?

I have written Python bindings for libssh2. Libssh2 is a client-side library implementing the SSH2 protocol.

import socket
import libssh2

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('exmaple.com', 22))

session = libssh2.Session()
session.startup(sock)
session.userauth_password('john', '******')

channel = session.channel()
channel.execute('ls -l')

print channel.read(1024)

How do you list volumes in docker containers?

For Docker 1.8, I use:

$ docker inspect -f "{{ .Config.Volumes }}" 957d2dd1d4e8
map[/xmount/dvol.01:{}]
$ 

css h1 - only as wide as the text

You could use a <span> instead of an <h1>.

Number input type that takes only integers?

Currently, it is not possible to prevent a user from writing decimal values in your input with HTML only. You have to use javascript.

How to find index of an object by key and value in an javascript array

The Functional Approach

All the cool kids are doing functional programming (hello React users) these days so I thought I would give the functional solution. In my view it's actually a lot nicer than the imperatival for and each loops that have been proposed thus far and with ES6 syntax it is quite elegant.

Update

There's now a great way of doing this called findIndex which takes a function that return true/false based on whether the array element matches (as always, check for browser compatibility though).

var index = peoples.findIndex(function(person) {
  return person.attr1 == "john"
}

With ES6 syntax you get to write this:

var index = peoples.findIndex(p => p.attr1 == "john")

The (Old) Functional Approach

TL;DR

If you're looking for index where peoples[index].attr1 == "john" use:

var index = peoples.map(function(o) { return o.attr1; }).indexOf("john");

Explanation

Step 1

Use .map() to get an array of values given a particular key:

var values = object_array.map(function(o) { return o.your_key; });

The line above takes you from here:

var peoples = [
  { "attr1": "bob", "attr2": "pizza" },
  { "attr1": "john", "attr2": "sushi" },
  { "attr1": "larry", "attr2": "hummus" }
];

To here:

var values = [ "bob", "john", "larry" ];

Step 2

Now we just use .indexOf() to find the index of the key we want (which is, of course, also the index of the object we're looking for):

var index = values.indexOf(your_value);

Solution

We combine all of the above:

var index = peoples.map(function(o) { return o.attr1; }).indexOf("john");

Or, if you prefer ES6 syntax:

var index = peoples.map((o) => o.attr1).indexOf("john");

Demo:

_x000D_
_x000D_
var peoples = [_x000D_
  { "attr1": "bob", "attr2": "pizza" },_x000D_
  { "attr1": "john", "attr2": "sushi" },_x000D_
  { "attr1": "larry", "attr2": "hummus" }_x000D_
];_x000D_
_x000D_
var index = peoples.map(function(o) { return o.attr1; }).indexOf("john");_x000D_
console.log("index of 'john': " + index);_x000D_
_x000D_
var index = peoples.map((o) => o.attr1).indexOf("larry");_x000D_
console.log("index of 'larry': " + index);_x000D_
_x000D_
var index = peoples.map(function(o) { return o.attr1; }).indexOf("fred");_x000D_
console.log("index of 'fred': " + index);_x000D_
_x000D_
var index = peoples.map((o) => o.attr2).indexOf("pizza");_x000D_
console.log("index of 'pizza' in 'attr2': " + index);
_x000D_
_x000D_
_x000D_

CSS - Make divs align horizontally

This seems close to what you want:

_x000D_
_x000D_
#foo {_x000D_
  background: red;_x000D_
  max-height: 100px;_x000D_
  overflow-y: hidden;_x000D_
}_x000D_
_x000D_
.bar {_x000D_
  background: blue;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  float: left;_x000D_
  margin: 1em;_x000D_
}
_x000D_
<div id="foo">_x000D_
  <div class="bar"></div>_x000D_
  <div class="bar"></div>_x000D_
  <div class="bar"></div>_x000D_
  <div class="bar"></div>_x000D_
  <div class="bar"></div>_x000D_
  <div class="bar"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to know which is running in Jupyter notebook?

from platform import python_version

print(python_version())

This will give you the exact version of python running your script. eg output:

3.6.5

Iterating on a file doesn't work the second time

As the file object reads the file, it uses a pointer to keep track of where it is. If you read part of the file, then go back to it later it will pick up where you left off. If you read the whole file, and go back to the same file object, it will be like reading an empty file because the pointer is at the end of the file and there is nothing left to read. You can use file.tell() to see where in the file the pointer is and file.seek to set the pointer. For example:

>>> file = open('myfile.txt')
>>> file.tell()
0
>>> file.readline()
'one\n'
>>> file.tell()
4L
>>> file.readline()
'2\n'
>>> file.tell()
6L
>>> file.seek(4)
>>> file.readline()
'2\n'

Also, you should know that file.readlines() reads the whole file and stores it as a list. That's useful to know because you can replace:

for line in file.readlines():
    #do stuff
file.seek(0)
for line in file.readlines():
    #do more stuff

with:

lines = file.readlines()
for each_line in lines:
    #do stuff
for each_line in lines:
    #do more stuff

You can also iterate over a file, one line at a time, without holding the whole file in memory (this can be very useful for very large files) by doing:

for line in file:
    #do stuff

How to read PDF files using Java?

PDFBox contains tools for text extraction.

iText has more low-level support for text manipulation, but you'd have to write a considerable amount of code to get text extraction.

iText in Action contains a good overview of the limitations of text extraction from PDF, regardless of the library used (Section 18.2: Extracting and editing text), and a convincing explanation why the library does not have text extraction support. In short, it's relatively easy to write a code that will handle simple cases, but it's basically impossible to extract text from PDF in general.

Console.WriteLine does not show up in Output window

Console outputs to the console window and Winforms applications do not show the console window. You should be able to use System.Diagnostics.Debug.WriteLine to send output to the output window in your IDE.

Edit: In regards to the problem, have you verified your mainForm_Load is actually being called? You could place a breakpoint at the beginning of mainForm_Load to see. If it is not being called, I suspect that mainForm_Load is not hooked up to the Load event.

Also, it is more efficient and generally better to override On{EventName} instead of subscribing to {EventName} from within derived classes (in your case overriding OnLoad instead of Load).

How to display the value of the bar on each bar with pyplot.barh()?

I needed the bar labels too, note that my y-axis is having a zoomed view using limits on y axis. The default calculations for putting the labels on top of the bar still works using height (use_global_coordinate=False in the example). But I wanted to show that the labels can be put in the bottom of the graph too in zoomed view using global coordinates in matplotlib 3.0.2. Hope it help someone.

def autolabel(rects,data):
"""
Attach a text label above each bar displaying its height
"""
c = 0
initial = 0.091
offset = 0.205
use_global_coordinate = True

if use_global_coordinate:
    for i in data:        
        ax.text(initial+offset*c, 0.05, str(i), horizontalalignment='center',
                verticalalignment='center', transform=ax.transAxes,fontsize=8)
        c=c+1
else:
    for rect,i in zip(rects,data):
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width()/2., height,str(i),ha='center', va='bottom')

Example output

UICollectionView Self Sizing Cells with Auto Layout

For anyone who tried everything without luck, this is the only thing that got it working for me. For the multiline labels inside cell, try adding this magic line:

label.preferredMaxLayoutWidth = 200

More info: here

Cheers!

Where can I find a NuGet package for upgrading to System.Web.Http v5.0.0.0?

You need the Microsoft.AspNet.WebApi.Core package.

You can see it in the .csproj file:

<Reference Include="System.Web.Http, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
  <SpecificVersion>False</SpecificVersion>
  <HintPath>..\packages\Microsoft.AspNet.WebApi.Core.5.0.0\lib\net45\System.Web.Http.dll</HintPath>
</Reference>

Static constant string (class member)

The class static variables can be declared in the header but must be defined in a .cpp file. This is because there can be only one instance of a static variable and the compiler can't decide in which generated object file to put it so you have to make the decision, instead.

To keep the definition of a static value with the declaration in C++11 a nested static structure can be used. In this case the static member is a structure and has to be defined in a .cpp file, but the values are in the header.

class A
{
private:
  static struct _Shapes {
     const std::string RECTANGLE {"rectangle"};
     const std::string CIRCLE {"circle"};
  } shape;
};

Instead of initializing individual members the whole static structure is initialized in .cpp:

A::_Shapes A::shape;

The values are accessed with

A::shape.RECTANGLE;

or -- since the members are private and are meant to be used only from A -- with

shape.RECTANGLE;

Note that this solution still suffers from the problem of the order of initialization of the static variables. When a static value is used to initialize another static variable, the first may not be initialized, yet.

// file.h
class File {
public:
  static struct _Extensions {
    const std::string h{ ".h" };
    const std::string hpp{ ".hpp" };
    const std::string c{ ".c" };
    const std::string cpp{ ".cpp" };
  } extension;
};

// file.cpp
File::_Extensions File::extension;

// module.cpp
static std::set<std::string> headers{ File::extension.h, File::extension.hpp };

In this case the static variable headers will contain either { "" } or { ".h", ".hpp" }, depending on the order of initialization created by the linker.

As mentioned by @abyss.7 you could also use constexpr if the value of the variable can be computed at compile time. But if you declare your strings with static constexpr const char* and your program uses std::string otherwise there will be an overhead because a new std::string object will be created every time you use such a constant:

class A {
public:
   static constexpr const char* STRING = "some value";
};
void foo(const std::string& bar);
int main() {
   foo(A::STRING); // a new std::string is constructed and destroyed.
}

Android ADB devices unauthorized

I removed the following files from the ~/.android folder:

  • adbkey
  • adbkey.pub

I disabled and enabled ADB within device and now it works...

How to _really_ programmatically change primary and accent color in Android Lollipop?

USE A TOOLBAR

You can set a custom toolbar item color dynamically by creating a custom toolbar class:

package view;

import android.app.Activity;
import android.content.Context;
import android.graphics.ColorFilter;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.support.v7.internal.view.menu.ActionMenuItemView;
import android.support.v7.widget.ActionMenuView;
import android.support.v7.widget.Toolbar;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

public class CustomToolbar extends Toolbar{

    public CustomToolbar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        // TODO Auto-generated constructor stub
    }

    public CustomToolbar(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }

    public CustomToolbar(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
        ctxt = context;
    }

    int itemColor;
    Context ctxt;

    @Override 
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        Log.d("LL", "onLayout");
        super.onLayout(changed, l, t, r, b);
        colorizeToolbar(this, itemColor, (Activity) ctxt);
    } 

    public void setItemColor(int color){
        itemColor = color;
        colorizeToolbar(this, itemColor, (Activity) ctxt);
    }



    /**
     * Use this method to colorize toolbar icons to the desired target color
     * @param toolbarView toolbar view being colored
     * @param toolbarIconsColor the target color of toolbar icons
     * @param activity reference to activity needed to register observers
     */
    public static void colorizeToolbar(Toolbar toolbarView, int toolbarIconsColor, Activity activity) {
        final PorterDuffColorFilter colorFilter
                = new PorterDuffColorFilter(toolbarIconsColor, PorterDuff.Mode.SRC_IN);

        for(int i = 0; i < toolbarView.getChildCount(); i++) {
            final View v = toolbarView.getChildAt(i);

            doColorizing(v, colorFilter, toolbarIconsColor);
        }

      //Step 3: Changing the color of title and subtitle.
        toolbarView.setTitleTextColor(toolbarIconsColor);
        toolbarView.setSubtitleTextColor(toolbarIconsColor);
    }

    public static void doColorizing(View v, final ColorFilter colorFilter, int toolbarIconsColor){
        if(v instanceof ImageButton) {
            ((ImageButton)v).getDrawable().setAlpha(255);
            ((ImageButton)v).getDrawable().setColorFilter(colorFilter);
        }

        if(v instanceof ImageView) {
            ((ImageView)v).getDrawable().setAlpha(255);
            ((ImageView)v).getDrawable().setColorFilter(colorFilter);
        }

        if(v instanceof AutoCompleteTextView) {
            ((AutoCompleteTextView)v).setTextColor(toolbarIconsColor);
        }

        if(v instanceof TextView) {
            ((TextView)v).setTextColor(toolbarIconsColor);
        }

        if(v instanceof EditText) {
            ((EditText)v).setTextColor(toolbarIconsColor);
        }

        if (v instanceof ViewGroup){
            for (int lli =0; lli< ((ViewGroup)v).getChildCount(); lli ++){
                doColorizing(((ViewGroup)v).getChildAt(lli), colorFilter, toolbarIconsColor);
            }
        }

        if(v instanceof ActionMenuView) {
            for(int j = 0; j < ((ActionMenuView)v).getChildCount(); j++) {

                //Step 2: Changing the color of any ActionMenuViews - icons that
                //are not back button, nor text, nor overflow menu icon.
                final View innerView = ((ActionMenuView)v).getChildAt(j);

                if(innerView instanceof ActionMenuItemView) {
                    int drawablesCount = ((ActionMenuItemView)innerView).getCompoundDrawables().length;
                    for(int k = 0; k < drawablesCount; k++) {
                        if(((ActionMenuItemView)innerView).getCompoundDrawables()[k] != null) {
                            final int finalK = k;

                            //Important to set the color filter in seperate thread, 
                            //by adding it to the message queue
                            //Won't work otherwise. 
                            //Works fine for my case but needs more testing

                            ((ActionMenuItemView) innerView).getCompoundDrawables()[finalK].setColorFilter(colorFilter);

//                              innerView.post(new Runnable() {
//                                  @Override
//                                  public void run() {
//                                      ((ActionMenuItemView) innerView).getCompoundDrawables()[finalK].setColorFilter(colorFilter);
//                                  }
//                              });
                        }
                    }
                }
            }
        }
    }



}

then refer to it in your layout file. Now you can set a custom color using

toolbar.setItemColor(Color.Red);

Sources:

I found the information to do this here: How to dynamicaly change Android Toolbar icons color

and then I edited it, improved upon it, and posted it here: GitHub:AndroidDynamicToolbarItemColor

How to pass a JSON array as a parameter in URL

& is a keyword for the next parameter like this ur?param1=1&param2=2

so effectively you send a second param named R". You should urlencode your string. Isn't POST an option?

How to get difference between two rows for a column field?

SQL Server 2012 and up support LAG / LEAD functions to access the previous or subsequent row. SQL Server 2005 does not support this (in SQL2005 you need a join or something else).

A SQL 2012 example on this data

/* Prepare */
select * into #tmp
from
(
    select 2  as rowint,      23 as Value
    union select 3,       45
    union select 17,      10
    union select 9,       0
) x


/* The SQL 2012 query */
select rowInt, Value, LEAD(value) over (order by rowInt) - Value  
from #tmp

LEAD(value) will return the value of the next row in respect to the given order in "over" clause.

Reusing a PreparedStatement multiple times

The loop in your code is only an over-simplified example, right?

It would be better to create the PreparedStatement only once, and re-use it over and over again in the loop.

In situations where that is not possible (because it complicated the program flow too much), it is still beneficial to use a PreparedStatement, even if you use it only once, because the server-side of the work (parsing the SQL and caching the execution plan), will still be reduced.

To address the situation that you want to re-use the Java-side PreparedStatement, some JDBC drivers (such as Oracle) have a caching feature: If you create a PreparedStatement for the same SQL on the same connection, it will give you the same (cached) instance.

About multi-threading: I do not think JDBC connections can be shared across multiple threads (i.e. used concurrently by multiple threads) anyway. Every thread should get his own connection from the pool, use it, and return it to the pool again.

Is it possible to use vh minus pixels in a CSS calc()?

It does work indeed. Issue was with my less compiler. It was compiled in to:

.container {
  min-height: calc(-51vh);
}

Fixed with the following code in less file:

.container {
  min-height: calc(~"100vh - 150px");
}

Thanks to this link: Less Aggressive Compilation with CSS3 calc

The request was rejected because no multipart boundary was found in springboot

When I use postman to send a file which is 5.6M to an external network, I faced the same issue. The same action is succeeded on my own computer and local testing environment.

After checking all the server configs and HTTP headers, I found that the reason is Postman may have some trouble simulating requests to external HTTP requests. Finally, I did the sendfile request on the chrome HTML page successfully. Just as a reference :)

Unable to launch the IIS Express Web server, Failed to register URL, Access is denied

My issue turned out to be that I had SSL Enabled on the project settings. I simply disabled this because I did not require SSL for running the project locally.

In Visual Studio 2015:

  • Select the project in the Solution Explorer.
  • In the Properties window set SSL Enabled to False.
  • I was able to run the project.

In my situation I was getting an error about port 443 in use because this was the port set on the SSL URL for the project.

C++ Remove new line from multiline string

 std::string some_str = SOME_VAL;
 if ( some_str.size() > 0 && some_str[some_str.length()-1] == '\n' ) 
  some_str.resize( some_str.length()-1 );

or (removes several newlines at the end)

some_str.resize( some_str.find_last_not_of(L"\n")+1 );

MySQL: ignore errors when importing?

Use the --force (-f) flag on your mysql import. Rather than stopping on the offending statement, MySQL will continue and just log the errors to the console.

For example:

mysql -u userName -p -f -D dbName < script.sql

Metadata file '.dll' could not be found

In VS 2019, under the project References check if there are any unresolved items by expanding Analyzers:

enter image description here

For me, there were two .dll files with wrong paths. Right click on each and select Remove:

enter image description here

Build the project, then build the solution. Done.

jQuery Datepicker onchange event issue

My soluthion:

var $dateInput = $('#dateInput');

$dateInput.datepicker({
    onSelect: function(f,d,i){
        if(d !== i.lastVal){
            $dateInput.trigger("change");
        }
    }
}).data('datepicker');

$dateInput.on("change", function () {
   //your code
});

How to convert DateTime to VarChar

-- This gives you the time as 0 in format 'yyyy-mm-dd 00:00:00.000'


SELECT CAST( CONVERT(VARCHAR, GETDATE(), 101) AS DATETIME) ; 

Is it possible to have placeholders in strings.xml for runtime values?

However, you should also read Elias Mårtenson's answer on Android plurals treatment of “zero”. There is a problem with the interpretation of certain values such as "zero".

How to convert 'binary string' to normal string in Python3?

If the answer from falsetru didn't work you could also try:

>>> b'a string'.decode('utf-8')
'a string'

How to resolve ORA-011033: ORACLE initialization or shutdown in progress

I faced the same problem. I restarted the oracle service for that DB instance and the error is gone.

Avoid trailing zeroes in printf()

Some of the highly voted solutions suggest the %g conversion specifier of printf. This is wrong because there are cases where %g will produce scientific notation. Other solutions use math to print the desired number of decimal digits.

I think the easiest solution is to use sprintf with the %f conversion specifier and to manually remove trailing zeros and possibly a decimal point from the result. Here's a C99 solution:

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

char*
format_double(double d) {
    int size = snprintf(NULL, 0, "%.3f", d);
    char *str = malloc(size + 1);
    snprintf(str, size + 1, "%.3f", d);

    for (int i = size - 1, end = size; i >= 0; i--) {
        if (str[i] == '0') {
            if (end == i + 1) {
                end = i;
            }
        }
        else if (str[i] == '.') {
            if (end == i + 1) {
                end = i;
            }
            str[end] = '\0';
            break;
        }
    }

    return str;
}

Note that the characters used for digits and the decimal separator depend on the current locale. The code above assumes a C or US English locale.

How to check edittext's text is email address or not?

   I Hope this code is beneficial for you

    public class Register extends Activity 
      {
       EditText FirstName, PhoneNo, EmailId,weight;
       Button Register;
       private static final Pattern EMAIL_PATTERN = Pattern
        .compile("^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");


   private static final Pattern USERFIRSTNAME_PATTERN = Pattern
        .compile("[a-zA-Z0-9]{1,250}");
   private static final Pattern PHONE_PATTERN = Pattern
        .compile("[a-zA-Z0-9]{1,250}");
       @Override
   public void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);


        Register=(Button) findViewById(R.id.register);

        FirstName=(EditText)findViewById(R.id.person_firstname);

            PhoneNo =(EditText)findViewById(R.id.phone_no);
            EmailId=(EditText)findViewById(R.id.email_id);
            weight=(EditText) findViewById(R.id.weight);

         Register.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                sFirstName= FirstName.getText().toString();
                 sPhoneNo= PhoneNo.getText().toString();
                sEmailId= EmailId.getText().toString();
                sweight= weight.getText().toString(); 

                if(sFirstName.equals("")||sPhoneNo.equals("")||sEmailId.equals("")||sweight.equals(""))
                {
                    if ((!CheckUsername(sFirstName))) 
                     {
                     Toast.makeText(Register.this, "FirstName can not be null",Toast.LENGTH_LONG).show();
                     }
                   else if ((!Checkphoneno(sPhoneNo)))
                       {
                    Toast.makeText(Register.this, "ENTER VALID mobile no ",Toast.LENGTH_LONG).show();
                       }
                    else if ((!CheckEmail(sEmailId)))
                       {
                      Toast.makeText(Register.this, "ENTER VALID EMAIL ID",Toast.LENGTH_LONG).show();
                       }
                    else if ((!Checkweight(sweight)))
                      {
                    Toast.makeText(Register.this, "ENTER Weight in kg",Toast.LENGTH_LONG).show();
                      }
               }

            }
                private boolean CheckEmail(String sEmailId) {

                    return EMAIL_PATTERN.matcher(sEmailId).matches();
                }



                private boolean CheckUsername(String sFirstName) {

                    return USERFIRSTNAME_PATTERN.matcher(sFirstName).matches();
                }
                private boolean Checkphoneno(String sPhoneNo) {

                    return PHONE_PATTERN.matcher(sPhoneNo).matches();
                }
                private boolean Checkweight(String sweight) {

                    return Weight_PATTERN.matcher(sweight).matches();
                }


        });

How to delete row in gridview using rowdeleting event?

See the following code and make some changes to get the answer for your question

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

    void CustomersGridView_RowDeleting
        (Object sender, GridViewDeleteEventArgs e)
    {
        TableCell cell = CustomersGridView.Rows[e.RowIndex].Cells[2];
        if (cell.Text == "Beaver")
        {
            e.Cancel = true;
            Message.Text = "You cannot delete customer Beaver.";
        }
        else
        {
            Message.Text = "";
        }
    }  

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>GridView RowDeleting Example</title>
</head>
<body>
    <form id="form1" runat="server">
    <h3>
        GridView RowDeleting Example
    </h3>
    <asp:Label ID="Message" ForeColor="Red" runat="server" />
    <br />
    <asp:GridView ID="CustomersGridView" runat="server" 
        DataSourceID="CustomersSqlDataSource" 
        AutoGenerateColumns="False"
        AutoGenerateDeleteButton="True" 
        OnRowDeleting="CustomersGridView_RowDeleting"
        DataKeyNames="CustomerID,AddressID">
        <Columns>
            <asp:BoundField DataField="FirstName" 
                HeaderText="FirstName" SortExpression="FirstName" />
            <asp:BoundField DataField="LastName" HeaderText="LastName" 
                SortExpression="LastName" />
            <asp:BoundField DataField="City" HeaderText="City" 
                SortExpression="City" />
            <asp:BoundField DataField="StateProvince" HeaderText="State" 
                SortExpression="StateProvince" />
        </Columns>
    </asp:GridView>
    <asp:SqlDataSource ID="CustomersSqlDataSource" runat="server"
        SelectCommand="SELECT SalesLT.CustomerAddress.CustomerID, 
            SalesLT.CustomerAddress.AddressID, 
            SalesLT.Customer.FirstName, 
            SalesLT.Customer.LastName, 
            SalesLT.Address.City, 
            SalesLT.Address.StateProvince 
            FROM SalesLT.Customer 
            INNER JOIN SalesLT.CustomerAddress 
            ON SalesLT.Customer.CustomerID = 
                SalesLT.CustomerAddress.CustomerID 
            INNER JOIN SalesLT.Address ON SalesLT.CustomerAddress.AddressID = 
                SalesLT.Address.AddressID"
        DeleteCommand="Delete from SalesLT.CustomerAddress where CustomerID = 
            @CustomerID and AddressID = @AddressID" 
        ConnectionString="<%$ ConnectionStrings:AdventureWorksLTConnectionString %>">
        <DeleteParameters>
            <asp:Parameter Name="AddressID" />
            <asp:Parameter Name="CustomerID" />
        </DeleteParameters>
    </asp:SqlDataSource>
    </form>
</body>
</html>

What is the difference between json.dumps and json.load?

json loads -> returns an object from a string representing a json object.

json dumps -> returns a string representing a json object from an object.

load and dump -> read/write from/to file instead of string

Detect the Internet connection is offline?

The HTML5 Application Cache API specifies navigator.onLine, which is currently available in the IE8 betas, WebKit (eg. Safari) nightlies, and is already supported in Firefox 3

What version of Python is on my Mac?

Take a look at the docs regarding Python on Mac.

The version at /System/Library/Frameworks/Python.framework is installed by Apple and is used by the system. It is version 3.3 in your case. You can access and use this Python interpreter, but you shouldn't try to remove it, and it may not be the one that comes up when you type "Python" in a terminal or click on an icon to launch it.

You must have installed another version of Python (2.7) on your own at some point, and now that is the one that is launched by default.

As other answers have pointed out, you can use the command which python on your terminal to find the path to this other installation.

Android offline documentation and sample codes

This thread is a little old, and I am brand new to this, but I think I found the preferred solution.

First, I assume that you are using Eclipse and the Android ADT plugin.

In Eclipse, choose Window/Android SDK Manager. In the display, expand the entry for the MOST RECENT PLATFORM, even if that is not the platform that your are developing for. As of Jan 2012, it is "Android 4.0.3 (API 15)". When expanded, the first entry is "Documentation for Android SDK" Click the checkbox next to it, and then click the "Install" button.

When done, you should have a new directory in your "android-sdks" called "doc". Look for "offline.html" in there. Since this is packaged with the most recent version, it will document the most recent platform, but it should also show the APIs for previous versions.

How can I reverse a NSArray in Objective-C?

Here is a nice macro that will work for either NSMutableArray OR NSArray:

#define reverseArray(__theArray) {\
    if ([__theArray isKindOfClass:[NSMutableArray class]]) {\
        if ([(NSMutableArray *)__theArray count] > 1) {\
            NSUInteger i = 0;\
            NSUInteger j = [(NSMutableArray *)__theArray count]-1;\
            while (i < j) {\
                [(NSMutableArray *)__theArray exchangeObjectAtIndex:i\
                                                withObjectAtIndex:j];\
                i++;\
                j--;\
            }\
        }\
    } else if ([__theArray isKindOfClass:[NSArray class]]) {\
        __theArray = [[NSArray alloc] initWithArray:[[(NSArray *)__theArray reverseObjectEnumerator] allObjects]];\
    }\
}

To use just call: reverseArray(myArray);

Return value using String result=Command.ExecuteScalar() error occurs when result returns null

To work with NpgsqlCommand or the standard sqlCommand use:

int result = int.Parse(cmd.ExecuteScalar().ToString());

How can I hide an HTML table row <tr> so that it takes up no space?

var result_style = document.getElementById('result_tr').style;
result_style.display = '';

is working perfectly for me..

Google Chrome form autofill and its yellow background

The following CSS removes the yellow background color and replaces it with a background color of your choosing. It doesn't disable auto-fill and it requires no jQuery or Javascript hacks.

input:-webkit-autofill {
    -webkit-box-shadow:0 0 0 50px white inset; /* Change the color to your own background color */
    -webkit-text-fill-color: #333;
}
input:-webkit-autofill:focus {
    -webkit-box-shadow: /*your box-shadow*/,0 0 0 50px white inset;
    -webkit-text-fill-color: #333;
}

Solution copied from: Override browser form-filling and input highlighting with HTML/CSS

Setting DIV width and height in JavaScript

The onclick attribute of a button takes a string of JavaScript, not an href like you provided. Just remove the "javascript:" part.

Does bootstrap have builtin padding and margin classes?

I would like to give an example which I tried by understanding above documentation and works correctly. If you wish to apply 25% padding on left and right sides medium screen size then please use px-md-1. It works as desired and can similarly follow for other screen sizes. :)

How to use Google App Engine with my own naked domain (not subdomain)?

You can redirect forward or mask your domain name in godaddy but I don't know about other hosting sites.Have a look on this link

How to display a Windows Form in full screen on top of the taskbar?

A tested and simple solution

I've been looking for an answer for this question in SO and some other sites, but one gave an answer was very complex to me and some others answers simply doesn't work correctly, so after a lot code testing I solved this puzzle.

Note: I'm using Windows 8 and my taskbar isn't on auto-hide mode.

I discovered that setting the WindowState to Normal before performing any modifications will stop the error with the not covered taskbar.

The code

I created this class that have two methods, the first enters in the "full screen mode" and the second leaves the "full screen mode". So you just need to create an object of this class and pass the Form you want to set full screen as an argument to the EnterFullScreenMode method or to the LeaveFullScreenMode method:

class FullScreen
{
    public void EnterFullScreenMode(Form targetForm)
    {
        targetForm.WindowState = FormWindowState.Normal;
        targetForm.FormBorderStyle = FormBorderStyle.None;
        targetForm.WindowState = FormWindowState.Maximized;
    }

    public void LeaveFullScreenMode(Form targetForm)
    {
        targetForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
        targetForm.WindowState = FormWindowState.Normal;
    }
}

Usage example

    private void fullScreenToolStripMenuItem_Click(object sender, EventArgs e)
    {
        FullScreen fullScreen = new FullScreen();

        if (fullScreenMode == FullScreenMode.No)  // FullScreenMode is an enum
        {
            fullScreen.EnterFullScreenMode(this);
            fullScreenMode = FullScreenMode.Yes;
        }
        else
        {
            fullScreen.LeaveFullScreenMode(this);
            fullScreenMode = FullScreenMode.No;
        }
    }

I have placed this same answer on another question that I'm not sure if is a duplicate or not of this one. (Link to the other question: How do I make a WinForms app go Full Screen)

How to implement "select all" check box in HTML?

As I cannot comment, here as answer: I would write Can Berk Güder's solution in a more general way, so you may reuse the function for other checkboxes

<script language="JavaScript">
  function toggleCheckboxes(source, cbName) {
    checkboxes = document.getElementsByName(cbName);
    for (var i = 0, n = checkboxes.length; i < n; i++) {
      checkboxes[i].checked = source.checked;
    }
  }
</script>
<input type="checkbox" onClick="toggleCheckboxes(this,\'foo\')" /> Toggle All<br/>

<input type="checkbox" name="foo" value="bar1"> Bar 1<br/>
<input type="checkbox" name="foo" value="bar2"> Bar 2<br/>
<input type="checkbox" name="foo" value="bar3"> Bar 3<br/>
<input type="checkbox" name="foo" value="bar4"> Bar 4<br/>
<input type="checkbox" name="foo" value="bar5"> Bar 5<br/>

Getting "cannot find Symbol" in Java project in Intellij

I was having the same problem except that I was importing the classes for which dependencies were not resolving somehow. I refreshed maven projects, Rebuild Project. It still did not resolve. Looks like IntelliJ was caching something incorrectly. I restarted IntelliJ and that resolved the dependencies. I guess it cleared the cache somehow.

How to read line by line of a text area HTML tag

A simple regex should be efficent to check your textarea:

/\s*\d+\s*\n/g.test(text) ? "OK" : "KO"

Is it ok to use `any?` to check if an array is not empty?

Avoid any? for large arrays.

  • any? is O(n)
  • empty? is O(1)

any? does not check the length but actually scans the whole array for truthy elements.

static VALUE
rb_ary_any_p(VALUE ary)
{
  long i, len = RARRAY_LEN(ary);
  const VALUE *ptr = RARRAY_CONST_PTR(ary);

  if (!len) return Qfalse;
  if (!rb_block_given_p()) {
    for (i = 0; i < len; ++i) if (RTEST(ptr[i])) return Qtrue;
  }
  else {
    for (i = 0; i < RARRAY_LEN(ary); ++i) {
        if (RTEST(rb_yield(RARRAY_AREF(ary, i)))) return Qtrue;
    }
  }
  return Qfalse;
}

empty? on the other hand checks the length of the array only.

static VALUE
rb_ary_empty_p(VALUE ary)
{
  if (RARRAY_LEN(ary) == 0)
    return Qtrue;
  return Qfalse;
}

The difference is relevant if you have "sparse" arrays that start with lots of nil values, like for example an array that was just created.

What's the right way to decode a string that has special HTML entities in it?

This is so good answer. You can use this with angular like this:

 moduleDefinitions.filter('sanitize', ['$sce', function($sce) {
    return function(htmlCode) {
        var txt = document.createElement("textarea");
        txt.innerHTML = htmlCode;
        return $sce.trustAsHtml(txt.value);
    }
}]);

How to resolve "Input string was not in a correct format." error?

The problem is with line

imageWidth = 1 * Convert.ToInt32(Label1.Text);

Label1.Text may or may not be int. Check.

Use Int32.TryParse(value, out number) instead. That will solve your problem.

int imageWidth;
if(Int32.TryParse(Label1.Text, out imageWidth))
{
    Image1.Width= imageWidth;
}

How to read data from a zip file without having to unzip the entire file

DotNetZip is your friend here.

As easy as:

using (ZipFile zip = ZipFile.Read(ExistingZipFile))
{
  ZipEntry e = zip["MyReport.doc"];
  e.Extract(OutputStream);
}

(you can also extract to a file or other destinations).

Reading the zip file's table of contents is as easy as:

using (ZipFile zip = ZipFile.Read(ExistingZipFile))
{
  foreach (ZipEntry e in zip)
  {
    if (header)
    {
      System.Console.WriteLine("Zipfile: {0}", zip.Name);
      if ((zip.Comment != null) && (zip.Comment != "")) 
        System.Console.WriteLine("Comment: {0}", zip.Comment);
      System.Console.WriteLine("\n{1,-22} {2,8}  {3,5}   {4,8}  {5,3} {0}",
                               "Filename", "Modified", "Size", "Ratio", "Packed", "pw?");
      System.Console.WriteLine(new System.String('-', 72));
      header = false;
    }
    System.Console.WriteLine("{1,-22} {2,8} {3,5:F0}%   {4,8}  {5,3} {0}",
                             e.FileName,
                             e.LastModified.ToString("yyyy-MM-dd HH:mm:ss"),
                             e.UncompressedSize,
                             e.CompressionRatio,
                             e.CompressedSize,
                             (e.UsesEncryption) ? "Y" : "N");

  }
}

Edited To Note: DotNetZip used to live at Codeplex. Codeplex has been shut down. The old archive is still available at Codeplex. It looks like the code has migrated to Github:


Convert XmlDocument to String

As an extension method:

public static class Extensions
{
    public static string AsString(this XmlDocument xmlDoc)
    {
        using (StringWriter sw = new StringWriter())
        {
            using (XmlTextWriter tx = new XmlTextWriter(sw))
            {
                xmlDoc.WriteTo(tx);
                string strXmlText = sw.ToString();
                return strXmlText;
            }
        }
    }
}

Now to use simply:

yourXmlDoc.AsString()

Targeting .NET Framework 4.5 via Visual Studio 2010

FYI, if you want to create an Installer package in VS2010, unfortunately it only targets .NET 4. To work around this, you have to add NET 4.5 as a launch condition.

Add the following in to the Launch Conditions of the installer (Right click, View, Launch Conditions).

In "Search Target Machine", right click and select "Add Registry Search".

Property: REGISTRYVALUE1
RegKey: Software\Microsoft\NET Framework Setup\NDP\v4\Full
Root: vsdrrHKLM
Value: Release

Add new "Launch Condition":

Condition: REGISTRYVALUE1>="#378389"
InstallUrl: http://www.microsoft.com/en-gb/download/details.aspx?id=30653
Message: Setup requires .NET Framework 4.5 to be installed.

Where:

378389 = .NET Framework 4.5

378675 = .NET Framework 4.5.1 installed with Windows 8.1

378758 = .NET Framework 4.5.1 installed on Windows 8, Windows 7 SP1, or Windows Vista SP2

379893 = .NET Framework 4.5.2

Launch condition reference: http://msdn.microsoft.com/en-us/library/vstudio/xxyh2e6a(v=vs.100).aspx

What are NDF Files?

From Files and Filegroups Architecture

Secondary data files

Secondary data files make up all the data files, other than the primary data file. Some databases may not have any secondary data files, while others have several secondary data files. The recommended file name extension for secondary data files is .ndf.

Also from file extension NDF - Microsoft SQL Server secondary data file

See Understanding Files and Filegroups

Secondary data files are optional, are user-defined, and store user data. Secondary files can be used to spread data across multiple disks by putting each file on a different disk drive. Additionally, if a database exceeds the maximum size for a single Windows file, you can use secondary data files so the database can continue to grow.

The recommended file name extension for secondary data files is .ndf.

/

For example, three files, Data1.ndf, Data2.ndf, and Data3.ndf, can be created on three disk drives, respectively, and assigned to the filegroup fgroup1. A table can then be created specifically on the filegroup fgroup1. Queries for data from the table will be spread across the three disks; this will improve performance. The same performance improvement can be accomplished by using a single file created on a RAID (redundant array of independent disks) stripe set. However, files and filegroups let you easily add new files to new disks.

Routing for custom ASP.NET MVC 404 Error page

Source

NotFoundMVC - Provides a user-friendly 404 page whenever a controller, action or route is not found in your ASP.NET MVC3 application. A view called NotFound is rendered instead of the default ASP.NET error page.

You can add this plugin via nuget using: Install-Package NotFoundMvc

NotFoundMvc automatically installs itself during web application start-up. It handles all the different ways a 404 HttpException is usually thrown by ASP.NET MVC. This includes a missing controller, action and route.

Step by Step Installation Guide :

1 - Right click on your Project and Select Manage Nuget Packages...

2 - Search for NotFoundMvc and install it. enter image description here

3 - Once the installation has be completed, two files will be added to your project. As shown in the screenshots below.

enter image description here

4 - Open the newly added NotFound.cshtml present at Views/Shared and modify it at your will. Now run the application and type in an incorrect url, and you will be greeted with a User friendly 404 page.

enter image description here

No more, will users get errors message like Server Error in '/' Application. The resource cannot be found.

Hope this helps :)

P.S : Kudos to Andrew Davey for making such an awesome plugin.

HashMap to return default value for non-found keys?

Use:

myHashMap.getOrDefault(key, defaultValue);

socket.error: [Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions

Just run on ports above 1024 , anything below is privileged, its the same deal with Linux, i use 5000 for example on wins without any UAC priv escalation.

Whether a variable is undefined

function my_url (base, opt)
{
    var retval = ["" + base];
    retval.push( opt.page_name ? "&page_name=" + opt.page_name : "");
    retval.push( opt.table_name ? "&table_name=" + opt.table_name : "");
    retval.push( opt.optionResult ? "&optionResult=" + opt.optionResult : "");
    return retval.join("");
}

my_url("?z=z",  { page_name : "pageX" /* no table_name and optionResult */ } );

/* Returns:
     ?z=z&page_name=pageX
*/

This avoids using typeof whatever === "undefined". (Also, there isn't any string concatenation.)

Scala check if element is present in a list

Even easier!

strings contains myString

How to rollback everything to previous commit

If you have pushed the commits upstream...

Select the commit you would like to roll back to and reverse the changes by clicking Reverse File, Reverse Hunk or Reverse Selected Lines. Do this for all the commits after the commit you would like to roll back to also.

reverse stuff reverse commit

If you have not pushed the commits upstream...

Right click on the commit and click on Reset current branch to this commit.

reset branch to commit

Adding a right click menu to an item

Having just messed around with this, it's useful to kjnow that the e.X / e.Y points are relative to the control, so if (as I was) you are adding a context menu to a listview or something similar, you will want to adjust it with the form's origin. In the example below I've added 20 to the x/y so that the menu appears slightly to the right and under the cursor.

cmDelete.Show(this, new Point(e.X + ((Control)sender).Left+20, e.Y + ((Control)sender).Top+20));

Swift: Sort array of objects alphabetically

Sorted array Swift 4.2

arrayOfRaces = arrayOfItems.sorted(by: { ($0["raceName"] as! String) < ($1["raceName"] as! String) })

Create folder in Android

Add this permission in Manifest,
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

File folder = new File(Environment.getExternalStorageDirectory() + 
                             File.separator + "TollCulator");
boolean success = true;
if (!folder.exists()) {
    success = folder.mkdirs();
}
if (success) {
    // Do something on success
} else {
    // Do something else on failure 
}

when u run the application go too DDMS->File Explorer->mnt folder->sdcard folder->toll-creation folder

How to do a JUnit assert on a message in a logger

Note that in Log4J 2.x, the public interface org.apache.logging.log4j.Logger doesn't include the setAppender() and removeAppender() methods.

But if you're not doing anything too fancy, you should be able to cast it to the implementation class org.apache.logging.log4j.core.Logger, which does expose those methods.

Here's an example with Mockito and AssertJ:

// Import the implementation class rather than the API interface
import org.apache.logging.log4j.core.Logger;
// Cast logger to implementation class to get access to setAppender/removeAppender
Logger log = (Logger) LogManager.getLogger(MyClassUnderTest.class);

// Set up the mock appender, stubbing some methods Log4J needs internally
Appender appender = mock(Appender.class);
when(appender.getName()).thenReturn("Mock Appender");
when(appender.isStarted()).thenReturn(true);

log.addAppender(appender);
try {
    new MyClassUnderTest().doSomethingThatShouldLogAnError();
} finally {
    log.removeAppender(appender);
}

// Verify that we got an error with the expected message
ArgumentCaptor<LogEvent> logEventCaptor = ArgumentCaptor.forClass(LogEvent.class);
verify(appender).append(logEventCaptor.capture());
LogEvent logEvent = logEventCaptor.getValue();
assertThat(logEvent.getLevel()).isEqualTo(Level.ERROR);
assertThat(logEvent.getMessage().getFormattedMessage()).contains(expectedErrorMessage);

Get Date in YYYYMMDD format in windows batch file

If, after reading the other questions and viewing the links mentioned in the comment sections, you still can't figure it out, read on.

First of all, where you're going wrong is the offset.

It should look more like this...

set mydate=%date:~10,4%%date:~6,2%/%date:~4,2%
echo %mydate%

If the date was Tue 12/02/2013 then it would display it as 2013/02/12.

To remove the slashes, the code would look more like

set mydate=%date:~10,4%%date:~7,2%%date:~4,2%
echo %mydate%

which would output 20130212

And a hint for doing it in the future, if mydate equals something like %date:~10,4%%date:~7,2% or the like, you probably forgot a tilde (~).

Plot data in descending order as appears in data frame

You want reorder(). Here is an example with dummy data

set.seed(42)
df <- data.frame(Category = sample(LETTERS), Count = rpois(26, 6))

require("ggplot2")

p1 <- ggplot(df, aes(x = Category, y = Count)) +
         geom_bar(stat = "identity")

p2 <- ggplot(df, aes(x = reorder(Category, -Count), y = Count)) +
         geom_bar(stat = "identity")

require("gridExtra")
grid.arrange(arrangeGrob(p1, p2))

Giving:

enter image description here

Use reorder(Category, Count) to have Category ordered from low-high.

How to read a .xlsx file using the pandas Library in iPython?

Assign spreadsheet filename to file

Load spreadsheet

Print the sheet names

Load a sheet into a DataFrame by name: df1

file = 'example.xlsx'
xl = pd.ExcelFile(file)
print(xl.sheet_names)
df1 = xl.parse('Sheet1')

Redirect in Spring MVC

Try this

HttpServletResponse response;       
response.sendRedirect(".../webpage.xhtml");

Laravel 5 Carbon format datetime

Declare in model:

class ModelName extends Model
{      

 protected $casts = [
    'created_at' => 'datetime:d/m/Y', // Change your format
    'updated_at' => 'datetime:d/m/Y',
];

Make just one slide different size in Powerpoint

true, this option is not available in any version of MS ppt.Now the solution is that You put your different sized slide in other file and put a hyperlink in first file.

filemtime "warning stat failed for"

in my case it was not related to the path or filename. If filemtime(), fileatime() or filectime() don't work, try stat().

$filedate = date_create(date("Y-m-d", filectime($file)));

becomes

$stat = stat($directory.$file);
$filedate = date_create(date("Y-m-d", $stat['ctime']));

that worked for me.

Complete snippet for deleting files by number of days:

$directory = $_SERVER['DOCUMENT_ROOT'].'/directory/';
$files = array_slice(scandir($directory), 2);
foreach($files as $file)
{
    $extension      = substr($file, -3, 3); 
    if ($extension == 'jpg') // in case you only want specific files deleted
    {
        $stat = stat($directory.$file);
        $filedate = date_create(date("Y-m-d", $stat['ctime']));
        $today = date_create(date("Y-m-d"));
        $days = date_diff($filedate, $today, true);
        if ($days->days > 1) 
        { 
            unlink($directory.$file);
        }
    } 
}

Entity Framework and Connection Pooling

According to Daniel Simmons:

Create a new ObjectContext instance in a Using statement for each service method so that it is disposed of before the method returns. This step is critical for scalability of your service. It makes sure that database connections are not kept open across service calls and that temporary state used by a particular operation is garbage collected when that operation is over. The Entity Framework automatically caches metadata and other information it needs in the app domain, and ADO.NET pools database connections, so re-creating the context each time is a quick operation.

This is from his comprehensive article here:

http://msdn.microsoft.com/en-us/magazine/ee335715.aspx

I believe this advice extends to HTTP requests, so would be valid for ASP.NET. A stateful, fat-client application such as a WPF application might be the only case for a "shared" context.

Django return redirect() with parameters

urls.py:

#...    
url(r'element/update/(?P<pk>\d+)/$', 'element.views.element_update', name='element_update'),

views.py:

from django.shortcuts import redirect
from .models import Element


def element_info(request):
    # ...
    element = Element.object.get(pk=1)
    return redirect('element_update', pk=element.id)

def element_update(request, pk)
    # ...

How to solve could not create the virtual machine error of Java Virtual Machine Launcher?

I was also facing this issue when we upgraded from java 8 to java 10. I solved by removing -Djava.endorsed.dirs="C:\Program Files\Apache Software Foundation\Tomcat 8.5\endorsed" from the argument.

Get Hard disk serial Number

There is a simple way for @Sprunth's answer.

private void GetAllDiskDrives()
    {
        var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");

        foreach (ManagementObject wmi_HD in searcher.Get())
        {
            HardDrive hd = new HardDrive();
            hd.Model = wmi_HD["Model"].ToString();
            hd.InterfaceType = wmi_HD["InterfaceType"].ToString();
            hd.Caption = wmi_HD["Caption"].ToString();

            hd.SerialNo =wmi_HD.GetPropertyValue("SerialNumber").ToString();//get the serailNumber of diskdrive

            hdCollection.Add(hd);
        }

 }


public class HardDrive
{
    public string Model { get; set; }
    public string InterfaceType { get; set; }
    public string Caption { get; set; }
    public string SerialNo { get; set; }
}

How to make responsive table

For make responsive table you can make 100% of each ‘td’ and insert related heading in the ‘td’ on the mobile(less the ’768px’ width).

See More:
http://wonderdesigners.com/?p=227

Why can't decimal numbers be represented exactly in binary?

(Note: I'll append 'b' to indicate binary numbers here. All other numbers are given in decimal)

One way to think about things is in terms of something like scientific notation. We're used to seeing numbers expressed in scientific notation like, 6.022141 * 10^23. Floating point numbers are stored internally using a similar format - mantissa and exponent, but using powers of two instead of ten.

Your 61.0 could be rewritten as 1.90625 * 2^5, or 1.11101b * 2^101b with the mantissa and exponents. To multiply that by ten and (move the decimal point), we can do:

(1.90625 * 2^5) * (1.25 * 2^3) = (2.3828125 * 2^8) = (1.19140625 * 2^9)

or in with the mantissa and exponents in binary:

(1.11101b * 2^101b) * (1.01b * 2^11b) = (10.0110001b * 2^1000b) = (1.00110001b * 2^1001b)

Note what we did there to multiply the numbers. We multiplied the mantissas and added the exponents. Then, since the mantissa ended greater than two, we normalized the result by bumping the exponent. It's just like when we adjust the exponent after doing an operation on numbers in decimal scientific notation. In each case, the values that we worked with had a finite representation in binary, and so the values output by the basic multiplication and addition operations also produced values with a finite representation.

Now, consider how we'd divide 61 by 10. We'd start by dividing the mantissas, 1.90625 and 1.25. In decimal, this gives 1.525, a nice short number. But what is this if we convert it to binary? We'll do it the usual way -- subtracting out the largest power of two whenever possible, just like converting integer decimals to binary, but we'll use negative powers of two:

1.525         - 1*2^0   --> 1
0.525         - 1*2^-1  --> 1
0.025         - 0*2^-2  --> 0
0.025         - 0*2^-3  --> 0
0.025         - 0*2^-4  --> 0
0.025         - 0*2^-5  --> 0
0.025         - 1*2^-6  --> 1
0.009375      - 1*2^-7  --> 1
0.0015625     - 0*2^-8  --> 0
0.0015625     - 0*2^-9  --> 0
0.0015625     - 1*2^-10 --> 1
0.0005859375  - 1*2^-11 --> 1
0.00009765625...

Uh oh. Now we're in trouble. It turns out that 1.90625 / 1.25 = 1.525, is a repeating fraction when expressed in binary: 1.11101b / 1.01b = 1.10000110011...b Our machines only have so many bits to hold that mantissa and so they'll just round the fraction and assume zeroes beyond a certain point. The error you see when you divide 61 by 10 is the difference between:

1.100001100110011001100110011001100110011...b * 2^10b
and, say:
1.100001100110011001100110b * 2^10b

It's this rounding of the mantissa that leads to the loss of precision that we associate with floating point values. Even when the mantissa can be expressed exactly (e.g., when just adding two numbers), we can still get numeric loss if the mantissa needs too many digits to fit after normalizing the exponent.

We actually do this sort of thing all the time when we round decimal numbers to a manageable size and just give the first few digits of it. Because we express the result in decimal it feels natural. But if we rounded a decimal and then converted it to a different base, it'd look just as ugly as the decimals we get due to floating point rounding.

Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"

If you would like to open a servlet with javascript without using 'form' and 'submit' button, here is the following code:

var button = document.getElementById("<<button-id>>");
button.addEventListener("click", function() {
  window.location.href= "<<full-servlet-path>>" (eg. http://localhost:8086/xyz/servlet)
});

Key:

1) button-id : The 'id' tag you give to your button in your html/jsp file.

2) full-servlet-path: The path that shows in the browser when you run the servlet alone

Summing elements in a list

Python iterable can be summed like so - [sum(range(10)[1:])] . This sums all elements from the list except the first element.

>>> atuple = (1,2,3,4,5)
>>> sum(atuple)
15
>>> alist = [1,2,3,4,5]
>>> sum(alist)
15

how to find all indexes and their columns for tables, views and synonyms in oracle

Your query should work for synonyms as well as the tables. However, you seem to expect indexes on views where there are not. Maybe is it materialized views ?

How do I use tools:overrideLibrary in a build.gradle file?

As soulution for all libraries we can match sdk version of them so no unexpected event may happen

subprojects { 
afterEvaluate {project -> 
    if (project.hasProperty("android")) { 
        android { 
            compileSdkVersion 28 
            buildToolsVersion '28.0.3'
            defaultConfig {
                //It's kinda tricking android studio but anyway it works
                minSdkVersion 17
            }
        } 
    } 
    if (project.hasProperty("dependencies")) {
        dependencies {
            implementation 'com.android.support:support-core-utils:28.0.0'
            implementation 'com.android.support:appcompat-v7:28.0.0'
            implementation 'com.google.android.gms:play-services-base:16.1.0'
        }
    }
} 
}

Remove libraries that you do not use in your project (gms) and make sure that sdk version matches your app level gradle data

How to get the indexpath.row when an element is activated?

Since the sender of the event handler is the button itself, I'd use the button's tag property to store the index, initialized in cellForRowAtIndexPath.

But with a little more work I'd do in a completely different way. If you are using a custom cell, this is how I would approach the problem:

  • add an 'indexPath` property to the custom table cell
  • initialize it in cellForRowAtIndexPath
  • move the tap handler from the view controller to the cell implementation
  • use the delegation pattern to notify the view controller about the tap event, passing the index path

Android : Fill Spinner From Java Code Programmatically

Here is an example to fully programmatically:

  • init a Spinner.
  • fill it with data via a String List.
  • resize the Spinner and add it to my View.
  • format the Spinner font (font size, colour, padding).
  • clear the Spinner.
  • add new values to the Spinner.
  • redraw the Spinner.

I am using the following class vars:

Spinner varSpinner;
List<String> varSpinnerData;

float varScaleX;
float varScaleY;    

A - Init and render the Spinner (varRoot is a pointer to my main Activity):

public void renderSpinner() {


    List<String> myArraySpinner = new ArrayList<String>();

    myArraySpinner.add("red");
    myArraySpinner.add("green");
    myArraySpinner.add("blue");     

    varSpinnerData = myArraySpinner;

    Spinner mySpinner = new Spinner(varRoot);               

    varSpinner = mySpinner;

    ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(varRoot, android.R.layout.simple_spinner_item, myArraySpinner);
    spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down vieww
    mySpinner.setAdapter(spinnerArrayAdapter);

B - Resize and Add the Spinner to my View:

    FrameLayout.LayoutParams myParamsLayout = new FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.MATCH_PARENT, 
            FrameLayout.LayoutParams.WRAP_CONTENT);
    myParamsLayout.gravity = Gravity.NO_GRAVITY;             

    myParamsLayout.leftMargin = (int) (100 * varScaleX);
    myParamsLayout.topMargin = (int) (350 * varScaleY);             
    myParamsLayout.width = (int) (300 * varScaleX);;
    myParamsLayout.height = (int) (60 * varScaleY);;


    varLayoutECommerce_Dialogue.addView(mySpinner, myParamsLayout);

C - Make the Click handler and use this to set the font.

    mySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int myPosition, long myID) {

            Log.i("renderSpinner -> ", "onItemSelected: " + myPosition + "/" + myID);

            ((TextView) parentView.getChildAt(0)).setTextColor(Color.GREEN);
            ((TextView) parentView.getChildAt(0)).setTextSize(TypedValue.COMPLEX_UNIT_PX, (int) (varScaleY * 22.0f) );
            ((TextView) parentView.getChildAt(0)).setPadding(1,1,1,1);


        }

        @Override
        public void onNothingSelected(AdapterView<?> parentView) {
            // your code here
        }

    });

}   

D - Update the Spinner with new data:

private void updateInitSpinners(){

     String mySelected = varSpinner.getSelectedItem().toString();
     Log.i("TPRenderECommerce_Dialogue -> ", "updateInitSpinners -> mySelected: " + mySelected);


     varSpinnerData.clear();

     varSpinnerData.add("Hello World");
     varSpinnerData.add("Hello World 2");

     ((BaseAdapter) varSpinner.getAdapter()).notifyDataSetChanged();
     varSpinner.invalidate();
     varSpinner.setSelection(1);

}

}

What I have not been able to solve in the updateInitSpinners, is to do varSpinner.setSelection(0); and have the custom font settings activated automatically.

UPDATE:

This "ugly" solution solves the varSpinner.setSelection(0); issue, but I am not very happy with it:

private void updateInitSpinners(){

    String mySelected = varSpinner.getSelectedItem().toString();
    Log.i("TPRenderECommerce_Dialogue -> ", "updateInitSpinners -> mySelected: " + mySelected);


    varSpinnerData.clear();

    ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(varRoot, android.R.layout.simple_spinner_item, varSpinnerData);
    spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
    varSpinner.setAdapter(spinnerArrayAdapter);  


    varSpinnerData.add("Hello World");
    varSpinnerData.add("Hello World 2");

    ((BaseAdapter) varSpinner.getAdapter()).notifyDataSetChanged();
    varSpinner.invalidate();
    varSpinner.setSelection(0);

}

}

Hope this helps......

Having both a Created and Last Updated timestamp columns in MySQL 4.0

For mysql 5.7.21 I use the following and works fine:

CREATE TABLE Posts ( modified_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP )

Get Number of Rows returned by ResultSet in Java

First, you should create Statement which can be move cursor by command:

Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

Then retrieve the ResultSet as below:

ResultSet rs = stmt.executeQuery(...);

Move cursor to the latest row and get it:

if (rs.last()) {
    int rows = rs.getRow();
    // Move to beginning
    rs.beforeFirst();
    ...
}

Then rows variable will contains number of rows returned by sql

What is the iBeacon Bluetooth Profile

Just to reconcile the difference between sandeepmistry's answer and davidgyoung's answer:

02 01 1a 1a ff 4C 00

Is part of the advertising data format specification [1]

  02 # length of following AD structure
  01 # <<Flags>> AD Structure [2]
  1a # read as b00011010. 
     # In this case, LE General Discoverable,
     # and simultaneous BR/EDR but this may vary by device!

  1a # length of following AD structure
  FF # Manufacturer specific data [3]
4C00 # Apple Inc [4]
0215 # ?? some 2-byte header

Missing from the AD is a Service [5] definition. I think the iBeacon protocol itself has no relationship to the GATT and standard service discovery. If you download RedBearLab's iBeacon program, you'll see that they happen to use the GATT for configuring the advertisement parameters, but this seems to be specific to their implementation, and not part of the spec. The AirLocate program doesn't seem to use the GATT for configuration, for instance, according to LightBlue and or other similar programs I tried.

References:

  1. Core Bluetooth Spec v4, Vol 3, Part C, 11
  2. Vol 3, Part C, 18.1
  3. Vol 3, Part C, 18.11
  4. https://www.bluetooth.org/en-us/specification/assigned-numbers/company-identifiers
  5. Vol 3, Part C, 18.2

Why doesn't java.io.File have a close method?

Say suppose, you have

File f  = new File("SomeFile");
f.length();

You need not close the Files, because its just the representation of a path.

You should always consider to close only reader/writers and in fact streams.

AngularJS accessing DOM elements inside directive template

I don't think there is a more "angular way" to select an element. See, for instance, the way they are achieving this goal in the last example of this old documentation page:

{
     template: '<div>' +
    '<div class="title">{{title}}</div>' +
    '<div class="body" ng-transclude></div>' +
    '</div>',

    link: function(scope, element, attrs) {
        // Title element
        var title = angular.element(element.children()[0]),
        // ...
    }
}

set serveroutput on in oracle procedure

Procedure successful but any outpout

Error line1: Unexpected identifier

Here is the code:

SET SERVEROUTPUT ON 

DECLARE

    -- Curseurs 
    CURSOR c1 IS        
    SELECT RWID FROM J_EVT
     WHERE DT_SYST < TO_DATE(TO_CHAR(SYSDATE,'DD/MM') || '/' || TO_CHAR(TO_NUMBER(TO_CHAR(SYSDATE, 'YYYY')) - 3));

    -- Collections 

    TYPE tc1 IS TABLE OF c1%RWTYPE;

    -- Variables de type record
    rtc1                        tc1;    

    vCpt                        NUMBER:=0;

BEGIN

    OPEN c1;
    LOOP
        FETCH c1 BULK COLLECT INTO rtc1 LIMIT 5000;

        FORALL i IN 1..rtc1.COUNT 
        DELETE FROM J_EVT
          WHERE RWID = rtc1(i).RWID;
        COMMIT;

        -- Nombres lus : 5025651
        FOR i IN 1..rtc1.COUNT LOOP               
            vCpt := vCpt + SQL%BULK_RWCOUNT(i);
        END LOOP;            

        EXIT WHEN c1%NOTFOUND;   
    END LOOP;
    CLOSE c1;
    COMMIT;

    DBMS_OUTPUT.PUT_LINE ('Nombres supprimes : ' || TO_CHAR(vCpt)); 

END;
/
exit

How do I do base64 encoding on iOS?

Here's a compact Objective-C version as a Category on NSData. It takes some thinking about...

@implementation NSData (DataUtils)

static char base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

- (NSString *)newStringInBase64FromData
{
 NSMutableString *dest = [[NSMutableString alloc] initWithString:@""];
 unsigned char * working = (unsigned char *)[self bytes];
 int srcLen = [self length];

 // tackle the source in 3's as conveniently 4 Base64 nibbles fit into 3 bytes
 for (int i=0; i<srcLen; i += 3)
 {
  // for each output nibble
  for (int nib=0; nib<4; nib++)
  {
   // nibble:nib from char:byt
   int byt = (nib == 0)?0:nib-1;
   int ix = (nib+1)*2;

   if (i+byt >= srcLen) break;

   // extract the top bits of the nibble, if valid
   unsigned char curr = ((working[i+byt] << (8-ix)) & 0x3F);

   // extract the bottom bits of the nibble, if valid
   if (i+nib < srcLen) curr |= ((working[i+nib] >> ix) & 0x3F);

   [dest appendFormat:@"%c", base64[curr]];
  }
 }

 return dest;
}

@end

Padding can be added if required by making the scope of 'byt' wider and appending 'dest' with (2-byt) "=" characters before returning.

A Category can then be added to NSString, thus:

@implementation NSString (StringUtils)

- (NSString *)newStringInBase64FromString
{
 NSData *theData = [NSData dataWithBytes:[self UTF8String] length:[self length]]; 

 return [theData newStringInBase64FromData];
}

@end