Programs & Examples On #Hierarchy

For issues relating to creating, maintaining, or displaying a hierarchy of data or resources, etc.

Attempt to present UIViewController on UIViewController whose view is not in the window hierarchy

It's working fine try this.Link

UIViewController *top = [UIApplication sharedApplication].keyWindow.rootViewController;
[top presentViewController:secondView animated:YES completion: nil];

Warning: Attempt to present * on * whose view is not in the window hierarchy - swift

Swift 3

I had this keep coming up as a newbie and found that present loads modal views that can be dismissed but switching to root controller is best if you don't need to show a modal.

I was using this

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc  = storyboard?.instantiateViewController(withIdentifier: "MainAppStoryboard") as! TabbarController
present(vc, animated: false, completion: nil)

Using this instead with my tabController:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let view = storyboard.instantiateViewController(withIdentifier: "MainAppStoryboard") as UIViewController
let appDelegate = UIApplication.shared.delegate as! AppDelegate
//show window
appDelegate.window?.rootViewController = view

Just adjust to a view controller if you need to switch between multiple storyboard screens.

How to view hierarchical package structure in Eclipse package explorer

For Eclipse in Macbook it is just 2 click process:

  • Click on view menu (3 dot symbol) in package explorer -> hover over package presentation -> Click on Hierarchical

enter image description here

Getting activity from context in android

Never ever use getApplicationContext() with views.

It should always be activity's context, as the view is attached to activity. Also, you may have a custom theme set, and when using application's context, all theming will be lost. Read more about different versions of contexts here.

How to cut first n and last n columns?

The first part of your question is easy. As already pointed out, cut accepts omission of either the starting or the ending index of a column range, interpreting this as meaning either “from the start to column n (inclusive)” or “from column n (inclusive) to the end,” respectively:

$ printf 'this:is:a:test' | cut -d: -f-2
this:is
$ printf 'this:is:a:test' | cut -d: -f3-
a:test

It also supports combining ranges. If you want, e.g., the first 3 and the last 2 columns in a row of 7 columns:

$ printf 'foo:bar:baz:qux:quz:quux:quuz' | cut -d: -f-3,6-
foo:bar:baz:quux:quuz

However, the second part of your question can be a bit trickier depending on what kind of input you’re expecting. If by “last n columns” you mean “last n columns (regardless of their indices in the overall row)” (i.e. because you don’t necessarily know how many columns you’re going to find in advance) then sadly this is not possible to accomplish using cut alone. In order to effectively use cut to pull out “the last n columns” in each line, the total number of columns present in each line must be known beforehand, and each line must be consistent in the number of columns it contains.

If you do not know how many “columns” may be present in each line (e.g. because you’re working with input that is not strictly tabular), then you’ll have to use something like awk instead. E.g., to use awk to pull out the last 2 “columns” (awk calls them fields, the number of which can vary per line) from each line of input:

$ printf '/a\n/a/b\n/a/b/c\n/a/b/c/d\n' | awk -F/ '{print $(NF-1) FS $(NF)}'
/a
a/b
b/c
c/d

What is the difference between require_relative and require in Ruby?

I just saw the RSpec's code has some comment on require_relative being O(1) constant and require being O(N) linear. So probably the difference is that require_relative is the preferred one than require.

JQuery add class to parent element

$(this.parentNode).addClass('newClass');

jQuery .search() to any string

Ah, that would be because RegExp is not jQuery. :)

Try this page. jQuery.attr doesn't return a String so that would certainly cause in this regard. Fortunately I believe you can just use .text() to return the String representation.

Something like:

$("li").val("title").search(/sometext/i));

How can I update npm on Windows?

1. Installing latest npm version

npm install –g npm@latest 

(You can type "npm –version" to check that)


2. Installing Node

a. Install node new version via following URL: https://nodejs.org/en/download/current/ Follow the default choices
b. Remove C:\Users\\AppData\Roaming\NPM
c. Remove C:\Users\\AppData\Roaming\npm-cache


Optionally:

d. (Delete node_modules folder in your current project folder)
e. npm cache verify
f. npm install

Hex colors: Numeric representation for "transparent"?

I was also trying for transparency - maybe you could try leaving blank the value of background e.g. something like

bgcolor=" "

Pad a number with leading zeros in JavaScript

You could do something like this:

function pad ( num, size ) {
  return ( Math.pow( 10, size ) + ~~num ).toString().substring( 1 );
}

Edit: This was just a basic idea for a function, but to add support for larger numbers (as well as invalid input), this would probably be better:

function pad ( num, size ) {
  if (num.toString().length >= size) return num;
  return ( Math.pow( 10, size ) + Math.floor(num) ).toString().substring( 1 );
}

This does 2 things:

  1. If the number is larger than the specified size, it will simply return the number.
  2. Using Math.floor(num) in place of ~~num will support larger numbers.

No provider for Router?

If you created a separate module (eg. AppRoutingModule) to contain your routing commands you can get this same error:

Error: StaticInjectorError(AppModule)[RouterLinkWithHref -> Router]: 
StaticInjectorError(Platform: core)[RouterLinkWithHref -> Router]: 
NullInjectorError: No provider for Router!

You may have forgotten to import it to the main AppModule as shown here:

@NgModule({
  imports:      [ BrowserModule, FormsModule, RouterModule, AppRoutingModule ],
  declarations: [ AppComponent, Page1Component, Page2Component ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

Getting current date and time in JavaScript

I have found the simplest way to get current date and time in JavaScript from here - How to get current Date and Time using JavaScript

var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var CurrentDateTime = date+' '+time;

Is there a way to override class variables in Java?

Why would you want to override variables when you could easily reassign them in the subClasses.

I follow this pattern to work around the language design. Assume a case where you have a weighty service class in your framework which needs be used in different flavours in multiple derived applications.In that case , the best way to configure the super class logic is by reassigning its 'defining' variables.

public interface ExtensibleService{
void init();
}

public class WeightyLogicService implements ExtensibleService{
    private String directoryPath="c:\hello";

    public void doLogic(){
         //never forget to call init() before invocation or build safeguards
         init();
       //some logic goes here
   }

   public void init(){}    

}

public class WeightyLogicService_myAdaptation extends WeightyLogicService {
   @Override
   public void init(){
    directoryPath="c:\my_hello";
   }

}

Make an html number input always display 2 decimal places

an inline solution combines Groot and Ivaylo suggestions in the format below:

onchange="(function(el){el.value=parseFloat(el.value).toFixed(2);})(this)"

Is it possible to create a 'link to a folder' in a SharePoint document library?

i couldn't change the permissions on the sharepoint i'm using but got a round it by uploading .url files with the drag and drop multiple files uploader.

Using the normal upload didn't work because they are intepreted by the file open dialog when you try to open them singly so it just tries to open the target not the .url file.

.url files can be made by saving a favourite with internet exploiter.

Python Progress Bar

I like Gabriel answer, but i changed it to be flexible. You can send bar-length to the function and get your progress bar with any length that you want. And you can't have a progress bar with zero or negative length. Also, you can use this function like Gabriel answer (Look at the Example #2).

import sys
import time

def ProgressBar(Total, Progress, BarLength=20, ProgressIcon="#", BarIcon="-"):
    try:
        # You can't have a progress bar with zero or negative length.
        if BarLength <1:
            BarLength = 20
        # Use status variable for going to the next line after progress completion.
        Status = ""
        # Calcuting progress between 0 and 1 for percentage.
        Progress = float(Progress) / float(Total)
        # Doing this conditions at final progressing.
        if Progress >= 1.:
            Progress = 1
            Status = "\r\n"    # Going to the next line
        # Calculating how many places should be filled
        Block = int(round(BarLength * Progress))
        # Show this
        Bar = "[{}] {:.0f}% {}".format(ProgressIcon * Block + BarIcon * (BarLength - Block), round(Progress * 100, 0), Status)
        return Bar
    except:
        return "ERROR"

def ShowBar(Bar):
    sys.stdout.write(Bar)
    sys.stdout.flush()

if __name__ == '__main__':
    print("This is a simple progress bar.\n")

    # Example #1:
    print('Example #1')
    Runs = 10
    for i in range(Runs + 1):
        progressBar = "\rProgress: " + ProgressBar(10, i, Runs)
        ShowBar(progressBar)
        time.sleep(1)

    # Example #2:
    print('\nExample #2')
    Runs = 10
    for i in range(Runs + 1):
        progressBar = "\rProgress: " + ProgressBar(10, i, 20, '|', '.')
        ShowBar(progressBar)
        time.sleep(1)

    print('\nDone.')

# Example #2:
Runs = 10
for i in range(Runs + 1):
    ProgressBar(10, i)
    time.sleep(1)

Result:

This is a simple progress bar.

Example #1

Progress: [###-------] 30%

Example #2

Progress: [||||||||||||........] 60%

Done.

case-insensitive matching in xpath?

for selenium xpath lower-case will not work ... Translate will help Case 1 :

  1. using Attribute //*[translate(@id,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')='login_field']
  2. Using any attribute //[translate(@,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')='login_field']

Case 2 : (with contains) //[contains(translate(@id,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz'),'login_field')]

case 3 : for Text property //*[contains(translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'),'username')]


QA Automator is automation management tool on cloud platform , where you can create, execute and maintenance the automation test scripts https://www.youtube.com/watch?v=iFk1Na_627U&t=53s

Split Div Into 2 Columns Using CSS

The most flexible way to do this:

#content::after {
  display:block;
  content:"";
  clear:both;
}

This acts exactly the same as appending the element to #content:

<br style="clear:both;"/>

but without actually adding an element. ::after is called a pseudo element. The only reason this is better than adding overflow:hidden; to #content is that you can have absolute positioned child elements overflow and still be visible. Also it will allow box-shadow's to still be visible.

Razor MVC Populating Javascript array with Model Array

This is possible, you just need to loop through the razor collection

<script type="text/javascript">

    var myArray = [];

    @foreach (var d in Model.data)
    {
        @:myArray.push("@d");
    }

    alert(myArray);

</script>

Hope this helps

How to change the font color of a disabled TextBox?

NOTE: see Cheetah's answer below as it identifies a prerequisite to get this solution to work. Setting the BackColor of the TextBox.


I think what you really want to do is enable the TextBox and set the ReadOnly property to true.

It's a bit tricky to change the color of the text in a disabled TextBox. I think you'd probably have to subclass and override the OnPaint event.

ReadOnly though should give you the same result as !Enabled and allow you to maintain control of the color and formatting of the TextBox. I think it will also still support selecting and copying text from the TextBox which is not possible with a disabled TextBox.

Another simple alternative is to use a Label instead of a TextBox.

how can select from drop down menu and call javascript function

<script type="text/javascript">
function report(func)
{
    func();
}

function daily()
{
    alert('daily');
}

function monthly()
{
    alert('monthly');
}
</script>

Node.js on multi-core machines

It's also possible to design the web-service as several stand alone servers that listen to unix sockets, so that you can push functions like data processing into seperate processes.

This is similar to most scrpting/database web server architectures where a cgi process handles business logic and then pushes and pulls the data via a unix socket to a database.

the difference being that the data processing is written as a node webserver listening on a port.

it's more complex but ultimately its where multi-core development has to go. a multiprocess architecture using multiple components for each web request.

Android: Tabs at the BOTTOM

Try it ;) Just watch the content of the FrameLayout(@id/tabcontent), because I don't know how it will handle in case of scrolling... In my case it works because I used ListView as the content of my tabs. :) Hope it helps.

<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <RelativeLayout 
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent">
        <FrameLayout android:id="@android:id/tabcontent"
             android:layout_width="fill_parent" 
             android:layout_height="fill_parent"
             android:layout_alignParentTop="true" 
             android:layout_above="@android:id/tabs" />
    <TabWidget android:id="@android:id/tabs"
             android:layout_width="fill_parent" 
             android:layout_height="wrap_content"
             android:layout_alignParentBottom="true" />
    </RelativeLayout>
</TabHost>

When do you use Java's @Override annotation and why?

I use it as much as can to identify when a method is being overriden. If you look at the Scala programming language, they also have an override keyword. I find it useful.

How to convert Hexadecimal #FFFFFF to System.Drawing.Color

You can do

var color =  System.Drawing.ColorTranslator.FromHtml("#FFFFFF");

Or this (you will need the System.Windows.Media namespace)

var color = (Color)ColorConverter.ConvertFromString("#FFFFFF");

Android Fragment onClick button Method

If you want to use data binding you can follow this solution The following solution might be a better one to follow. the layout is in fragment_my.xml

<data>
    <variable
        name="listener"
        type="my_package.MyListener" />
</data>

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    
    <Button
        android:id="@+id/moreTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="@{() -> listener.onClick()}"
        android:text="@string/login"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
And the Fragment would be as follows
class MyFragment : Fragment(), MyListener {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
            return FragmentMyBinding.inflate(
                inflater,
                container,
                false
            ).apply {
                lifecycleOwner = viewLifecycleOwner
                listener = this@MyFragment
            }.root
    }

    override fun onClick() {
        TODO("Not yet implemented")
    }

}

interface MyListener{
    fun onClick()
}

jQuery - Dynamically Create Button and Attach Event Handler

You can either use onclick inside the button to ensure the event is preserved, or else attach the button click handler by finding the button after it is inserted. The test.html() call will not serialize the event.

Get value of div content using jquery

You can get div content using .text() in jquery

var divContent = $('#field-function_purpose').text();
console.log(divContent);

Fiddle

how to prevent css inherit

Non-inherited elements must have default styles set.
If parent class set color:white and font-weight:bold style then no inherited child must set 'color:black' and font-weight: normal in their class. If style is not set, elements get their style from their parents.

Consider marking event handler as 'passive' to make the page more responsive

For those stuck with legacy issues, find the line throwing the error and add {passive: true} - eg:

this.element.addEventListener(t, e, !1)

becomes

this.element.addEventListener(t, e, { passive: true} )

What does servletcontext.getRealPath("/") mean and when should I use it

A web application's context path is the directory that contains the web application's WEB-INF directory. It can be thought of as the 'home' of the web app. Often, when writing web applications, it can be important to get the actual location of this directory in the file system, since this allows you to do things such as read from files or write to files.

This location can be obtained via the ServletContext object's getRealPath() method. This method can be passed a String parameter set to File.separator to get the path using the operating system's file separator ("/" for UNIX, "\" for Windows).

How to set up a cron job to run an executable every hour?

Did you mean the executable fails to run , if invoked from any other directory? This is rather a bug on the executable. One potential reason could be the executable requires some shared libraires from the installed folder. You may check environment variable LD_LIBRARY_PATH

How to display image from URL on Android

I tried this code working for me,get image directly from url

      private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
      ImageView bmImage;
      public DownloadImageTask(ImageView bmImage) {
          this.bmImage = bmImage;
      }

      protected Bitmap doInBackground(String... urls) {
          String urldisplay = urls[0];
          Bitmap mIcon11 = null;
          try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
          } catch (Exception e) {
              Log.e("Error", e.getMessage());
              e.printStackTrace();
          }
          return mIcon11;
      }

      protected void onPostExecute(Bitmap result) {
          bmImage.setImageBitmap(result);
      }
    }

use inside onCreate() method

new DownloadImageTask((ImageView) findViewById(R.id.image)) .execute("http://scoopak.com/wp-content/uploads/2013/06/free-hd-natural-wallpapers-download-for-pc.jpg");

For-loop vs while loop in R

And about timing:

fn1 <- function (N) {
    for(i in as.numeric(1:N)) { y <- i*i }
}
fn2 <- function (N) {
    i=1
    while (i <= N) {
        y <- i*i
        i <- i + 1
    }
}

system.time(fn1(60000))
# user  system elapsed 
# 0.06    0.00    0.07 
system.time(fn2(60000))
# user  system elapsed 
# 0.12    0.00    0.13

And now we know that for-loop is faster than while-loop. You cannot ignore warnings during timing.

how to refresh my datagridview after I add new data

You can use a binding source to bind to with your datagridview. Set your class or list of data. Set a bindingsource.datasource equal to that. Set the datasource of your datagridview to your bindingsource.

How to make the corners of a button round?

Create rounded_btn.xml file in Drawable folder...

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
     <solid android:color="@color/#FFFFFF"/>    

     <stroke android:width="1dp"
        android:color="@color/#000000"
        />

     <padding android:left="1dp"
         android:top="1dp"
         android:right="1dp"
         android:bottom="1dp"
         /> 

     <corners android:bottomRightRadius="5dip" android:bottomLeftRadius="5dip" 
         android:topLeftRadius="5dip" android:topRightRadius="5dip"/> 
  </shape>

and use this.xml file as a button background

<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/rounded_btn"
android:text="Test" />

Can not find the tag library descriptor of springframework

If you are using maven use this dependency:

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-taglibs</artifactId>
    <version>3.1.4.RELEASE</version>
</dependency>

Django ChoiceField

New method in Django 3

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

from django.db import models

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


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

django docs

How can I URL encode a string in Excel VBA?

The accepted answer's code stopped on a Unicode error in Access 2013, so I wrote a function for myself with high readability that should follow RFC 3986 according to Davis Peixoto, and cause minimal trouble in various environments.

Note: The percent sign itself must be replaced first, or it will double-encode any previously encoded characters. Replacing space with + was added, not to conform with RFC 3986, but to provide links that don't break due to formatting. It is optional.

Public Function URLEncode(str As Variant) As String
    Dim i As Integer, sChar() As String, sPerc() As String
    sChar = Split("%|!|*|'|(|)|;|:|@|&|=|+|$|,|/|?|#|[|]| ", "|")
    sPerc = Split("%25 %21 %2A %27 %28 %29 %3B %3A %40 %26 %3D %2B %24 %2C %2F %3F %23 %5B %5D +", " ")
    URLEncode = Nz(str)
    For i = 0 To 19
        URLEncode = Replace(URLEncode, sChar(i), sPerc(i))
    Next i
End Function

How to programmatically tell if a Bluetooth device is connected?

This code is for the headset profiles, probably it will work for other profiles too. First you need to provide profile listener (Kotlin code):

private val mProfileListener = object : BluetoothProfile.ServiceListener {
    override fun onServiceConnected(profile: Int, proxy: BluetoothProfile) {
        if (profile == BluetoothProfile.HEADSET) 
            mBluetoothHeadset = proxy as BluetoothHeadset            
    }

    override fun onServiceDisconnected(profile: Int) {
        if (profile == BluetoothProfile.HEADSET) {
            mBluetoothHeadset = null
        }
    }
}

Then while checking bluetooth:

mBluetoothAdapter.getProfileProxy(context, mProfileListener, BluetoothProfile.HEADSET)
if (!mBluetoothAdapter.isEnabled) {
    return Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
}

It takes a bit of time until onSeviceConnected is called. After that you may get the list of the connected headset devices from:

mBluetoothHeadset!!.connectedDevices

What is the difference between C# and .NET?

Here I provided you a link where explain what is C# Language and the .NET Framework Platform Architecture. Remember that C# is a general-purpose, object-oriented programming language, and it runs on the .NET Framework.

.NET Framework includes a large class library named Framework Class Library (FCL) and provides user interface, data access, database connectivity, cryptography, web application development, numeric algorithms, and network communications.

.NET Framework was developed by Microsoft that runs primarily on Microsoft Windows.

Introduction to the C# Language and the .NET Framework from Microsoft Docs

How to use GROUP BY to concatenate strings in SQL Server?

SQL Server 2005 and later allow you to create your own custom aggregate functions, including for things like concatenation- see the sample at the bottom of the linked article.

How to check if an Object is a Collection Type in Java?

Update: there are two possible scenarios here:

  1. You are determining if an object is a collection;

  2. You are determining if a class is a collection.

The solutions are slightly different but the principles are the same. You also need to define what exactly constitutes a "collection". Implementing either Collection or Map will cover the Java Collections.

Solution 1:

public static boolean isCollection(Object ob) {
  return ob instanceof Collection || ob instanceof Map;
}

Solution 2:

public static boolean isClassCollection(Class c) {
  return Collection.class.isAssignableFrom(c) || Map.class.isAssignableFrom(c);
}

(1) can also be implemented in terms of (2):

public static boolean isCollection(Object ob) {
  return ob != null && isClassCollection(ob.getClass());
}

I don't think the efficiency of either method will be greatly different from the other.

Genymotion error at start 'Unable to load virtualbox'

Had the same problem, Uninstall Genymotion, install VirtualBox stand alone from https://www.virtualbox.org/wiki/Downloads then install the Genymotion package without VirtualBox.

How to get first and last day of week in Oracle?

Another solution is

SELECT 
  ROUND((TRUNC(SYSDATE) - TRUNC(SYSDATE, 'YEAR')) / 7,0) CANTWEEK,
  NEXT_DAY(SYSDATE, 'SUNDAY') - 7 FIRSTDAY,
  NEXT_DAY(SYSDATE, 'SUNDAY') - 1 LASTDAY
FROM DUAL

You must concat the cantweek with the year

check output from CalledProcessError

This will return true only if host responds to ping. Works on windows and linux

def ping(host):
    """
    Returns True if host (str) responds to a ping request.
    NB on windows ping returns true for success and host unreachable
    """
    param = '-n' if platform.system().lower()=='windows' else '-c'
    result = False
    try:
        out = subprocess.check_output(['ping', param, '1', host])
        #ping exit code 0
        if 'Reply from {}'.format(host) in str(out):
            result = True          
    except  subprocess.CalledProcessError:
        #ping exit code not 0
            result = False
    #print(str(out))
    return result

Map over object preserving keys

I think you want a mapValues function (to map a function over the values of an object), which is easy enough to implement yourself:

mapValues = function(obj, f) {
  var k, result, v;
  result = {};
  for (k in obj) {
    v = obj[k];
    result[k] = f(v);
  }
  return result;
};

if (boolean == false) vs. if (!boolean)

- Here its more about the coding style than being the functionality....

- The 1st option is very clear, but then the 2nd one is quite elegant... no offense, its just my view..

Efficient way to add spaces between characters in a string

s = "BINGO"
print(s.replace("", " ")[1: -1])

Timings below

$ python -m timeit -s's = "BINGO"' 's.replace(""," ")[1:-1]'
1000000 loops, best of 3: 0.584 usec per loop
$ python -m timeit -s's = "BINGO"' '" ".join(s)'
100000 loops, best of 3: 1.54 usec per loop

Pass arguments into C program from command line

You could use getopt.

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

 int
 main (int argc, char **argv)
 {
   int bflag = 0;
   int sflag = 0;
   int index;
   int c;

   opterr = 0;

   while ((c = getopt (argc, argv, "bs")) != -1)
     switch (c)
       {
       case 'b':
         bflag = 1;
         break;
       case 's':
         sflag = 1;
         break;
       case '?':
         if (isprint (optopt))
           fprintf (stderr, "Unknown option `-%c'.\n", optopt);
         else
           fprintf (stderr,
                    "Unknown option character `\\x%x'.\n",
                    optopt);
         return 1;
       default:
         abort ();
       }

   printf ("bflag = %d, sflag = %d\n", bflag, sflag);

   for (index = optind; index < argc; index++)
     printf ("Non-option argument %s\n", argv[index]);
   return 0;
 }

Exception in thread "main" java.lang.Error: Unresolved compilation problems

You have to Import the Scanner and Timer Package Properly using the java.util classes.

import java.util.Scanner;
import java.util.Timer;

Aligning text and image on UIButton with imageEdgeInsets and titleEdgeInsets

Here is a simple example of how to use imageEdgeInsets This will make a 30x30 button with a hittable area 10 pixels bigger all the way around (50x50)

    var expandHittableAreaAmt : CGFloat = 10
    var buttonWidth : CGFloat = 30
    var button = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
    button.frame = CGRectMake(0, 0, buttonWidth+expandHittableAreaAmt, buttonWidth+expandHittableAreaAmt)
    button.imageEdgeInsets = UIEdgeInsetsMake(expandHittableAreaAmt, expandHittableAreaAmt, expandHittableAreaAmt, expandHittableAreaAmt)
    button.setImage(UIImage(named: "buttonImage"), forState: .Normal)
    button.addTarget(self, action: "didTouchButton:", forControlEvents:.TouchUpInside)

Make WPF Application Fullscreen (Cover startmenu)

<Window x:Class="HTA.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    mc:Ignorable="d" 
    ResizeMode="NoResize"
    WindowStartupLocation="CenterScreen" 
    Width="1024" Height="768"
    WindowState="Maximized" WindowStyle="None">

Window state to Maximized and window style to None

How to control border height?

not bad .. but try this one ... (should works for all but ist just -webkit included)

<br>
<input type="text" style="
  background: transparent;
border-bottom: 1px solid #B5D5FF;
border-left: 1px solid;
border-right: 1px solid;
border-left-color: #B5D5FF;
border-image: -webkit-linear-gradient(top, #fff 50%, #B5D5FF 0%) 1 repeat;
">

//Feel free to edit and add all other browser..

'typeid' versus 'typeof' in C++

The primary difference between the two is the following

  • typeof is a compile time construct and returns the type as defined at compile time
  • typeid is a runtime construct and hence gives information about the runtime type of the value.

typeof Reference: http://www.delorie.com/gnu/docs/gcc/gcc_36.html

typeid Reference: https://en.wikipedia.org/wiki/Typeid

Java - Get a list of all Classes loaded in the JVM

Well, what I did was simply listing all the files in the classpath. It may not be a glorious solution, but it works reliably and gives me everything I want, and more.

How do I fix a "Performance counter registry hive consistency" when installing SQL Server R2 Express?

Use Rafael's solution: http://social.msdn.microsoft.com/Forums/en/sqlsetupandupgrade/thread/dddf0349-557b-48c7-bf82-6bd1adb5c694..

Added data from link to avoid link rot..

put this at any Console application:

string.Format("{0,3}", CultureInfo.InstalledUICulture.Parent.LCID.ToString("X")).Replace(" ", "0");

Watch the result. At mine it was "016".

Then you go to the registry at this key:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Perflib

and create another one with the name you got from the string.Format result.

In my case:

"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Perflib\016"

and copy the info that is on any other key in this Perflib to this key you just created. Run the instalation again.

Just run the script and get your 3 digit code. Then follow his simple and quick steps, and you're ready to go!

Cheers

AngularJs ReferenceError: angular is not defined

You should put the include angular line first, before including any other js file

DB2 SQL error: SQLCODE: -206, SQLSTATE: 42703

That only means that an undefined column or parameter name was detected. The errror that DB2 gives should point what that may be:

DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=[THE_UNDEFINED_COLUMN_OR_PARAMETER_NAME], DRIVER=4.8.87

Double check your table definition. Maybe you just missed adding something.

I also tried google-ing this problem and saw this:

http://www.coderanch.com/t/515475/JDBC/databases/sql-insert-statement-giving-sqlcode

How to fix .pch file missing on build?

Precompiled Header (pch) use is a two-step process.

In step one, you compile a stub file (In VS200x it's usually called stdafx.cpp. Newer versions use pch.cpp.). This stub file indirectly includes only the headers you want precompiled. Typically, one small header (usually stdafx.h or pch.hpp) lists standard headers such as <iostream> and <string>, and this is then included in the stub file. Compiling this creates the .pch file.

In step 2, your actual source code includes the same small header from step 1 as the first header. The compiler, when it encounters this special header, reads the corresponding .pch file instead. That means it doesn't have to (re)compile those standard headers every time.

In your case, it seems step 1 fails. Is the stub file still present? In your case, that would probably be xxxxx.cpp. It must be a file that's compiled with /Yc:xxxxx.pch, since that's the compiler flag to indicate it's step 1 of the PCH process. If xxxxx.cpp is present, and is such a stub file, then it's probably missing its /Yc: compiler option.

How to convert a byte array to Stream

In your case:

MemoryStream ms = new MemoryStream(buffer);

jQuery Data vs Attr?

The main difference between the two is where it is stored and how it is accessed.

$.fn.attr stores the information directly on the element in attributes which are publicly visible upon inspection, and also which are available from the element's native API.

$.fn.data stores the information in a ridiculously obscure place. It is located in a closed over local variable called data_user which is an instance of a locally defined function Data. This variable is not accessible from outside of jQuery directly.

Data set with attr()

  • accessible from $(element).attr('data-name')
  • accessible from element.getAttribute('data-name'),
  • if the value was in the form of data-name also accessible from $(element).data(name) and element.dataset['name'] and element.dataset.name
  • visible on the element upon inspection
  • cannot be objects

Data set with .data()

  • accessible only from .data(name)
  • not accessible from .attr() or anywhere else
  • not publicly visible on the element upon inspection
  • can be objects

Does Arduino use C or C++?

Arduino doesn't run either C or C++. It runs machine code compiled from either C, C++ or any other language that has a compiler for the Arduino instruction set.

C being a subset of C++, if Arduino can "run" C++ then it can "run" C.

If you don't already know C nor C++, you should probably start with C, just to get used to the whole "pointer" thing. You'll lose all the object inheritance capabilities though.

SQL Server: how to select records with specific date from datetime column

For Perfect DateTime Match in SQL Server

SELECT ID FROM [Table Name] WHERE (DateLog between '2017-02-16 **00:00:00.000**' and '2017-12-16 **23:59:00.999**') ORDER BY DateLog DESC

How to select Multiple images from UIImagePickerController

You can't use UIImagePickerController, but you can use a custom image picker. I think ELCImagePickerController is the best option, but here are some other libraries you could use:

Objective-C
1. ELCImagePickerController
2. WSAssetPickerController
3. QBImagePickerController
4. ZCImagePickerController
5. CTAssetsPickerController
6. AGImagePickerController
7. UzysAssetsPickerController
8. MWPhotoBrowser
9. TSAssetsPickerController
10. CustomImagePicker
11. InstagramPhotoPicker
12. GMImagePicker
13. DLFPhotosPicker
14. CombinationPickerController
15. AssetPicker
16. BSImagePicker
17. SNImagePicker
18. DoImagePickerController
19. grabKit
20. IQMediaPickerController
21. HySideScrollingImagePicker
22. MultiImageSelector
23. TTImagePicker
24. SelectImages
25. ImageSelectAndSave
26. imagepicker-multi-select
27. MultiSelectImagePickerController
28. YangMingShan(Yahoo like image selector)
29. DBAttachmentPickerController
30. BRImagePicker
31. GLAssetGridViewController
32. CreolePhotoSelection

Swift
1. LimPicker (Similar to WhatsApp's image picker)
2. RMImagePicker
3. DKImagePickerController
4. BSImagePicker
5. Fusuma(Instagram like image selector)
6. YangMingShan(Yahoo like image selector)
7. NohanaImagePicker
8. ImagePicker
9. OpalImagePicker
10. TLPhotoPicker
11. AssetsPickerViewController
12. Alerts-and-pickers/Telegram Picker

Thanx to @androidbloke,
I have added some library that I know for multiple image picker in swift.
Will update list as I find new ones.
Thank You.

How to include static library in makefile

use

LDFLAGS= -L<Directory where the library resides> -l<library name>

Like :

LDFLAGS = -L. -lmine

for ensuring static compilation you can also add

LDFLAGS = -static

Or you can just get rid of the whole library searching, and link with with it directly.

say you have main.c fun.c

and a static library libmine.a

then you can just do in your final link line of the Makefile

$(CC) $(CFLAGS) main.o fun.o libmine.a

No content to map due to end-of-input jackson parser

In my case the problem was caused by my passing a null InputStream to the ObjectMapper.readValue call:

ObjectMapper objectMapper = ...
InputStream is = null; // The code here was returning null.
Foo foo = objectMapper.readValue(is, Foo.class)

I am guessing that this is the most common reason for this exception.

How do I make Git use the editor of my choice for commits?

For EmEditor users

To set EmEditor as the default text editor for Git, open Git Bash, and type:

git config --global core.editor "emeditor.exe -sp"

EmEditor v19.9.2 or later required.

How to make an ng-click event conditional?

Basically ng-click first checks the isDisabled and based on its value it will decide whether the function should be called or not.

<span ng-click="(isDisabled) || clicked()">Do something</span>

OR read it as

<span ng-click="(if this value is true function clicked won't be called. and if it's false the clicked will be called) || clicked()">Do something</span>

What does .shape[] do in "for i in range(Y.shape[0])"?

shape() consists of array having two arguments rows and columns.

if you search shape[0] then it will gave you the number of rows. shape[1] will gave you number of columns.

How can I convince IE to simply display application/json rather than offer to download it?

Changing IE's JSON mime-type settings will effect the way IE treats all JSON responses.

Changing the mime-type header to text/html will effectively tell any browser that the JSON response you are returning is not JSON but plain text.

Neither options are preferable.

Instead you would want to use a plugin or tool like the above mentioned Fiddler or any other network traffic inspector proxy where you can choose each time how to process the JSON response.

How to plot two columns of a pandas data frame using points?

Now in latest pandas you can directly use df.plot.scatter function

df = pd.DataFrame([[5.1, 3.5, 0], [4.9, 3.0, 0], [7.0, 3.2, 1],
                   [6.4, 3.2, 1], [5.9, 3.0, 2]],
                  columns=['length', 'width', 'species'])
ax1 = df.plot.scatter(x='length',
                      y='width',
                      c='DarkBlue')

https://pandas.pydata.org/pandas-docs/version/0.23/generated/pandas.DataFrame.plot.scatter.html

Passing Multiple route params in Angular2

      new AsyncRoute({path: '/demo/:demoKey1/:demoKey2', loader: () => {
      return System.import('app/modules/demo/demo').then(m =>m.demoComponent);
       }, name: 'demoPage'}),
       export class demoComponent {
       onClick(){
            this._router.navigate( ['/demoPage', {demoKey1: "123", demoKey2: "234"}]);
          }
        }

SQL keys, MUL vs PRI vs UNI

Walkthough on what is MUL, PRI and UNI in MySQL?

From the MySQL 5.7 documentation:

  • If Key is PRI, the column is a PRIMARY KEY or is one of the columns in a multiple-column PRIMARY KEY.
  • If Key is UNI, the column is the first column of a UNIQUE index. (A UNIQUE index permits multiple NULL values, but you can tell whether the column permits NULL by checking the Null field.)
  • If Key is MUL, the column is the first column of a nonunique index in which multiple occurrences of a given value are permitted within the column.

Live Examples

Control group, this example has neither PRI, MUL, nor UNI:

mysql> create table penguins (foo INT);
Query OK, 0 rows affected (0.01 sec)

mysql> desc penguins;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| foo   | int(11) | YES  |     | NULL    |       |
+-------+---------+------+-----+---------+-------+
1 row in set (0.00 sec)

A table with one column and an index on the one column has a MUL:

mysql> create table penguins (foo INT, index(foo));
Query OK, 0 rows affected (0.01 sec)

mysql> desc penguins;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| foo   | int(11) | YES  | MUL | NULL    |       |
+-------+---------+------+-----+---------+-------+
1 row in set (0.00 sec)

A table with a column that is a primary key has PRI

mysql> create table penguins (foo INT primary key);
Query OK, 0 rows affected (0.02 sec)

mysql> desc penguins;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| foo   | int(11) | NO   | PRI | NULL    |       |
+-------+---------+------+-----+---------+-------+
1 row in set (0.00 sec)

A table with a column that is a unique key has UNI:

mysql> create table penguins (foo INT unique);
Query OK, 0 rows affected (0.01 sec)

mysql> desc penguins;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| foo   | int(11) | YES  | UNI | NULL    |       |
+-------+---------+------+-----+---------+-------+
1 row in set (0.00 sec)

A table with an index covering foo and bar has MUL only on foo:

mysql> create table penguins (foo INT, bar INT, index(foo, bar));
Query OK, 0 rows affected (0.01 sec)

mysql> desc penguins;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| foo   | int(11) | YES  | MUL | NULL    |       |
| bar   | int(11) | YES  |     | NULL    |       |
+-------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)

A table with two separate indexes on two columns has MUL for each one

mysql> create table penguins (foo INT, bar int, index(foo), index(bar));
Query OK, 0 rows affected (0.01 sec)

mysql> desc penguins;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| foo   | int(11) | YES  | MUL | NULL    |       |
| bar   | int(11) | YES  | MUL | NULL    |       |
+-------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)

A table with an Index spanning three columns has MUL on the first:

mysql> create table penguins (foo INT, 
       bar INT, 
       baz INT, 
       INDEX name (foo, bar, baz));
Query OK, 0 rows affected (0.01 sec)

mysql> desc penguins;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| foo   | int(11) | YES  | MUL | NULL    |       |
| bar   | int(11) | YES  |     | NULL    |       |
| baz   | int(11) | YES  |     | NULL    |       |
+-------+---------+------+-----+---------+-------+
3 rows in set (0.00 sec)

A table with a foreign key that references another table's primary key is MUL

mysql> create table penguins(id int primary key);
Query OK, 0 rows affected (0.01 sec)

mysql> create table skipper(id int, foreign key(id) references penguins(id));
Query OK, 0 rows affected (0.01 sec)

mysql> desc skipper;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id    | int(11) | YES  | MUL | NULL    |       |
+-------+---------+------+-----+---------+-------+
1 row in set (0.00 sec)

mysql> desc penguins;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id    | int(11) | NO   | PRI | NULL    |       |
+-------+---------+------+-----+---------+-------+
1 row in set (0.00 sec)

Stick that in your neocortex and set the dial to "frappe".

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

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

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

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

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

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

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


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

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

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

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

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

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

MacOS Xcode CoreSimulator folder very big. Is it ok to delete content?

That directory is part of your user data and you can delete any user data without affecting Xcode seriously. You can delete the whole CoreSimulator/ directory. Xcode will recreate fresh instances there for you when you do your next simulator run. If you can afford losing any previous simulator data of your apps this is the easy way to get space.

Update: A related useful app is "DevCleaner for Xcode" https://apps.apple.com/app/devcleaner-for-xcode/id1388020431

How to set shadows in React Native for android?

The elevation style property on Android does not work unless backgroundColor has been specified for the element.

Android - elevation style property does not work without backgroundColor

Example:

{
  shadowColor: 'black',
  shadowOpacity: 0.26,
  shadowOffset: { width: 0, height: 2},
  shadowRadius: 10,
  elevation: 3,
  backgroundColor: 'white'
}

If statement for strings in python?

Even once you fixed the mis-cased if and improper indentation in your code, it wouldn't work as you probably expected. To check a string against a set of strings, use in. Here's how you'd do it (and note that if is all lowercase and that the code within the if block is indented one level).

One approach:

if answer in ['y', 'Y', 'yes', 'Yes', 'YES']:
    print("this will do the calculation")

Another:

if answer.lower() in ['y', 'yes']:
    print("this will do the calculation")

Change default text in input type="file"?

I think this is what you want:

_x000D_
_x000D_
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>

<body>
  <button style="display:block;width:120px; height:30px;" onclick="document.getElementById('getFile').click()">Your text here</button>
  <input type='file' id="getFile" style="display:none">
</body>

</html>
_x000D_
_x000D_
_x000D_

How to insert an image in python

Install PIL(Python Image Library) :

then:

from PIL import Image
myImage = Image.open("your_image_here");
myImage.show();

How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator

Hope this will help little more :-

var string = "123456789"

If you want a substring after some particular index.

var indexStart  =  string.index(after: string.startIndex )// you can use any index in place of startIndex
var strIndexStart   = String (string[indexStart...])//23456789

If you want a substring after removing some string at the end.

var indexEnd  =  string.index(before: string.endIndex)
var strIndexEnd   = String (string[..<indexEnd])//12345678

you can also create indexes with the following code :-

var  indexWithOffset =  string.index(string.startIndex, offsetBy: 4)

Disable button in jQuery

Simply it's work fine, in HTML:

<button type="button" id="btn_CommitAll"class="btn_CommitAll">save</button>

In JQuery side put this function for disable button:

function disableButton() {
    $('.btn_CommitAll').prop("disabled", true);
}

For enable button:

function enableButton() {
    $('.btn_CommitAll').prop("disabled", false);
}

That's all.

"The specified Android SDK Build Tools version (26.0.0) is ignored..."

Open app/build.gradle file

Change buildToolsVersion to buildToolsVersion "26.0.2"

change compile 'com.android.support:appcompat to compile 'com.android.support:appcompat-v7:26.0.2'

Simple JavaScript Checkbox Validation

If the check box's ID "Delete" then for the "onclick" event of the submit button the javascript function can be as follows:

html:
<input type="checkbox" name="Delete" value="Delete" id="Delete"></td>
<input type="button" value="Delete" name="delBtn" id="delBtn" onclick="deleteData()">

script:
<script type="text/Javascript">
    function deleteData() {
        if(!document.getElementById('Delete').checked){
            alert('Checkbox not checked');
            return false;
        }
</script>

Node.js/Windows error: ENOENT, stat 'C:\Users\RT\AppData\Roaming\npm'

I ran into the same problem while installing a package via npm.

After creating the npm folder manually in C:\Users\UserName\AppData\Roaming\ that particular error was gone, but it gave similar multiple errors as it tried to create additional directories in the npm folder and failed. The issue was resolved after running the command prompt as an administrator.

CSV parsing in Java - working example..?

At a minimum you are going to need to know the column delimiter.

extract date only from given timestamp in oracle sql

If you want the value from your timestamp column to come back as a date datatype, use something like this:

select trunc(my_timestamp_column,'dd') as my_date_column from my_table;

Simple post to Web Api

It's been quite sometime since I asked this question. Now I understand it more clearly, I'm going to put a more complete answer to help others.

In Web API, it's very simple to remember how parameter binding is happening.

  • if you POST simple types, Web API tries to bind it from the URL
  • if you POST complex type, Web API tries to bind it from the body of the request (this uses a media-type formatter).

  • If you want to bind a complex type from the URL, you'll use [FromUri] in your action parameter. The limitation of this is down to how long your data going to be and if it exceeds the url character limit.

    public IHttpActionResult Put([FromUri] ViewModel data) { ... }

  • If you want to bind a simple type from the request body, you'll use [FromBody] in your action parameter.

    public IHttpActionResult Put([FromBody] string name) { ... }

as a side note, say you are making a PUT request (just a string) to update something. If you decide not to append it to the URL and pass as a complex type with just one property in the model, then the data parameter in jQuery ajax will look something like below. The object you pass to data parameter has only one property with empty property name.

var myName = 'ABC';
$.ajax({url:.., data: {'': myName}});

and your web api action will look something like below.

public IHttpActionResult Put([FromBody] string name){ ... }

This asp.net page explains it all. http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

Stop executing further code in Java

Just do:

public void onClick() {
    if(condition == true) {
        return;
    }
    string.setText("This string should not change if condition = true");
}

It's redundant to write if(condition == true), just write if(condition) (This way, for example, you'll not write = by mistake).

Display SQL query results in php

You need to do a while loop to get the result from the SQL query, like this:

require_once('db.php');  
$sql="SELECT * FROM  modul1open WHERE idM1O>=(SELECT FLOOR( MAX( idM1O ) * RAND( ) )    
FROM modul1open) ORDER BY idM1O LIMIT 1";

$result = mysql_query($sql);

while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {

    // If you want to display all results from the query at once:
    print_r($row);

    // If you want to display the results one by one
    echo $row['column1'];
    echo $row['column2']; // etc..

}

Also I would strongly recommend not using mysql_* since it's deprecated. Instead use the mysqli or PDO extension. You can read more about that here.

Value of type 'T' cannot be converted to

Both lines have the same problem

T newT1 = "some text";
T newT2 = (string)t;

The compiler doesn't know that T is a string and so has no way of knowing how to assign that. But since you checked you can just force it with

T newT1 = "some text" as T;
T newT2 = t; 

you don't need to cast the t since it's already a string, also need to add the constraint

where T : class

Launch Image does not show up in my iOS App

Removing "Launch screen interface file base name" from Info.plist file AND trashing "Launch Screen.xib" worked for me.

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

For me it was complaining like that on Windows 7 x64 when I had another process already listening on that same port.

It is possible to see currently occupied (bound) ports by running

netstat -ban

ImportError: No module named 'Queue'

I solve the problem my issue was I had file named queue.py in the same directory

Change keystore password from no password to a non blank password

On my system the password is 'changeit'. On blank if I hit enter then it complains about short password. Hope this helps

enter image description here

How do I properly force a Git push?

If I'm on my local branch A, and I want to force push local branch B to the origin branch C I can use the following syntax:

git push --force origin B:C

How do I keep two side-by-side divs the same height?

I like to use pseudo elements to achieve this. You can use it as background of the content and let them fill the space.

With these approach you can set margins between columns, borders, etc.

_x000D_
_x000D_
.wrapper{_x000D_
  position: relative;_x000D_
  width: 200px;_x000D_
}_x000D_
.wrapper:before,_x000D_
.wrapper:after{_x000D_
  content: "";_x000D_
  display: block;_x000D_
  height: 100%;_x000D_
  width: 40%;_x000D_
  border: 2px solid blue;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
}_x000D_
.wrapper:before{_x000D_
  left: 0;_x000D_
  background-color: red;_x000D_
}_x000D_
.wrapper:after{_x000D_
  right: 0;_x000D_
  background-color: green;_x000D_
}_x000D_
_x000D_
.div1, .div2{_x000D_
  width: 40%;_x000D_
  display: inline-block;_x000D_
  position: relative;_x000D_
  z-index: 1;_x000D_
}_x000D_
.div1{_x000D_
  margin-right: 20%;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="div1">Content Content Content Content Content Content Content Content Content_x000D_
  </div><div class="div2">Other</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Why am I getting "IndentationError: expected an indented block"?

I had this same problem and discovered (via this answer to a similar question) that the problem was that I didn't properly indent the docstring properly. Unfortunately IDLE doesn't give useful feedback here, but once I fixed the docstring indentation, the problem went away.

Specifically --- bad code that generates indentation errors:

def my_function(args):
"Here is my docstring"
    ....

Good code that avoids indentation errors:

def my_function(args):
    "Here is my docstring"
    ....

Note: I'm not saying this is the problem, but that it might be, because in my case, it was!

Disable submit button when form invalid with AngularJS

Selected response is correct, but someone like me, may have issues with async validation with sending request to the server-side - button will be not disabled during given request processing, so button will blink, which looks pretty strange for the users.

To void this, you just need to handle $pending state of the form:

<form name="myForm">
  <input name="myText" type="text" ng-model="mytext" required />
  <button ng-disabled="myForm.$invalid || myForm.$pending">Save</button>
</form>

Eclipse: "'Periodic workspace save.' has encountered a pro?blem."

Just for another data point, none of the above helped my situation. The way I finally got past this issue is that each time Eclipse complained about some folder not being there, I went on my hard drive and created the folder. E.g. after I see

Could not write metadata for '/servers'.
C:\...\.metadata\.plugins\org.eclipse.core.resources\.projects\servers\.markers.snap (The system cannot find the path specified.)

I create the "servers" folder (not the file inside it). This gets me to the next error. I went through 3-4 of these iterations (exiting Eclipse each time to force the save) before the issues went away.

HTH, Mark

How to pass an object from one activity to another on Android

This question is also discussed in another Stack Overflow question. Please have a look at a solution to Passing data through intent using Serializable. The main point is about using Bundle object which stores the necessary data inside Intent.

 Bundle bundle = new Bundle();

 bundle.putSerializable(key1, value1);
 bundle.putSerializable(key2, value2);
 bundle.putSerializable(key3, value3);

 intent.putExtras(bundle);

To extract values:

 Bundle bundle = new Bundle();

 for (String key : bundle.keySet()) {
 value = bundle.getSerializable(key));
 }

Advantage of Serializable is its simplicity. However, you should consider using Parcelable method if you need many data to be transferred, because Parcelable is specifically designed for Android and it is more efficient than Serializable. You can create Parcelable class using:

  1. an online tool - parcelabler
  2. a plugin for Android Studio - Android Parcelable code generator

qmake: could not find a Qt installation of ''

For others in my situation, the solution was:

qmake -qt=qt5

This was on Ubuntu 14.04 after install qt5-qmake. qmake was a symlink to qtchooser which takes the -qt argument.

How do I parse a string to a float or int?

float(x) if '.' in x else int(x)

Is there a better alternative than this to 'switch on type'?

Yes - just use the slightly weirdly named "pattern matching" from C#7 upwards to match on class or structure:

IObject concrete1 = new ObjectImplementation1();
IObject concrete2 = new ObjectImplementation2();

switch (concrete1)
{
    case ObjectImplementation1 c1: return "type 1";         
    case ObjectImplementation2 c2: return "type 2";         
}

JAVA_HOME directory in Linux

http://www.gnu.org/software/sed/manual/html_node/Print-bash-environment.html#Print-bash-environment

If you really want to get some info about your BASH put that script in your .bashrc and watch it fly by. You can scroll around and look it over.

Add Variables to Tuple

Another tactic not yet mentioned is using appending to a list, and then converting the list to a tuple at the end:

mylist = []
for x in range(5):
    mylist.append(x)
mytuple = tuple(mylist)
print mytuple

returns

(0, 1, 2, 3, 4)

I sometimes use this when I have to pass a tuple as a function argument, which is often necessary for the numpy functions.

How to get thread id from a thread pool?

There is the way of current thread getting:

Thread t = Thread.currentThread();

After you have got Thread class object (t) you are able to get information you need using Thread class methods.

Thread ID gettting:

long tId = t.getId(); // e.g. 14291

Thread name gettting:

String tName = t.getName(); // e.g. "pool-29-thread-7"

define a List like List<int,string>?

You could use an immutable struct

public struct Data
{
    public Data(int intValue, string strValue)
    {
        IntegerData = intValue;
        StringData = strValue;
    }

    public int IntegerData { get; private set; }
    public string StringData { get; private set; }
}

var list = new List<Data>();

Or a KeyValuePair<int, string>

using Data = System.Collections.Generic.KeyValuePair<int, string>
...
var list = new List<Data>();
list.Add(new Data(12345, "56789"));

How do I install the babel-polyfill library?

The Babel docs describe this pretty concisely:

Babel includes a polyfill that includes a custom regenerator runtime and core.js.

This will emulate a full ES6 environment. This polyfill is automatically loaded when using babel-node and babel/register.

Make sure you require it at the entry-point to your application, before anything else is called. If you're using a tool like webpack, that becomes pretty simple (you can tell webpack to include it in the bundle).

If you're using a tool like gulp-babel or babel-loader, you need to also install the babel package itself to use the polyfill.

Also note that for modules that affect the global scope (polyfills and the like), you can use a terse import to avoid having unused variables in your module:

import 'babel/polyfill';

Algorithm to compare two images

These are simply ideas I've had thinking about the problem, never tried it but I like thinking about problems like this!

Before you begin

Consider normalising the pictures, if one is a higher resolution than the other, consider the option that one of them is a compressed version of the other, therefore scaling the resolution down might provide more accurate results.

Consider scanning various prospective areas of the image that could represent zoomed portions of the image and various positions and rotations. It starts getting tricky if one of the images are a skewed version of another, these are the sort of limitations you should identify and compromise on.

Matlab is an excellent tool for testing and evaluating images.

Testing the algorithms

You should test (at the minimum) a large human analysed set of test data where matches are known beforehand. If for example in your test data you have 1,000 images where 5% of them match, you now have a reasonably reliable benchmark. An algorithm that finds 10% positives is not as good as one that finds 4% of positives in our test data. However, one algorithm may find all the matches, but also have a large 20% false positive rate, so there are several ways to rate your algorithms.

The test data should attempt to be designed to cover as many types of dynamics as possible that you would expect to find in the real world.

It is important to note that each algorithm to be useful must perform better than random guessing, otherwise it is useless to us!

You can then apply your software into the real world in a controlled way and start to analyse the results it produces. This is the sort of software project which can go on for infinitum, there are always tweaks and improvements you can make, it is important to bear that in mind when designing it as it is easy to fall into the trap of the never ending project.

Colour Buckets

With two pictures, scan each pixel and count the colours. For example you might have the 'buckets':

white
red
blue
green
black

(Obviously you would have a higher resolution of counters). Every time you find a 'red' pixel, you increment the red counter. Each bucket can be representative of spectrum of colours, the higher resolution the more accurate but you should experiment with an acceptable difference rate.

Once you have your totals, compare it to the totals for a second image. You might find that each image has a fairly unique footprint, enough to identify matches.

Edge detection

How about using Edge Detection. alt text
(source: wikimedia.org)

With two similar pictures edge detection should provide you with a usable and fairly reliable unique footprint.

Take both pictures, and apply edge detection. Maybe measure the average thickness of the edges and then calculate the probability the image could be scaled, and rescale if necessary. Below is an example of an applied Gabor Filter (a type of edge detection) in various rotations.

alt text

Compare the pictures pixel for pixel, count the matches and the non matches. If they are within a certain threshold of error, you have a match. Otherwise, you could try reducing the resolution up to a certain point and see if the probability of a match improves.

Regions of Interest

Some images may have distinctive segments/regions of interest. These regions probably contrast highly with the rest of the image, and are a good item to search for in your other images to find matches. Take this image for example:

alt text
(source: meetthegimp.org)

The construction worker in blue is a region of interest and can be used as a search object. There are probably several ways you could extract properties/data from this region of interest and use them to search your data set.

If you have more than 2 regions of interest, you can measure the distances between them. Take this simplified example:

alt text
(source: per2000.eu)

We have 3 clear regions of interest. The distance between region 1 and 2 may be 200 pixels, between 1 and 3 400 pixels, and 2 and 3 200 pixels.

Search other images for similar regions of interest, normalise the distance values and see if you have potential matches. This technique could work well for rotated and scaled images. The more regions of interest you have, the probability of a match increases as each distance measurement matches.

It is important to think about the context of your data set. If for example your data set is modern art, then regions of interest would work quite well, as regions of interest were probably designed to be a fundamental part of the final image. If however you are dealing with images of construction sites, regions of interest may be interpreted by the illegal copier as ugly and may be cropped/edited out liberally. Keep in mind common features of your dataset, and attempt to exploit that knowledge.

Morphing

Morphing two images is the process of turning one image into the other through a set of steps:

alt text

Note, this is different to fading one image into another!

There are many software packages that can morph images. It's traditionaly used as a transitional effect, two images don't morph into something halfway usually, one extreme morphs into the other extreme as the final result.

Why could this be useful? Dependant on the morphing algorithm you use, there may be a relationship between similarity of images, and some parameters of the morphing algorithm.

In a grossly over simplified example, one algorithm might execute faster when there are less changes to be made. We then know there is a higher probability that these two images share properties with each other.

This technique could work well for rotated, distorted, skewed, zoomed, all types of copied images. Again this is just an idea I have had, it's not based on any researched academia as far as I am aware (I haven't look hard though), so it may be a lot of work for you with limited/no results.

Zipping

Ow's answer in this question is excellent, I remember reading about these sort of techniques studying AI. It is quite effective at comparing corpus lexicons.

One interesting optimisation when comparing corpuses is that you can remove words considered to be too common, for example 'The', 'A', 'And' etc. These words dilute our result, we want to work out how different the two corpus are so these can be removed before processing. Perhaps there are similar common signals in images that could be stripped before compression? It might be worth looking into.

Compression ratio is a very quick and reasonably effective way of determining how similar two sets of data are. Reading up about how compression works will give you a good idea why this could be so effective. For a fast to release algorithm this would probably be a good starting point.

Transparency

Again I am unsure how transparency data is stored for certain image types, gif png etc, but this will be extractable and would serve as an effective simplified cut out to compare with your data sets transparency.

Inverting Signals

An image is just a signal. If you play a noise from a speaker, and you play the opposite noise in another speaker in perfect sync at the exact same volume, they cancel each other out.

alt text
(source: themotorreport.com.au)

Invert on of the images, and add it onto your other image. Scale it/loop positions repetitively until you find a resulting image where enough of the pixels are white (or black? I'll refer to it as a neutral canvas) to provide you with a positive match, or partial match.

However, consider two images that are equal, except one of them has a brighten effect applied to it:

alt text
(source: mcburrz.com)

Inverting one of them, then adding it to the other will not result in a neutral canvas which is what we are aiming for. However, when comparing the pixels from both original images, we can definatly see a clear relationship between the two.

I haven't studied colour for some years now, and am unsure if the colour spectrum is on a linear scale, but if you determined the average factor of colour difference between both pictures, you can use this value to normalise the data before processing with this technique.

Tree Data structures

At first these don't seem to fit for the problem, but I think they could work.

You could think about extracting certain properties of an image (for example colour bins) and generate a huffman tree or similar data structure. You might be able to compare two trees for similarity. This wouldn't work well for photographic data for example with a large spectrum of colour, but cartoons or other reduced colour set images this might work.

This probably wouldn't work, but it's an idea. The trie datastructure is great at storing lexicons, for example a dictionarty. It's a prefix tree. Perhaps it's possible to build an image equivalent of a lexicon, (again I can only think of colours) to construct a trie. If you reduced say a 300x300 image into 5x5 squares, then decompose each 5x5 square into a sequence of colours you could construct a trie from the resulting data. If a 2x2 square contains:

FFFFFF|000000|FDFD44|FFFFFF

We have a fairly unique trie code that extends 24 levels, increasing/decreasing the levels (IE reducing/increasing the size of our sub square) may yield more accurate results.

Comparing trie trees should be reasonably easy, and could possible provide effective results.

More ideas

I stumbled accross an interesting paper breif about classification of satellite imagery, it outlines:

Texture measures considered are: cooccurrence matrices, gray-level differences, texture-tone analysis, features derived from the Fourier spectrum, and Gabor filters. Some Fourier features and some Gabor filters were found to be good choices, in particular when a single frequency band was used for classification.

It may be worth investigating those measurements in more detail, although some of them may not be relevant to your data set.

Other things to consider

There are probably a lot of papers on this sort of thing, so reading some of them should help although they can be very technical. It is an extremely difficult area in computing, with many fruitless hours of work spent by many people attempting to do similar things. Keeping it simple and building upon those ideas would be the best way to go. It should be a reasonably difficult challenge to create an algorithm with a better than random match rate, and to start improving on that really does start to get quite hard to achieve.

Each method would probably need to be tested and tweaked thoroughly, if you have any information about the type of picture you will be checking as well, this would be useful. For example advertisements, many of them would have text in them, so doing text recognition would be an easy and probably very reliable way of finding matches especially when combined with other solutions. As mentioned earlier, attempt to exploit common properties of your data set.

Combining alternative measurements and techniques each that can have a weighted vote (dependant on their effectiveness) would be one way you could create a system that generates more accurate results.

If employing multiple algorithms, as mentioned at the begining of this answer, one may find all the positives but have a false positive rate of 20%, it would be of interest to study the properties/strengths/weaknesses of other algorithms as another algorithm may be effective in eliminating false positives returned from another.

Be careful to not fall into attempting to complete the never ending project, good luck!

Node.js Write a line into a .txt file

Simply use fs module and something like this:

fs.appendFile('server.log', 'string to append', function (err) {
   if (err) return console.log(err);
   console.log('Appended!');
});

Basic calculator in Java

CompareStrings with equals(..) not with ==

if (operation.equals("+")
{
    System.out.println("your answer is" + (num1 + num2));
}
if (operation.equals("-"))
{
    System.out.println("your answer is" + (num1 - num2));
}
if (operation.equals("/"))
{
    System.out.println("your answer is" + (num1 / num2));
}
if (operation .equals( "*"))
{
    System.out.println("your answer is" + (num1 * num2));
}

And the ; after the conditions was an empty statement so the conditon had no effect at all.

If you use java 7 you can also replace the if statements with a switch.
In java <7 you can test, if operation has length 1 and than make a switch for the char [switch (operation.charAt(0))]

SVN Error: Commit blocked by pre-commit hook (exit code 1) with output: Error: n/a (6)

This happened to me, and it was caused the absence of a comment (should say "comment required" instead of this enigmatic error at first, right...)

CSS Flex Box Layout: full-width row and columns

This is copied from above, but condensed slightly and re-written in semantic terms. Note: #Container has display: flex; and flex-direction: column;, while the columns have flex: 3; and flex: 2; (where "One value, unitless number" determines the flex-grow property) per MDN flex docs.

_x000D_
_x000D_
#Container {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  height: 600px;_x000D_
  width: 580px;_x000D_
}_x000D_
_x000D_
.Content {_x000D_
  display: flex;_x000D_
  flex: 1;_x000D_
}_x000D_
_x000D_
#Detail {_x000D_
  flex: 3;_x000D_
  background-color: lime;_x000D_
}_x000D_
_x000D_
#ThumbnailContainer {_x000D_
  flex: 2;_x000D_
  background-color: black;_x000D_
}
_x000D_
<div id="Container">_x000D_
  <div class="Content">_x000D_
    <div id="Detail"></div>_x000D_
    <div id="ThumbnailContainer"></div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Android webview & localStorage

The following was missing:

settings.setDomStorageEnabled(true);

findAll() in yii

Another simple way get by using findall in yii

$id =101; 
$comments = EmailArchive::model()->findAll(array("condition"=>"':email_id'=$id"));
foreach($comments as $comments_1) 
{ 
echo  "email:".$comments_1['email_id'];
}

Can we cast a generic object to a custom object type in javascript?

No.

But if you're looking to treat your person1 object as if it were a Person, you can call methods on Person's prototype on person1 with call:

Person.prototype.getFullNamePublic = function(){
    return this.lastName + ' ' + this.firstName;
}
Person.prototype.getFullNamePublic.call(person1);

Though this obviously won't work for privileged methods created inside of the Person constructor—like your getFullName method.

Doctrine 2 ArrayCollection filter method

Your use case would be :

    $ArrayCollectionOfActiveUsers = $customer->users->filter(function($user) {
                        return $user->getActive() === TRUE;
                    });

if you add ->first() you'll get only the first entry returned, which is not what you want.

@ Sjwdavies You need to put () around the variable you pass to USE. You can also shorten as in_array return's a boolean already:

    $member->getComments()->filter( function($entry) use ($idsToFilter) {
        return in_array($entry->getId(), $idsToFilter);
    });

version `CXXABI_1.3.8' not found (required by ...)

GCC 4.9 introduces a newer C++ ABI version than your system libstdc++ has, so you need to tell the loader to use this newer version of the library by adding that path to LD_LIBRARY_PATH. Unfortunately, I cannot tell you straight off where the libstdc++ so for your GCC 4.9 installation is located, as this depends on how you configured GCC. So you need something in the style of:

export LD_LIBRARY_PATH=/home/user/lib/gcc-4.9.0/lib:/home/user/lib/boost_1_55_0/stage/lib:$LD_LIBRARY_PATH

Note the actual path may be different (there might be some subdirectory hidden under there, like `x86_64-unknown-linux-gnu/4.9.0´ or similar).

How to get the full URL of a Drupal page?

You can also do it this way:

$current_url = 'http://' .$_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

It's a bit faster.

UITableView, Separator color where to set?

Now you should be able to do it directly in the IB.

Not sure though, if this was available when the question was posted originally.

enter image description here

What is the simplest way to write the contents of a StringBuilder to a text file in .NET 1.1?

I know this is an old post and that it wants an answer for .NET 1.1 but there's already a very good answer for that. I thought it would be good to have an answer for those people who land on this post that may have a more recent version of the .Net framework, such as myself when I went looking for an answer to the same question.

In those cases there is an even simpler way to write the contents of a StringBuilder to a text file. It can be done with one line of code. It may not be the most efficient but that wasn't really the question now was it.

System.IO.File.WriteAllText(@"C:\MyDir\MyNewTextFile.txt",sbMyStringBuilder.ToString());

Compiling an application for use in highly radioactive environments

NASA has a paper on radiation-hardened software. It describes three main tasks:

  1. Regular monitoring of memory for errors then scrubbing out those errors,
  2. robust error recovery mechanisms, and
  3. the ability to reconfigure if something no longer works.

Note that the memory scan rate should be frequent enough that multi-bit errors rarely occur, as most ECC memory can recover from single-bit errors, not multi-bit errors.

Robust error recovery includes control flow transfer (typically restarting a process at a point before the error), resource release, and data restoration.

Their main recommendation for data restoration is to avoid the need for it, through having intermediate data be treated as temporary, so that restarting before the error also rolls back the data to a reliable state. This sounds similar to the concept of "transactions" in databases.

They discuss techniques particularly suitable for object-oriented languages such as C++. For example

  1. Software-based ECCs for contiguous memory objects
  2. Programming by Contract: verifying preconditions and postconditions, then checking the object to verify it is still in a valid state.

And, it just so happens, NASA has used C++ for major projects such as the Mars Rover.

C++ class abstraction and encapsulation enabled rapid development and testing among multiple projects and developers.

They avoided certain C++ features that could create problems:

  1. Exceptions
  2. Templates
  3. Iostream (no console)
  4. Multiple inheritance
  5. Operator overloading (other than new and delete)
  6. Dynamic allocation (used a dedicated memory pool and placement new to avoid the possibility of system heap corruption).

Difference between e.target and e.currentTarget

e.target is what triggers the event dispatcher to trigger and e.currentTarget is what you assigned your listener to.

Base64: java.lang.IllegalArgumentException: Illegal character

Just use the below code to resolve this:

JsonObject obj = Json.createReader(new ByteArrayInputStream(Base64.getDecoder().decode(accessToken.split("\\.")[1].
                        replace('-', '+').replace('_', '/')))).readObject();

In the above code replace('-', '+').replace('_', '/') did the job. For more details see the https://jwt.io/js/jwt.js. I understood the problem from the part of the code got from that link:

function url_base64_decode(str) {
  var output = str.replace(/-/g, '+').replace(/_/g, '/');
  switch (output.length % 4) {
    case 0:
      break;
    case 2:
      output += '==';
      break;
    case 3:
      output += '=';
      break;
    default:
      throw 'Illegal base64url string!';
  }
  var result = window.atob(output); //polifyll https://github.com/davidchambers/Base64.js
  try{
    return decodeURIComponent(escape(result));
  } catch (err) {
    return result;
  }
}

Flatten List in LINQ

Like this?

var iList = Method().SelectMany(n => n);

How do I install Keras and Theano in Anaconda Python on Windows?

Anaconda with Windows

  • Run anaconda prompt with administrator privilages
  • conda update conda
  • conda update --all
  • conda install mingw libpython
  • conda install theano

After conda commands it's required to accept process - Proceed ([y]/n)?

How do I find the authoritative name-server for a domain name?

I found that the best way it to add always the +trace option:

dig SOA +trace stackoverflow.com

It works also with recursive CNAME hosted in different provider. +trace trace imply +norecurse so the result is just for the domain you specify.

BeanFactory vs ApplicationContext

To me, the primary difference to choose BeanFactory over ApplicationContext seems to be that ApplicationContext will pre-instantiate all of the beans. From the Spring docs:

Spring sets properties and resolves dependencies as late as possible, when the bean is actually created. This means that a Spring container which has loaded correctly can later generate an exception when you request an object if there is a problem creating that object or one of its dependencies. For example, the bean throws an exception as a result of a missing or invalid property. This potentially delayed visibility of some configuration issues is why ApplicationContext implementations by default pre-instantiate singleton beans. At the cost of some upfront time and memory to create these beans before they are actually needed, you discover configuration issues when the ApplicationContext is created, not later. You can still override this default behavior so that singleton beans will lazy-initialize, rather than be pre-instantiated.

Given this, I initially chose BeanFactory for use in integration/performance tests since I didn't want to load the entire application for testing isolated beans. However -- and somebody correct me if I'm wrong -- BeanFactory doesn't support classpath XML configuration. So BeanFactory and ApplicationContext each provide a crucial feature I wanted, but neither did both.

Near as I can tell, the note in the documentation about overriding default instantiation behavior takes place in the configuration, and it's per-bean, so I can't just set the "lazy-init" attribute in the XML file or I'm stuck maintaining a version of it for test and one for deployment.

What I ended up doing was extending ClassPathXmlApplicationContext to lazily load beans for use in tests like so:

public class LazyLoadingXmlApplicationContext extends ClassPathXmlApplicationContext {

    public LazyLoadingXmlApplicationContext(String[] configLocations) {
        super(configLocations);
    }

    /**
     * Upon loading bean definitions, force beans to be lazy-initialized.
     * @see org.springframework.context.support.AbstractXmlApplicationContext#loadBeanDefinitions(org.springframework.beans.factory.xml.XmlBeanDefinitionReader)
     */

    @Override
    protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws IOException {
        super.loadBeanDefinitions(reader);
        for (String name: reader.getBeanFactory().getBeanDefinitionNames()) {
            AbstractBeanDefinition beanDefinition = (AbstractBeanDefinition) reader.getBeanFactory().getBeanDefinition(name);
            beanDefinition.setLazyInit(true);
        }
    }

}

How to install a certificate in Xcode (preparing for app store submission)

Under

Provisioning -> Distribution -> Distribution Provisioning Profiles

I downloaded the desired certificate again and installed it. Now I don't see an empty file in Xcode. The build also works now (no code sign error).

What I also did: I downloaded the WWDR and installed it, but I don't know if that was the reason (because I think it's always the same)

How to remove constraints from my MySQL table?

Some ORM's or frameworks use a different naming convention for foreign keys than the default FK_[parent table]_[referenced table]_[referencing field], because they can be altered.

Laravel for example uses [parent table]_[referencing field]_foreign as naming convention. You can show the names of the foreign keys by using this query, as shown here:

SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE 
WHERE REFERENCED_TABLE_SCHEMA = '<database>' AND REFERENCED_TABLE_NAME = '<table>';

Then remove the foreign key by running the before mentioned DROP FOREIGN KEY query and its proper name.

Bootstrap 3 - Set Container Width to 940px Maximum for Desktops?

The best option is to use the original LESS version of bootstrap (get it from github).

Open variables.less and look for // Media queries breakpoints

Find this code and change the breakpoint value:

// Large screen / wide desktop
@screen-lg:                  1200px; // change this
@screen-lg-desktop:          @screen-lg;

Change it to 9999px for example, and this will prevent the breakpoint to be reached, so your site will always load the previous media query which has 940px container

UPDATE if exists else INSERT in SQL Server 2008

Many people will suggest you use MERGE, but I caution you against it. By default, it doesn't protect you from concurrency and race conditions any more than multiple statements, but it does introduce other dangers:

http://www.mssqltips.com/sqlservertip/3074/use-caution-with-sql-servers-merge-statement/

Even with this "simpler" syntax available, I still prefer this approach (error handling omitted for brevity):

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
UPDATE dbo.table SET ... WHERE PK = @PK;
IF @@ROWCOUNT = 0
BEGIN
  INSERT dbo.table(PK, ...) SELECT @PK, ...;
END
COMMIT TRANSACTION;

A lot of folks will suggest this way:

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
IF EXISTS (SELECT 1 FROM dbo.table WHERE PK = @PK)
BEGIN
  UPDATE ...
END
ELSE
BEGIN
  INSERT ...
END
COMMIT TRANSACTION;

But all this accomplishes is ensuring you may need to read the table twice to locate the row(s) to be updated. In the first sample, you will only ever need to locate the row(s) once. (In both cases, if no rows are found from the initial read, an insert occurs.)

Others will suggest this way:

BEGIN TRY
  INSERT ...
END TRY
BEGIN CATCH
  IF ERROR_NUMBER() = 2627
    UPDATE ...
END CATCH

However, this is problematic if for no other reason than letting SQL Server catch exceptions that you could have prevented in the first place is much more expensive, except in the rare scenario where almost every insert fails. I prove as much here:

Not sure what you think you gain by having a single statement; I don't think you gain anything. MERGE is a single statement but it still has to really perform multiple operations anyway - even though it makes you think it doesn't.

How to include js file in another js file?

I disagree with the document.write technique (see suggestion of Vahan Margaryan). I like document.getElementsByTagName('head')[0].appendChild(...) (see suggestion of Matt Ball), but there is one important issue: the script execution order.

Recently, I have spent a lot of time reproducing one similar issue, and even the well-known jQuery plugin uses the same technique (see src here) to load the files, but others have also reported the issue. Imagine you have JavaScript library which consists of many scripts, and one loader.js loads all the parts. Some parts are dependent on one another. Imagine you include another main.js script per <script> which uses the objects from loader.js immediately after the loader.js. The issue was that sometimes main.js is executed before all the scripts are loaded by loader.js. The usage of $(document).ready(function () {/*code here*/}); inside of main.js script does not help. The usage of cascading onload event handler in the loader.js will make the script loading sequential instead of parallel, and will make it difficult to use main.js script, which should just be an include somewhere after loader.js.

By reproducing the issue in my environment, I can see that **the order of execution of the scripts in Internet Explorer 8 can differ in the inclusion of the JavaScript*. It is a very difficult issue if you need include scripts that are dependent on one another. The issue is described in Loading Javascript files in parallel, and the suggested workaround is to use document.writeln:

document.writeln("<script type='text/javascript' src='Script1.js'></script>");
document.writeln("<script type='text/javascript' src='Script2.js'></script>");

So in the case of "the scripts are downloaded in parallel but executed in the order they're written to the page", after changing from document.getElementsByTagName('head')[0].appendChild(...) technique to document.writeln, I had not seen the issue anymore.

So I recommend that you use document.writeln.

UPDATED: If somebody is interested, they can try to load (and reload) the page in Internet Explorer (the page uses the document.getElementsByTagName('head')[0].appendChild(...) technique), and then compare with the fixed version used document.writeln. (The code of the page is relatively dirty and is not from me, but it can be used to reproduce the issue).

Determine if Android app is being used for the first time

    /**
     * @author ALGO
     */
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.RandomAccessFile;
    import java.util.UUID;

    import android.content.Context;

    public class Util {
        // ===========================================================
        //
        // ===========================================================

        private static final String INSTALLATION = "INSTALLATION";

        public synchronized static boolean isFirstLaunch(Context context) {
            String sID = null;
            boolean launchFlag = false;
            if (sID == null) {
                File installation = new File(context.getFilesDir(), INSTALLATION);
                try {
                    if (!installation.exists()) {

                        writeInstallationFile(installation);
                    }
                    sID = readInstallationFile(installation);
launchFlag = true;
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
            return launchFlag;
        }

        private static String readInstallationFile(File installation) throws IOException {
            RandomAccessFile f = new RandomAccessFile(installation, "r");// read only mode
            byte[] bytes = new byte[(int) f.length()];
            f.readFully(bytes);
            f.close();

            return new String(bytes);
        }

        private static void writeInstallationFile(File installation) throws IOException {
            FileOutputStream out = new FileOutputStream(installation);
            String id = UUID.randomUUID().toString();
            out.write(id.getBytes());
            out.close();
        }
    }

> Usage (in class extending android.app.Activity)

Util.isFirstLaunch(this);

Run reg command in cmd (bat file)?

In command line it's better to use REG tool rather than REGEDIT:

REG IMPORT yourfile.reg

REG is designed for console mode, while REGEDIT is for graphical mode. This is why running regedit.exe /S yourfile.reg is a bad idea, since you will not be notified if the there's an error, whereas REG Tool will prompt:

>  REG IMPORT missing_file.reg

ERROR: Error opening the file. There may be a disk or file system error.

>  %windir%\System32\reg.exe /?

REG Operation [Parameter List]

  Operation  [ QUERY   | ADD    | DELETE  | COPY    |
               SAVE    | LOAD   | UNLOAD  | RESTORE |
               COMPARE | EXPORT | IMPORT  | FLAGS ]

Return Code: (Except for REG COMPARE)

  0 - Successful
  1 - Failed

For help on a specific operation type:

  REG Operation /?

Examples:

  REG QUERY /?
  REG ADD /?
  REG DELETE /?
  REG COPY /?
  REG SAVE /?
  REG RESTORE /?
  REG LOAD /?
  REG UNLOAD /?
  REG COMPARE /?
  REG EXPORT /?
  REG IMPORT /?
  REG FLAGS /?

How do I inject a controller into another controller in AngularJS

If your intention is to get hold of already instantiated controller of another component and that if you are following component/directive based approach you can always require a controller (instance of a component) from a another component that follows a certain hierarchy.

For example:

//some container component that provides a wizard and transcludes the page components displayed in a wizard
myModule.component('wizardContainer', {
  ...,
  controller : function WizardController() {
    this.disableNext = function() { 
      //disable next step... some implementation to disable the next button hosted by the wizard
    }
  },
  ...
});

//some child component
myModule.component('onboardingStep', {
 ...,
 controller : function OnboadingStepController(){

    this.$onInit = function() {
      //.... you can access this.container.disableNext() function
    }

    this.onChange = function(val) {
      //..say some value has been changed and it is not valid i do not want wizard to enable next button so i call container's disable method i.e
      if(notIsValid(val)){
        this.container.disableNext();
      }
    }
 },
 ...,
 require : {
    container: '^^wizardContainer' //Require a wizard component's controller which exist in its parent hierarchy.
 },
 ...
});

Now the usage of these above components might be something like this:

<wizard-container ....>
<!--some stuff-->
...
<!-- some where there is this page that displays initial step via child component -->

<on-boarding-step ...>
 <!--- some stuff-->
</on-boarding-step>
...
<!--some stuff-->
</wizard-container>

There are many ways you can set up require.

(no prefix) - Locate the required controller on the current element. Throw an error if not found.

? - Attempt to locate the required controller or pass null to the link fn if not found.

^ - Locate the required controller by searching the element and its parents. Throw an error if not found.

^^ - Locate the required controller by searching the element's parents. Throw an error if not found.

?^ - Attempt to locate the required controller by searching the element and its parents or pass null to the link fn if not found.

?^^ - Attempt to locate the required controller by searching the element's parents, or pass null to the link fn if not found.



Old Answer:

You need to inject $controller service to instantiate a controller inside another controller. But be aware that this might lead to some design issues. You could always create reusable services that follows Single Responsibility and inject them in the controllers as you need.

Example:

app.controller('TestCtrl2', ['$scope', '$controller', function ($scope, $controller) {
   var testCtrl1ViewModel = $scope.$new(); //You need to supply a scope while instantiating.
   //Provide the scope, you can also do $scope.$new(true) in order to create an isolated scope.
   //In this case it is the child scope of this scope.
   $controller('TestCtrl1',{$scope : testCtrl1ViewModel });
   testCtrl1ViewModel.myMethod(); //And call the method on the newScope.
}]);

In any case you cannot call TestCtrl1.myMethod() because you have attached the method on the $scope and not on the controller instance.

If you are sharing the controller, then it would always be better to do:-

.controller('TestCtrl1', ['$log', function ($log) {
    this.myMethod = function () {
        $log.debug("TestCtrl1 - myMethod");
    }
}]);

and while consuming do:

.controller('TestCtrl2', ['$scope', '$controller', function ($scope, $controller) {
     var testCtrl1ViewModel = $controller('TestCtrl1');
     testCtrl1ViewModel.myMethod();
}]);

In the first case really the $scope is your view model, and in the second case it the controller instance itself.

How to present UIActionSheet iOS Swift?

Swift 3 For displaying UIAlertController from UIBarButtonItem on iPad

        let alert = UIAlertController(title: "Title", message: "Please Select an Option", preferredStyle: .actionSheet)

    alert.addAction(UIAlertAction(title: "Approve", style: .default , handler:{ (UIAlertAction)in
        print("User click Approve button")
    }))

    alert.addAction(UIAlertAction(title: "Edit", style: .default , handler:{ (UIAlertAction)in
        print("User click Edit button")
    }))

    alert.addAction(UIAlertAction(title: "Delete", style: .destructive , handler:{ (UIAlertAction)in
        print("User click Delete button")
    }))

    alert.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.cancel, handler:{ (UIAlertAction)in
        print("User click Dismiss button")
    }))

    if let presenter = alert.popoverPresentationController {
        presenter.barButtonItem = sender
    }

    self.present(alert, animated: true, completion: {
        print("completion block")
    })

Where to change default pdf page width and font size in jspdf.debug.js?

For anyone trying to this in react. There is a slight difference.

// Document of 8.5 inch width and 11 inch high
new jsPDF('p', 'in', [612, 792]);

or

// Document of 8.5 inch width and 11 inch high
new jsPDF({
        orientation: 'p', 
        unit: 'in', 
        format: [612, 792]
});

When i tried the @Aidiakapi solution the pages were tiny. For a difference size take size in inches * 72 to get the dimensions you need. For example, i wanted 8.5 so 8.5 * 72 = 612. This is for [email protected].

List of all special characters that need to be escaped in a regex

Assuming that you have and trust (to be authoritative) the list of escape characters Java regex uses (would be nice if these characters were exposed in some Pattern class member) you can use the following method to escape the character if it is indeed necessary:

private static final char[] escapeChars = { '<', '(', '[', '{', '\\', '^', '-', '=', '$', '!', '|', ']', '}', ')', '?', '*', '+', '.', '>' };

private static String regexEscape(char character) {
    for (char escapeChar : escapeChars) {
        if (character == escapeChar) {
            return "\\" + character;
        }
    }
    return String.valueOf(character);
}

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

When I got the same error on my machine ("connection is refused"), the reason was that I had defined the following on the server side:

 Naming.rebind("rmi://localhost:8080/AddService"
   ,addService); 

Thus the server binds both the IP = 127.0.0.1 and the port 8080.

But on the client side I had used:

AddServerInterface st = (AddServerInterface)Naming.lookup("rmi://localhost"
                        +"/AddService");

Thus I forgot to add the port number after the localhost, so I rewrote the above command and added the port number 8080 as follows:

AddServerInterface st = (AddServerInterface)Naming.lookup("rmi://localhost:8080"
                        +"/AddService");

and everything worked fine.

How to install plugin for Eclipse from .zip

If you are reading this because you are getting error while updating from the "Install new Software" menu, then you need to do this

  1. Go to the location from where you want to update ex. http://update.eclemma.org/
  2. Download everything in the same order just as it is on site (every folder)
  3. Go to "Install new software", but instead of pasting the url of site paste the location of your harddrive where you downloaded the contents

please note: add the suffix file:/// to the location
ex. file:///C:/Users/harry/Downloads/eclox/

Maybe not the best solution but this gets the work done :)

Using Java 8's Optional with Stream::flatMap

As my previous answer appeared not to be very popular, I will give this another go.

A short answer:

You are mostly on a right track. The shortest code to get to your desired output I could come up with is this:

things.stream()
      .map(this::resolve)
      .filter(Optional::isPresent)
      .findFirst()
      .flatMap( Function.identity() );

This will fit all your requirements:

  1. It will find first response that resolves to a nonempty Optional<Result>
  2. It calls this::resolve lazily as needed
  3. this::resolve will not be called after first non-empty result
  4. It will return Optional<Result>

Longer answer

The only modification compared to OP initial version was that I removed .map(Optional::get) before call to .findFirst() and added .flatMap(o -> o) as the last call in the chain.

This has a nice effect of getting rid of the double-Optional, whenever stream finds an actual result.

You can't really go any shorter than this in Java.

The alternative snippet of code using the more conventional for loop technique is going to be about same number of lines of code and have more or less same order and number of operations you need to perform:

  1. Calling this.resolve,
  2. filtering based on Optional.isPresent
  3. returning the result and
  4. some way of dealing with negative result (when nothing was found)

Just to prove that my solution works as advertised, I wrote a small test program:

public class StackOverflow {

    public static void main( String... args ) {
        try {
            final int integer = Stream.of( args )
                    .peek( s -> System.out.println( "Looking at " + s ) )
                    .map( StackOverflow::resolve )
                    .filter( Optional::isPresent )
                    .findFirst()
                    .flatMap( o -> o )
                    .orElseThrow( NoSuchElementException::new )
                    .intValue();

            System.out.println( "First integer found is " + integer );
        }
        catch ( NoSuchElementException e ) {
            System.out.println( "No integers provided!" );
        }
    }

    private static Optional<Integer> resolve( String string ) {
        try {
            return Optional.of( Integer.valueOf( string ) );
        }
        catch ( NumberFormatException e )
        {
            System.out.println( '"' + string + '"' + " is not an integer");
            return Optional.empty();
        }
    }

}

(It does have few extra lines for debugging and verifying that only as many calls to resolve as needed...)

Executing this on a command line, I got the following results:

$ java StackOferflow a b 3 c 4
Looking at a
"a" is not an integer
Looking at b
"b" is not an integer
Looking at 3
First integer found is 3

Exporting result of select statement to CSV format in DB2

DBeaver allows you connect to a DB2 database, run a query, and export the result-set to a CSV file that can be opened and fine-tuned in MS Excel or LibreOffice Calc.

To do this, all you have to do (in DBeaver) is right-click on the results grid (after running the query) and select "Export Resultset" from the context-menu.

This produces the dialog below, where you can ultimately save the result-set to a file as CSV, XML, or HTML:

enter image description here

How can I slice an ArrayList out of an ArrayList in Java?

This is how I solved it. I forgot that sublist was a direct reference to the elements in the original list, so it makes sense why it wouldn't work.

ArrayList<Integer> inputA = new ArrayList<Integer>(input.subList(0, input.size()/2));

Eclipse: The resource is not on the build path of a Java project

You can add the src folder to build path by:

  1. Select Java perspective.
  2. Right click on src folder.
  3. Select Build Path > Use a source folder.

And you are done. Hope this help.

EDIT: Refer to the Eclipse documentation

How to slice an array in Bash

See the Parameter Expansion section in the Bash man page. A[@] returns the contents of the array, :1:2 takes a slice of length 2, starting at index 1.

A=( foo bar "a  b c" 42 )
B=("${A[@]:1:2}")
C=("${A[@]:1}")       # slice to the end of the array
echo "${B[@]}"        # bar a  b c
echo "${B[1]}"        # a  b c
echo "${C[@]}"        # bar a  b c 42
echo "${C[@]: -2:2}"  # a  b c 42 # The space before the - is necesssary

Note that the fact that "a b c" is one array element (and that it contains an extra space) is preserved.

Raise error in a Bash script

This depends on where you want the error message be stored.

You can do the following:

echo "Error!" > logfile.log
exit 125

Or the following:

echo "Error!" 1>&2
exit 64

When you raise an exception you stop the program's execution.

You can also use something like exit xxx where xxx is the error code you may want to return to the operating system (from 0 to 255). Here 125 and 64 are just random codes you can exit with. When you need to indicate to the OS that the program stopped abnormally (eg. an error occurred), you need to pass a non-zero exit code to exit.

As @chepner pointed out, you can do exit 1, which will mean an unspecified error.

Better way of getting time in milliseconds in javascript?

As far that I know you only can get time with Date.

Date.now is the solution but is not available everywhere : https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/now.

var currentTime = +new Date();

This gives you the current time in milliseconds.

For your jumps. If you compute interpolations correctly according to the delta frame time and you don't have some rounding number error, I bet for the garbage collector (GC).

If there is a lot of created temporary object in your loop, garbage collection has to lock the thread to make some cleanup and memory re-organization.

With Chrome you can see how much time the GC is spending in the Timeline panel.

EDIT: Since my answer, Date.now() should be considered as the best option as it is supported everywhere and on IE >= 9.

Deleting a file in VBA

I'll probably get flamed for this, but what is the point of testing for existence if you are just going to delete it? One of my major pet peeves is an app throwing an error dialog with something like "Could not delete file, it does not exist!"

On Error Resume Next
aFile = "c:\file_to_delete.txt"
Kill aFile
On Error Goto 0
return Len(Dir$(aFile)) > 0 ' Make sure it actually got deleted.

If the file doesn't exist in the first place, mission accomplished!

How to view user privileges using windows cmd?

I'd start with:

secedit /export /areas USER_RIGHTS /cfg OUTFILE.CFG

Then examine the line for the relevant privilege. However, the problem now is that the accounts are listed as SIDs, not usernames.

Python Flask, how to set content type

Usually you don’t have to create the Response object yourself because make_response() will take care of that for you.

from flask import Flask, make_response                                      
app = Flask(__name__)                                                       

@app.route('/')                                                             
def index():                                                                
    bar = '<body>foo</body>'                                                
    response = make_response(bar)                                           
    response.headers['Content-Type'] = 'text/xml; charset=utf-8'            
    return response

One more thing, it seems that no one mentioned the after_this_request, I want to say something:

after_this_request

Executes a function after this request. This is useful to modify response objects. The function is passed the response object and has to return the same or a new one.

so we can do it with after_this_request, the code should look like this:

from flask import Flask, after_this_request
app = Flask(__name__)

@app.route('/')
def index():
    @after_this_request
    def add_header(response):
        response.headers['Content-Type'] = 'text/xml; charset=utf-8'
        return response
    return '<body>foobar</body>'

Java substring: 'string index out of range'

It is a pity that substring is not implemented in a way that handles short strings – like in other languages e.g. Python.

Ok, we cannot change that and have to consider this edge case every time we use substr, instead of if-else clauses I would go for this shorter variant:

myText.substring(0, Math.min(6, myText.length()))

Order by multiple columns with Doctrine

The orderBy method requires either two strings or an Expr\OrderBy object. If you want to add multiple order declarations, the correct thing is to use addOrderBy method, or instantiate an OrderBy object and populate it accordingly:

   # Inside a Repository method:
   $myResults = $this->createQueryBuilder('a')
       ->addOrderBy('a.column1', 'ASC')
       ->addOrderBy('a.column2', 'ASC')
       ->addOrderBy('a.column3', 'DESC')
   ;

   # Or, using a OrderBy object:
   $orderBy = new OrderBy('a.column1', 'ASC');
   $orderBy->add('a.column2', 'ASC');
   $orderBy->add('a.column3', 'DESC');

   $myResults = $this->createQueryBuilder('a')
       ->orderBy($orderBy)
   ;

WCF - How to Increase Message Size Quota

If you're still getting this error message while using the WCF Test Client, it's because the client has a separate MaxBufferSize setting.

To correct the issue:

  1. Right-Click on the Config File node at the bottom of the tree
  2. Select Edit with SvcConfigEditor

A list of editable settings will appear, including MaxBufferSize.

Note: Auto-generated proxy clients also set MaxBufferSize to 65536 by default.

PHP Warning: Invalid argument supplied for foreach()

This means that you are doing a foreach on something that is not an array.

Check out all your foreach statements, and look if the thing before the as, to make sure it is actually an array. Use var_dump to dump it.

Then fix the one where it isn't an array.

How to reproduce this error:

<?php
$skipper = "abcd";
foreach ($skipper as $item){       //the warning happens on this line.
    print "ok";
}
?>

Make sure $skipper is an array.

Using WGET to run a cronjob PHP

wget -O- http://www.example.com/cronit.php >> /dev/null

This means send the file to stdout, and send stdout to /dev/null

How to sort a file, based on its numerical values for a field?

Take a peek at the man page for sort...

   -n, --numeric-sort
          compare according to string numerical value

So here is an example...

sort -n filename

Valid content-type for XML, HTML and XHTML documents

HTML: text/html, full-stop.

XHTML: application/xhtml+xml, or only if following HTML compatbility guidelines, text/html. See the W3 Media Types Note.

XML: text/xml, application/xml (RFC 2376).

There are also many other media types based around XML, for example application/rss+xml or image/svg+xml. It's a safe bet that any unrecognised but registered ending in +xml is XML-based. See the IANA list for registered media types ending in +xml.

(For unregistered x- types, all bets are off, but you'd hope +xml would be respected.)

How to make a transparent border using CSS?

Well if you want fully transparent than you can use

border: 5px solid transparent;

If you mean opaque/transparent, than you can use

border: 5px solid rgba(255, 255, 255, .5);

Here, a means alpha, which you can scale, 0-1.

Also some might suggest you to use opacity which does the same job as well, the only difference is it will result in child elements getting opaque too, yes, there are some work arounds but rgba seems better than using opacity.

For older browsers, always declare the background color using #(hex) just as a fall back, so that if old browsers doesn't recognize the rgba, they will apply the hex color to your element.

Demo

Demo 2 (With a background image for nested div)

Demo 3 (With an img tag instead of a background-image)

body {
    background: url(http://www.desktopas.com/files/2013/06/Images-1920x1200.jpg);   
}

div.wrap {
    border: 5px solid #fff; /* Fall back, not used in fiddle */
    border: 5px solid rgba(255, 255, 255, .5);
    height: 400px;
    width: 400px;
    margin: 50px;
    border-radius: 50%;
}

div.inner {
    background: #fff; /* Fall back, not used in fiddle */
    background: rgba(255, 255, 255, .5);
    height: 380px;
    width: 380px;
    border-radius: 50%; 
    margin: auto; /* Horizontal Center */
    margin-top: 10px; /* Vertical Center ... Yea I know, that's 
                         manually calculated*/
}

Note (For Demo 3): Image will be scaled according to the height and width provided so make sure it doesn't break the scaling ratio.

Syntax for creating a two-dimensional array in Java

These types of arrays are known as jagged arrays in Java:

int[][] multD = new int[3][];
multD[0] = new int[3];
multD[1] = new int[2];
multD[2] = new int[5];

In this scenario each row of the array holds the different number of columns. In the above example, the first row will hold three columns, the second row will hold two columns, and the third row holds five columns. You can initialize this array at compile time like below:

 int[][] multD = {{2, 4, 1}, {6, 8}, {7, 3, 6, 5, 1}};

You can easily iterate all elements in your array:

for (int i = 0; i<multD.length; i++) {
    for (int j = 0; j<multD[i].length; j++) {
        System.out.print(multD[i][j] + "\t");
    }
    System.out.println();
}

nginx- duplicate default server error

Execute this at the terminal to see conflicting configurations listening to the same port:

grep -R default_server /etc/nginx

Split comma-separated values

A way to do this without Linq & Lambdas

string source = "a,b, b, c";
string[] items = source.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);

Installing Python 3 on RHEL

As of RHEL 8, you can install python3 directly from the official repositories:

$ podman run --rm -ti ubi8 bash
[root@453fc5c55104 /]# yum install python3                                                                                                                                                    
Updating Subscription Management repositories.                                                                                                                                                
Unable to read consumer identity                                                                                                                                                              
Subscription Manager is operating in container mode.                                                                                                                                          
This system is not registered to Red Hat Subscription Management. You can use subscription-manager to register.  

...

Installed:
  platform-python-pip-9.0.3-16.el8.noarch
  python3-pip-9.0.3-16.el8.noarch
  python3-setuptools-39.2.0-5.el8.noarch
  python36-3.6.8-2.module+el8.1.0+3334+5cb623d7.x86_64      

Complete!

You can even get python 3.8:

[root@453fc5c55104 /]# yum install python38
Installed:
  python38-3.8.0-6.module+el8.2.0+5978+503155c0.x86_64
  python38-libs-3.8.0-6.module+el8.2.0+5978+503155c0.x86_64                                       
  python38-pip-19.2.3-5.module+el8.2.0+5979+f9f0b1d2.noarch                                  
  python38-pip-wheel-19.2.3-5.module+el8.2.0+5979+f9f0b1d2.noarch                                 
  python38-setuptools-41.6.0-4.module+el8.2.0+5978+503155c0.noarch                           
  python38-setuptools-wheel-41.6.0-4.module+el8.2.0+5978+503155c0.noarch                          

Complete!

How to install popper.js with Bootstrap 4?

https://cdnjs.com/libraries/popper.js does not look like a right src for popper, it does not specify the file

with bootstrap 4 I am using this

<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>

and it is working perfectly fine, give it a try

Android Transparent TextView?

Hi Please try with the below color code as textview's background.

android:background="#20535252"

split string only on first instance of specified character

Nowadays String.prototype.split does indeed allow you to limit the number of splits.

str.split([separator[, limit]])

...

limit Optional

A non-negative integer limiting the number of splits. If provided, splits the string at each occurrence of the specified separator, but stops when limit entries have been placed in the array. Any leftover text is not included in the array at all.

The array may contain fewer entries than limit if the end of the string is reached before the limit is reached. If limit is 0, no splitting is performed.

caveat

It might not work the way you expect. I was hoping it would just ignore the rest of the delimiters, but instead, when it reaches the limit, it splits the remaining string again, omitting the part after the split from the return results.

let str = 'A_B_C_D_E'
const limit_2 = str.split('_', 2)
limit_2
(2) ["A", "B"]
const limit_3 = str.split('_', 3)
limit_3
(3) ["A", "B", "C"]

I was hoping for:

let str = 'A_B_C_D_E'
const limit_2 = str.split('_', 2)
limit_2
(2) ["A", "B_C_D_E"]
const limit_3 = str.split('_', 3)
limit_3
(3) ["A", "B", "C_D_E"]

How to delete a cookie using jQuery?

it is the problem of misunderstand of cookie. Browsers recognize cookie values for not just keys also compare the options path & domain. So Browsers recognize different value which cookie values that key is 'name' with server setting option(path='/'; domain='mydomain.com') and key is 'name' with no option.

Error : Index was outside the bounds of the array.

public int[] posStatus;       

public UsersInput()    
{    
    //It means postStatus will contain 9 elements from index 0 to 8. 
    this.posStatus = new int[9];   
}

int intUsersInput = 0;   

if (posStatus[intUsersInput-1] == 0) //if i input 9, it should go to 8?    
{    
    posStatus[intUsersInput-1] += 1; //set it to 1    
} 

Getting an error "fopen': This function or variable may be unsafe." when compling

This is a warning for usual. You can either disable it by

#pragma warning(disable:4996)

or simply use fopen_s like Microsoft has intended.

But be sure to use the pragma before other headers.

Convert txt to csv python script

This is how I do it:

 with open(txtfile, 'r') as infile, open(csvfile, 'w') as outfile:
        stripped = (line.strip() for line in infile)
        lines = (line.split(",") for line in stripped if line)
        writer = csv.writer(outfile)
        writer.writerows(lines)

Hope it helps!

Git - How to fix "corrupted" interactive rebase?

Once you have satisfactorily completed rebasing X number of commits , the last command must be git rebase --continue . That completes the process and exits out of the rebase mode .

Apache Name Virtual Host with SSL

As far as I know, Apache supports SNI since Version 2.2.12 Sadly the documentation does not yet reflect that change.

Go for http://wiki.apache.org/httpd/NameBasedSSLVHostsWithSNI until that is finished

How to prevent Browser cache on Angular 2 site?

You can control client cache with HTTP headers. This works in any web framework.

You can set the directives these headers to have fine grained control over how and when to enable|disable cache:

  • Cache-Control
  • Surrogate-Control
  • Expires
  • ETag (very good one)
  • Pragma (if you want to support old browsers)

Good caching is good, but very complex, in all computer systems. Take a look at https://helmetjs.github.io/docs/nocache/#the-headers for more information.

Add swipe to delete UITableViewCell

Works for me in Swift 2.0

override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    return true
}

override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {

}

override func tableView(tableView: UITableView,
    editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
    let block = UITableViewRowAction(style: .Normal, title: "Block") { action, index in
        print("Block")
        self.removeObjectAtIndexPath(indexPath, animated: true)
    }
    let delete = UITableViewRowAction(style: .Default, title: "Delete") { action, index in
        print("Delete")
        self.removeObjectAtIndexPath(indexPath, animated: true)
    }
    return [delete, block]
}

fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

I was using CMake & then added a win32 configuration. The property page showed x86 but actually when opening the vcxproj file in a text editor it was x64! Manually changing to x86 solved this.

PostgreSQL, checking date relative to "today"

You could also check using the age() function

select * from mytable where age( mydate, now() ) > '1 year';

age() wil return an interval.

For example age( '2015-09-22', now() ) will return -1 years -7 days -10:56:18.274131

See postgresql documentation

How to write log file in c#?

create a class create a object globally and call this

using System.IO;
using System.Reflection;


   public class LogWriter
{
    private string m_exePath = string.Empty;
    public LogWriter(string logMessage)
    {
        LogWrite(logMessage);
    }
    public void LogWrite(string logMessage)
    {
        m_exePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
        try
        {
            using (StreamWriter w = File.AppendText(m_exePath + "\\" + "log.txt"))
            {
                Log(logMessage, w);
            }
        }
        catch (Exception ex)
        {
        }
    }

    public void Log(string logMessage, TextWriter txtWriter)
    {
        try
        {
            txtWriter.Write("\r\nLog Entry : ");
            txtWriter.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),
                DateTime.Now.ToLongDateString());
            txtWriter.WriteLine("  :");
            txtWriter.WriteLine("  :{0}", logMessage);
            txtWriter.WriteLine("-------------------------------");
        }
        catch (Exception ex)
        {
        }
    }
}

Return from lambda forEach() in java

The return there is returning from the lambda expression rather than from the containing method. Instead of forEach you need to filter the stream:

players.stream().filter(player -> player.getName().contains(name))
       .findFirst().orElse(null);

Here filter restricts the stream to those items that match the predicate, and findFirst then returns an Optional with the first matching entry.

This looks less efficient than the for-loop approach, but in fact findFirst() can short-circuit - it doesn't generate the entire filtered stream and then extract one element from it, rather it filters only as many elements as it needs to in order to find the first matching one. You could also use findAny() instead of findFirst() if you don't necessarily care about getting the first matching player from the (ordered) stream but simply any matching item. This allows for better efficiency when there's parallelism involved.

Unit testing private methods in C#

Ermh... Came along here with exactly the same problem: Test a simple, but pivotal private method. After reading this thread, it appears to be like "I want to drill this simple hole in this simple piece of metal, and I want to make sure the quality meets the specs", and then comes "Okay, this is not to easy. First of all, there is no proper tool to do so, but you could build a gravitational-wave observatory in your garden. Read my article at http://foobar.brigther-than-einstein.org/ First, of course, you have to attend some advanced quantum physics courses, then you need tons of ultra-cool nitrogenium, and then, of course, my book available at Amazon"...

In other words...

No, first things first.

Each and every method, may it private, internal, protected, public has to be testable. There has to be a way to implement such tests without such ado as was presented here.

Why? Exactly because of the architectural mentions done so far by some contributors. Perhaps a simple reiteration of software principles may clear up some missunderstandings.

In this case, the usual suspects are: OCP, SRP, and, as always, KIS.

But wait a minute. The idea of making everything publicly available is more of less political and a kind of an attitude. But. When it comes to code, even in then Open Source Community, this is no dogma. Instead, "hiding" something is good practice to make it easier to come familiar with a certain API. You would hide, for example, the very core calculations of your new-to-market digital thermometer building block--not to hide the maths behind the real measured curve to curious code readers, but to prevent your code from becoming dependent on some, perhaps suddenly important users who could not resist using your formerly private, internal, protected code to implement their own ideas.

What am I talking about?

private double TranslateMeasurementIntoLinear(double actualMeasurement);

It's easy to proclaim the Age of Aquarius or what is is been called nowadays, but if my piece of sensor gets from 1.0 to 2.0, the implementation of Translate... might change from a simple linear equation that is easily understandable and "re-usable" for everybody, to a pretty sophisticated calculation that uses analysis or whatever, and so I would break other's code. Why? Because they didn't understand the very priciples of software coding, not even KIS.

To make this fairy tale short: We need a simple way to test private methods--without ado.

First: Happy new year everyone!

Second: Rehearse your architect lessons.

Third: The "public" modifier is religion, not a solution.

How do I use Bash on Windows from the Visual Studio Code integrated terminal?

Latest VS code :

  • if you can't see the settings.json, go to menu File -> Preferences -> Settings (or press on Ctrl+,)
  • Settings appear, see two tabs User (selected by default) and Workspace. Go to User -> Features -> Terminal
  • Terminal section appear, see link edit in settings.json. Click and add "terminal.integrated.shell.windows": "C:\\Program Files\\Git\\bin\\bash.exe",
  • Save and Restart VS code.

Bash terminal will reflect on the terminal.

Objects inside objects in javascript

You may have as many levels of Object hierarchy as you want, as long you declare an Object as being a property of another parent Object. Pay attention to the commas on each level, that's the tricky part. Don't use commas after the last element on each level:

{el1, el2, {el31, el32, el33}, {el41, el42}}

_x000D_
_x000D_
var MainObj = {_x000D_
_x000D_
  prop1: "prop1MainObj",_x000D_
  _x000D_
  Obj1: {_x000D_
    prop1: "prop1Obj1",_x000D_
    prop2: "prop2Obj1",    _x000D_
    Obj2: {_x000D_
      prop1: "hey you",_x000D_
      prop2: "prop2Obj2"_x000D_
    }_x000D_
  },_x000D_
    _x000D_
  Obj3: {_x000D_
    prop1: "prop1Obj3",_x000D_
    prop2: "prop2Obj3"_x000D_
  },_x000D_
  _x000D_
  Obj4: {_x000D_
    prop1: true,_x000D_
    prop2: 3_x000D_
  }  _x000D_
};_x000D_
_x000D_
console.log(MainObj.Obj1.Obj2.prop1);
_x000D_
_x000D_
_x000D_

Getting a POST variable

In addition to using Request.Form and Request.QueryString and depending on your specific scenario, it may also be useful to check the Page's IsPostBack property.

if (Page.IsPostBack)
{
  // HTTP Post
}
else
{
  // HTTP Get
}

Android Studio update -Error:Could not run build action using Gradle distribution

I had a similar issue, when I upgraded to the latest version of Android Studio 1.3.2. What seemed to work for me was removing the .gradle folder from my project directory:

rm -rf ~/project/.gradle

How to POST JSON request using Apache HttpClient?

For Apache HttpClient 4.5 or newer version:

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost("http://targethost/login");
    String JSON_STRING="";
    HttpEntity stringEntity = new StringEntity(JSON_STRING,ContentType.APPLICATION_JSON);
    httpPost.setEntity(stringEntity);
    CloseableHttpResponse response2 = httpclient.execute(httpPost);

Note:

1 in order to make the code compile, both httpclient package and httpcore package should be imported.

2 try-catch block has been ommitted.

Reference: appache official guide

the Commons HttpClient project is now end of life, and is no longer being developed. It has been replaced by the Apache HttpComponents project in its HttpClient and HttpCore modules

Javascript: how to validate dates in format MM-DD-YYYY?

<!DOCTYPE html>  
<html>  
<head>  

<title></title>  
 <script>
     function dateCheck(inputText) {
         debugger;

         var dateFormat = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/;

         var flag = 1;

         if (inputText.value.match(dateFormat)) {
             document.myForm.dateInput.focus();

             var inputFormat1 = inputText.value.split('/');
             var inputFormat2 = inputText.value.split('-');
             linputFormat1 = inputFormat1.length;
             linputFormat2 = inputFormat2.length;

             if (linputFormat1 > 1) {
                 var pdate = inputText.value.split('/');
             }
             else if (linputFormat2 > 1) {
                 var pdate = inputText.value.split('-');
             }
             var date = parseInt(pdate[0]);
             var month = parseInt(pdate[1]);
             var year = parseInt(pdate[2]);

             var ListofDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
             if (month == 1 || month > 2) {
                 if (date > ListofDays[month - 1]) {
                     alert("Invalid date format!");
                     return false;
                 }
             }

             if (month == 2) {
                 var leapYear = false;

                 if ((!(year % 4) && year % 100) || !(year % 400)) {
                     leapYear = true;

                 }
                 if ((leapYear == false) && (date >= 29)) {
                     alert("Invalid date format!");
                     return false;
                 }
                 if ((leapYear == true) && (date > 29)) {
                     alert("Invalid date format!");
                     return false;
                 }
             }
             if (flag == 1) {
                 alert("Valid Date");
             }
         }
         else {
             alert("Invalid date format!");
             document.myForm.dateInput.focus();
             return false;
         }
     }
     function restrictCharacters(evt) {

         evt = (evt) ? evt : window.event;
         var charCode = (evt.which) ? evt.which : evt.keyCode;
         if (((charCode >= '48') && (charCode <= '57')) || (charCode == '47')) {
             return true;
         }
         else {
             return false;
         }
     }


 </script>   
</head>



<body>  
    <div>  
        <form name="myForm" action="#">   
            <table>
                <tr>
                    <td>Enter Date</td>
                    <td><input type="text" onkeypress="return restrictCharacters(event);" name="dateInput"/></td>
                    <td></td>
                    <td><span id="span2"></span></td>
                </tr>

                <tr>
                    <td></td>
                    <td><input type="button" name="submit" value="Submit" onclick="dateCheck(document.myForm.dateInput)"  /></td>
                </tr>
            </table>
        </form>  
    </div>   
</body>  
</html> 

How to install a node.js module without using npm?

These modules can't be installed using npm.

Actually you can install a module by specifying instead of a name a local path. As long as the repository has a valid package.json file it should work.


Type npm -l and a pretty help will appear like so :

CLI:

...
install     npm install <tarball file>
                npm install <tarball url>
                npm install <folder>
                npm install <pkg>
                npm install <pkg>@<tag>
                npm install <pkg>@<version>
                npm install <pkg>@<version range>
                
                Can specify one or more: npm install ./foo.tgz bar@stable /some/folder
                If no argument is supplied and ./npm-shrinkwrap.json is 
                present, installs dependencies specified in the shrinkwrap.
                Otherwise, installs dependencies from ./package.json.

What caught my eyes was: npm install <folder>

In my case I had trouble with mrt module so I did this (in a temporary directory)

  • Clone the repo

       git clone https://github.com/oortcloud/meteorite.git
    
  • And I install it globally with:

       npm install -g ./meteorite
    

Tip:

One can also install in the same manner the repo to a local npm project with:

     npm install ../meteorite

And also one can create a link to the repo, in case a patch in development is needed:

     npm link ../meteorite

Edit:

Nowadays npm supports also github and git repositories (see https://docs.npmjs.com/cli/v6/commands/npm-install), as a shorthand you can run :

npm i github.com:some-user/some-repo

How to wrap text using CSS?

This will work everywhere.

<body>
  <table style="table-layout:fixed;">
  <tr>
    <td><div style="word-wrap: break-word; width: 100px" > gdfggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg</div></td>
  </tr>
  </table>
 </body>

How to correctly use "section" tag in HTML5?

In the W3 wiki page about structuring HTML5, it says:

<section>: Used to either group different articles into different purposes or subjects, or to define the different sections of a single article.

And then displays an image that I cleaned up:

enter image description here

It's also important to know how to use the <article> tag (from the same W3 link above):

<article> is related to <section>, but is distinctly different. Whereas <section> is for grouping distinct sections of content or functionality, <article> is for containing related individual standalone pieces of content, such as individual blog posts, videos, images or news items. Think of it this way - if you have a number of items of content, each of which would be suitable for reading on their own, and would make sense to syndicate as separate items in an RSS feed, then <article> is suitable for marking them up.

In our example, <section id="main"> contains blog entries. Each blog entry would be suitable for syndicating as an item in an RSS feed, and would make sense when read on its own, out of context, therefore <article> is perfect for them:

<section id="main">
    <article>
      <!-- first blog post -->
    </article>

    <article>
      <!-- second blog post  -->
    </article>

    <article>
      <!-- third blog post -->
    </article>
</section>

Simple huh? Be aware though that you can also nest sections inside articles, where it makes sense to do so. For example, if each one of these blog posts has a consistent structure of distinct sections, then you could put sections inside your articles as well. It could look something like this:

<article>
  <section id="introduction">
  </section>

  <section id="content">
  </section>

  <section id="summary">
  </section>
</article>

ArrayIndexOutOfBoundsException when using the ArrayList's iterator

Efficient way to iterate your ArrayList followed by this link. This type will improve the performance of looping during iteration

int size = list.size();

for(int j = 0; j < size; j++) {
    System.out.println(list.get(i));
}

Transposing a 2D-array in JavaScript

Another approach by iterating the array from outside to inside and reduce the matrix by mapping inner values.

_x000D_
_x000D_
const_x000D_
    transpose = array => array.reduce((r, a) => a.map((v, i) => [...(r[i] || []), v]), []),_x000D_
    matrix = [[1, 2, 3], [1, 2, 3], [1, 2, 3]];_x000D_
_x000D_
console.log(transpose(matrix));
_x000D_
_x000D_
_x000D_

Int division: Why is the result of 1/3 == 0?

Because you are doing integer division.

As @Noldorin says, if both operators are integers, then integer division is used.

The result 0.33333333 can't be represented as an integer, therefore only the integer part (0) is assigned to the result.

If any of the operators is a double / float, then floating point arithmetic will take place. But you'll have the same problem if you do that:

int n = 1.0 / 3.0;

How to join multiple lines of file names into one with custom delimiter?

I think this one is awesome

ls -1 | awk 'ORS=","'

ORS is the "output record separator" so now your lines will be joined with a comma.

Xpath: select div that contains class AND whose specific child element contains text

You could use the xpath :

//div[@class="measure-tab" and .//span[contains(., "someText")]]

Input :

<root>
<div class="measure-tab">
  <td> someText</td>
</div>
<div class="measure-tab">
  <div>
    <div2>
       <span>someText2</span>
   </div2>
  </div>
</div>
</root>

Output :

    Element='<div class="measure-tab">
  <div>
    <div2>
      <span>someText2</span>
    </div2>
  </div>
</div>'

Vertical align in bootstrap table

The following appears to work:

table td {
  vertical-align: middle !important;
}

You can apply to a specific table as well like so:

#some_table td {
  vertical-align: middle !important;
}

How do I extract data from JSON with PHP?

You can use json_decode() to convert a json string to a PHP object/array.

Eg.

Input:

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json));
var_dump(json_decode($json, true));

Output:

object(stdClass)#1 (5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

array(5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

Few Points to remember:

  • json_decode requires the string to be a valid json else it will return NULL.
  • In the event of a failure to decode, json_last_error() can be used to determine the exact nature of the error.
  • Make sure you pass in utf8 content, or json_decode may error out and just return a NULL value.

How can I remove an SSH key?

The solution for me (openSUSE Leap 42.3, KDE) was to rename the folder ~/.gnupg which apparently contained the cached keys and profiles.

After KDE logout/logon the ssh-add/agent is running again and the folder is created from scratch, but the old keys are all gone.

I didn't have success with the other approaches.

How do I get information about an index and table owner in Oracle?

 select index_name, column_name
 from user_ind_columns
 where table_name = 'NAME';

OR use this:

select TABLE_NAME, OWNER 
from SYS.ALL_TABLES 
order by OWNER, TABLE_NAME 

And for Indexes:

select INDEX_NAME, TABLE_NAME, TABLE_OWNER 
from SYS.ALL_INDEXES 
order by TABLE_OWNER, TABLE_NAME, INDEX_NAME

Python Dictionary Comprehension

>>> {i:i for i in range(1, 11)}
{1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10}