Programs & Examples On #Google desktop

Why "Data at the root level is invalid. Line 1, position 1." for XML Document?

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

Sometimes, there is some "invisible" (not visible in all text editors). Some programs add this.

It's called BOM, you can read more about it here: https://en.wikipedia.org/wiki/Byte_order_mark#Representations_of_byte_order_marks_by_encoding

ASP.NET MVC Razor pass model to layout

For example

@model IList<Model.User>

@{
    Layout="~/Views/Shared/SiteLayout.cshtml";
}

Read more about the new @model directive

Reading Space separated input in python

For python 3 use this

inp = list(map(int,input().split()))
#input => java is a programming language
#return as => ("java","is","a","programming","language")

input() accepts a string from STDIN.

split() splits the string about whitespace character and returns a list of strings.

map() passes each element of the 2nd argument to the first argument and returns a map object

Finally list() converts the map to a list

Clearfix with twitter bootstrap

clearfix should contain the floating elements but in your html you have added clearfix only after floating right that is your pull-right so you should do like this:

<div class="clearfix">
  <div id="sidebar">
    <ul>
      <li>A</li>
      <li>A</li>
      <li>C</li>
      <li>D</li>
      <li>E</li>
      <li>F</li>
      <li>...</li>
      <li>Z</li>
    </ul>
  </div>
  <div id="main">
    <div>
      <div class="pull-right">
        <a>RIGHT</a>
      </div>
    </div>
  <div>MOVED BELOW Z</div>
</div>

see this demo


Happy to know you solved the problem by setting overflow properties. However this is also good idea to clear the float. Where you have floated your elements you could add overflow: hidden; as you have done in your main.

Convert datetime to Unix timestamp and convert it back in python

If your datetime object represents UTC time, don't use time.mktime, as it assumes the tuple is in your local timezone. Instead, use calendar.timegm:

>>> import datetime, calendar
>>> d = datetime.datetime(1970, 1, 1, 0, 1, 0)
>>> calendar.timegm(d.timetuple())
60

Is < faster than <=?

Historically (we're talking the 1980s and early 1990s), there were some architectures in which this was true. The root issue is that integer comparison is inherently implemented via integer subtractions. This gives rise to the following cases.

Comparison     Subtraction
----------     -----------
A < B      --> A - B < 0
A = B      --> A - B = 0
A > B      --> A - B > 0

Now, when A < B the subtraction has to borrow a high-bit for the subtraction to be correct, just like you carry and borrow when adding and subtracting by hand. This "borrowed" bit was usually referred to as the carry bit and would be testable by a branch instruction. A second bit called the zero bit would be set if the subtraction were identically zero which implied equality.

There were usually at least two conditional branch instructions, one to branch on the carry bit and one on the zero bit.

Now, to get at the heart of the matter, let's expand the previous table to include the carry and zero bit results.

Comparison     Subtraction  Carry Bit  Zero Bit
----------     -----------  ---------  --------
A < B      --> A - B < 0    0          0
A = B      --> A - B = 0    1          1
A > B      --> A - B > 0    1          0

So, implementing a branch for A < B can be done in one instruction, because the carry bit is clear only in this case, , that is,

;; Implementation of "if (A < B) goto address;"
cmp  A, B          ;; compare A to B
bcz  address       ;; Branch if Carry is Zero to the new address

But, if we want to do a less-than-or-equal comparison, we need to do an additional check of the zero flag to catch the case of equality.

;; Implementation of "if (A <= B) goto address;"
cmp A, B           ;; compare A to B
bcz address        ;; branch if A < B
bzs address        ;; also, Branch if the Zero bit is Set

So, on some machines, using a "less than" comparison might save one machine instruction. This was relevant in the era of sub-megahertz processor speed and 1:1 CPU-to-memory speed ratios, but it is almost totally irrelevant today.

Javascript : array.length returns undefined

try this

Object.keys(data).length

If IE < 9, you can loop through the object yourself with a for loop

var len = 0;
var i;

for (i in data) {
    if (data.hasOwnProperty(i)) {
        len++;
    }
}

How to find out the location of currently used MySQL configuration file in linux

login to mysql with proper credential and used mysql>SHOW VARIABLES LIKE 'datadir'; that will give you path of where mysql stored

How to printf long long

    // acos(0.0) will return value of pi/2, inverse of cos(0) is pi/2 
    double pi = 2 * acos(0.0);
    int n; // upto 6 digit
    scanf("%d",&n); //precision with which you want the value of pi
    printf("%.*lf\n",n,pi); // * will get replaced by n which is the required precision

SQL Server 2008 - Case / If statements in SELECT Clause

Try something like

SELECT
    CASE var
        WHEN xyz THEN col1
        WHEN zyx THEN col2
        ELSE col7
    END AS col1,
    ...

In other words, use a conditional expression to select the value, then rename the column.

Alternately, you could build up some sort of dynamic SQL hack to share the query tail; I've done this with iBatis before.

How to resolve cURL Error (7): couldn't connect to host?

This issue can also be caused by making curl calls to https when it is not configured on the remote device. Calling over http can resolve this problem in these situations, at least until you configure ssl on the remote.

querySelector and querySelectorAll vs getElementsByClassName and getElementById in JavaScript

I would like to know what exactly is the difference between querySelector and querySelectorAll against getElementsByClassName and getElementById?

The syntax and the browser support.

querySelector is more useful when you want to use more complex selectors.

e.g. All list items descended from an element that is a member of the foo class: .foo li

document.querySelector("#view:_id1:inputText1") it doesn't work. But writing document.getElementById("view:_id1:inputText1") works. Any ideas why?

The : character has special meaning inside a selector. You have to escape it. (The selector escape character has special meaning in a JS string too, so you have to escape that too).

document.querySelector("#view\\:_id1\\:inputText1")

How do I correctly upgrade angular 2 (npm) to the latest version?

Upgrade to latest Angular 5

Angular Dep packages: npm install @angular/{animations,common,compiler,core,forms,http,platform-browser,platform-browser-dynamic,router}@latest --save

Other packages that are installed by the angular cli npm install --save core-js@latest rxjs@latest zone.js@latest

Angular Dev packages: npm install --save-dev @angular/{compiler-cli,cli,language-service}@latest

Types Dev packages: npm install --save-dev @types/{jasmine,jasminewd2,node}@latest

Other packages that are installed as dev dev by the angular cli: npm install --save-dev codelyzer@latest jasmine-core@latest jasmine-spec-reporter@latest karma@latest karma-chrome-launcher@latest karma-cli@latest karma-coverage-istanbul-reporter@latest karma-jasmine@latest karma-jasmine-html-reporter@latest protractor@latest ts-node@latest tslint@latest

Install the latest supported version used by the Angular cli (don't do @latest): npm install --save-dev [email protected]

Rename file angular-cli.json to .angular-cli.json and update the content:

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": {
    "name": "project3-example"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "app",
      "styles": [
        "styles.css"
      ],
      "scripts": [],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],
  "e2e": {
    "protractor": {
      "config": "./protractor.conf.js"
    }
  },
  "lint": [
    {
      "project": "src/tsconfig.app.json",
      "exclude": "**/node_modules/**"
    },
    {
      "project": "src/tsconfig.spec.json",
      "exclude": "**/node_modules/**"
    },
    {
      "project": "e2e/tsconfig.e2e.json",
      "exclude": "**/node_modules/**"
    }
  ],
  "test": {
    "karma": {
      "config": "./karma.conf.js"
    }
  },
  "defaults": {
    "styleExt": "css",
    "component": {}
  }
}

Writing List of Strings to Excel CSV File in Python

Very simple to fix, you just need to turn the parameter to writerow into a list.

for item in RESULTS:
     wr.writerow([item,])

A CSS selector to get last visible div

I think it's not possible to select by a css value (display)

edit:

in my opinion, it would make sense to use a bit of jquery here:

$('#your_container > div:visible:last').addClass('last-visible-div');

How to read until end of file (EOF) using BufferedReader in Java?

With text files, maybe the EOF is -1 when using BufferReader.read(), char by char. I made a test with BufferReader.readLine()!=null and it worked properly.

How can I open multiple files using "with open" in Python?

With python 2.6 It will not work, we have to use below way to open multiple files:

with open('a', 'w') as a:
    with open('b', 'w') as b:

Merge two json/javascript arrays in to one array

You can use the new js spread operator if using es6:

_x000D_
_x000D_
var json1 = [{id:1, name: 'xxx'}]_x000D_
var json2 = [{id:2, name: 'xyz'}]_x000D_
var finalObj = [...json1, ...json2]_x000D_
_x000D_
console.log(finalObj)
_x000D_
_x000D_
_x000D_

What's the difference between commit() and apply() in SharedPreferences

The difference between commit() and apply()

We might be confused by those two terms, when we are using SharedPreference. Basically they are probably the same, so let’s clarify the differences of commit() and apply().

1.Return value:

apply() commits without returning a boolean indicating success or failure. commit() returns true if the save works, false otherwise.

  1. Speed:

apply() is faster. commit() is slower.

  1. Asynchronous v.s. Synchronous:

apply(): Asynchronous commit(): Synchronous

  1. Atomic:

apply(): atomic commit(): atomic

  1. Error notification:

apply(): No commit(): Yes

How do I download a file from the internet to my linux server with Bash

I guess you could use curl and wget, but since Oracle requires you to check of some checkmarks this will be painfull to emulate with the tools mentioned. You would have to download the page with the license agreement and from looking at it figure out what request is needed to get to the actual download.

Of course you could simply start a browser, but this might not qualify as 'from the command line'. So you might want to look into lynx, a text based browser.

How to read the post request parameters using JavaScript

function getParameterByName(name, url) {
            if (!url) url = window.location.href;
            name = name.replace(/[\[\]]/g, "\\$&");
            var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
                results = regex.exec(url);
            if (!results) return null;
            if (!results[2]) return '';
            return decodeURIComponent(results[2].replace(/\+/g, " "));
        }
var formObj = document.getElementById("pageID");
formObj.response_order_id.value = getParameterByName("name");

How can I shuffle an array?

Use the modern version of the Fisher–Yates shuffle algorithm:

/**
 * Shuffles array in place.
 * @param {Array} a items An array containing the items.
 */
function shuffle(a) {
    var j, x, i;
    for (i = a.length - 1; i > 0; i--) {
        j = Math.floor(Math.random() * (i + 1));
        x = a[i];
        a[i] = a[j];
        a[j] = x;
    }
    return a;
}

ES2015 (ES6) version

/**
 * Shuffles array in place. ES6 version
 * @param {Array} a items An array containing the items.
 */
function shuffle(a) {
    for (let i = a.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [a[i], a[j]] = [a[j], a[i]];
    }
    return a;
}

Note however, that swapping variables with destructuring assignment causes significant performance loss, as of October 2017.

Use

var myArray = ['1','2','3','4','5','6','7','8','9'];
shuffle(myArray);

Implementing prototype

Using Object.defineProperty (method taken from this SO answer) we can also implement this function as a prototype method for arrays, without having it show up in loops such as for (i in arr). The following will allow you to call arr.shuffle() to shuffle the array arr:

Object.defineProperty(Array.prototype, 'shuffle', {
    value: function() {
        for (let i = this.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [this[i], this[j]] = [this[j], this[i]];
        }
        return this;
    }
});

Angular 2 Sibling Component Communication

This is not what you exactly want but for sure will help you out

I'm surprised there's not more information out there about component communication <=> consider this tutorial by angualr2

For sibling components communication, I'd suggest to go with sharedService. There are also other options available though.

import {Component,bind} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
import {HTTP_PROVIDERS} from 'angular2/http';
import {NameService} from 'src/nameService';


import {TheContent} from 'src/content';
import {Navbar} from 'src/nav';


@Component({
  selector: 'app',
  directives: [TheContent,Navbar],
  providers: [NameService],
  template: '<navbar></navbar><thecontent></thecontent>'
})


export class App {
  constructor() {
    console.log('App started');
  }
}

bootstrap(App,[]);

Please refer to link at top for more code.

Edit: This is a very small demo. You have already mention that you have already tried with sharedService. So please consider this tutorial by angualr2 for more information.

Bootstrap 3 - jumbotron background image effect

After inspecting the sample website you provided, I found that the author might achieve the effect by using a library called Stellar.js, take a look at the library site, cheers!

jQuery - Trigger event when an element is removed from the DOM

Just checked, it is already built-in in current version of JQuery:

jQuery - v1.9.1

jQuery UI - v1.10.2

$("#myDiv").on("remove", function () {
    alert("Element was removed");
})

Important: This is functionality of Jquery UI script (not JQuery), so you have to load both scripts (jquery and jquery-ui) to make it work. Here is example: http://jsfiddle.net/72RTz/

How to change already compiled .class file without decompile?

You can follow these steps to modify your java class:

  1. Decompile the .class file as you have done and save it as .java
  2. Create a project in Eclipse with that java file, the original JAR as library, and all its dependencies
  3. Change the .java and compile
  4. Get the modified .class file and put it again inside the original JAR.

Android: Go back to previous activity

There are few cases to go back to your previous activity:

Case 1: if you want take result back to your previous activity then ActivityA.java

 Intent intent = new Intent(ActivityA.this, FBHelperActivity.class);
               startActivityForResult(intent,2);

FBHelperActivity.java

 Intent returnIntent = new Intent();
 setResult(RESULT_OK, returnIntent);
 finish();

Case 2: ActivityA --> FBHelperActivity---->ActivityA

ActivityA.java

 Intent intent = new Intent(ActivityA.this, FBHelperActivity.class);
               startActivity(intent);

FBHelperActivity.java

after getting of result call finish();
 By this way your second activity will finish and because 
 you did not call finish() in your first activity then
 automatic first activity is in back ground, will visible.

How can I find my Apple Developer Team id and Team Agent Apple ID?

There are ways you can check even if you are not a paid user. You can confirm TeamID from Xcode. [Build setting] Displayed on tooltip of development team.

How to access share folder in virtualbox. Host Win7, Guest Fedora 16?

You probably need to change your mount command from:

[root@localhost Desktop]# sudo mount -t vboxsf D:\share_folder_vm \share_folder

to:

[root@localhost Desktop]# sudo mount -t vboxsf share_name \share_folder

where share_name is the "Name" of the share in the VirtualBox -> Shared Folders -> Folder List list box. The argument you have ("D:\share_folder_vm") is the "Path" of the share on the host, not the "Name".

Does List<T> guarantee insertion order?

This is the code I have for moving an item down one place in a list:

if (this.folderImages.SelectedIndex > -1 && this.folderImages.SelectedIndex < this.folderImages.Items.Count - 1)
{
    string imageName = this.folderImages.SelectedItem as string;
    int index = this.folderImages.SelectedIndex;

    this.folderImages.Items.RemoveAt(index);
    this.folderImages.Items.Insert(index + 1, imageName);
    this.folderImages.SelectedIndex = index + 1;
 }

and this for moving it one place up:

if (this.folderImages.SelectedIndex > 0)
{
    string imageName = this.folderImages.SelectedItem as string;
    int index = this.folderImages.SelectedIndex;

    this.folderImages.Items.RemoveAt(index);
    this.folderImages.Items.Insert(index - 1, imageName);
    this.folderImages.SelectedIndex = index - 1;
}

folderImages is a ListBox of course so the list is a ListBox.ObjectCollection, not a List<T>, but it does inherit from IList so it should behave the same. Does this help?

Of course the former only works if the selected item is not the last item in the list and the latter if the selected item is not the first item.

Remote JMX connection

Thanks a lot, it works like this:

java -Djava.rmi.server.hostname=xxx.xxx.xxx.xxx -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.port=25000 -jar myjar.jar

Saving and loading objects and using pickle

The following works for me:

class Fruits: pass

banana = Fruits()

banana.color = 'yellow'
banana.value = 30

import pickle

filehandler = open("Fruits.obj","wb")
pickle.dump(banana,filehandler)
filehandler.close()

file = open("Fruits.obj",'rb')
object_file = pickle.load(file)
file.close()

print(object_file.color, object_file.value, sep=', ')
# yellow, 30

Facebook API: Get fans of / people who like a page

Facebook's FQL documentation here tells you how to do it. Run the example SELECT name, fan_count FROM page WHERE page_id = 19292868552 and replace the page_id number with your page's id number and it will return the page name and the fan count.

Is it possible to sort a ES6 map object?

Unfortunately, not really implemented in ES6. You have this feature with OrderedMap.sort() from ImmutableJS or _.sortBy() from Lodash.

Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

mAddTaskButton is null because you never initialize it with:

mAddTaskButton = (Button) findViewById(R.id.addTaskButton);

before you call mAddTaskButton.setOnClickListener().

How to use the curl command in PowerShell?

Use splatting.

$CurlArgument = '-u', '[email protected]:yyyy',
                '-X', 'POST',
                'https://xxx.bitbucket.org/1.0/repositories/abcd/efg/pull-requests/2229/comments',
                '--data', 'content=success'
$CURLEXE = 'C:\Program Files\Git\mingw64\bin\curl.exe'
& $CURLEXE @CurlArgument

Make an Android button change background on click through XML

To change image by using code

public void onClick(View v) {
   if(v == ButtonName) {
     ButtonName.setImageResource(R.drawable.ImageName);
   }
}

Or, using an XML file:

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_pressed="true"
   android:drawable="@drawable/login_selected" /> <!-- pressed -->
  <item android:state_focused="true"
   android:drawable="@drawable/login_mouse_over" /> <!-- focused -->
  <item android:drawable="@drawable/login" /> <!-- default -->
</selector>

In OnClick, just add this code:

ButtonName.setBackgroundDrawable(getResources().getDrawable(R.drawable.ImageName));

Font size relative to the user's screen resolution?

I've created a variant of https://stackoverflow.com/a/17845473/189411

where you can set min and max text size in relation of min and max size of box that you want "check" size. In addition you can check size of dom element different than box where you want apply text size.

You resize text between 19px and 25px on #size-2 element, based on 500px and 960px width of #size-2 element

resizeTextInRange(500,960,19,25,'#size-2');

You resize text between 13px and 20px on #size-1 element, based on 500px and 960px width of body element

resizeTextInRange(500,960,13,20,'#size-1','body');

complete code are there https://github.com/kiuz/sandbox-html-js-css/tree/gh-pages/text-resize-in-range-of-text-and-screen/src

function inRange (x,min,max) {
    return Math.min(Math.max(x, min), max);
}

function resizeTextInRange(minW,maxW,textMinS,textMaxS, elementApply, elementCheck=0) {

    if(elementCheck==0){elementCheck=elementApply;}

    var ww = $(elementCheck).width();
    var difW = maxW-minW;
    var difT = textMaxS- textMinS;
    var rapW = (ww-minW);
    var out=(difT/100)*(rapW/(difW/100))+textMinS;
    var normalizedOut = inRange(out, textMinS, textMaxS);
    $(elementApply).css('font-size',normalizedOut+'px');

    console.log(normalizedOut);

}

$(function () {
    resizeTextInRange(500,960,19,25,'#size-2');
    resizeTextInRange(500,960,13,20,'#size-1','body');
    $(window).resize(function () {
        resizeTextInRange(500,960,19,25,'#size-2');
        resizeTextInRange(500,960,13,20,'#size-1','body');
    });
});

Use Fieldset Legend with bootstrap

In bootstrap 4 it is much easier to have a border on the fieldset that blends with the legend. You don't need custom css to achieve it, it can be done like this:

<fieldset class="border p-2">
   <legend  class="w-auto">Your Legend</legend>
</fieldset>

which looks like this: bootstrap 4 fieldset and legend

How to add data to DataGridView

Let's assume you have a class like this:

public class Staff
{
    public int ID { get; set; }
    public string Name { get; set; }
}

And assume you have dragged and dropped a DataGridView to your form, and name it dataGridView1.

You need a BindingSource to hold your data to bind your DataGridView. This is how you can do it:

private void frmDGV_Load(object sender, EventArgs e)
{
    //dummy data
    List<Staff> lstStaff = new List<Staff>();
    lstStaff.Add(new Staff()
    {
        ID = 1,
        Name = "XX"
    });
    lstStaff.Add(new Staff()
    {
        ID = 2,
        Name = "YY"
    });

    //use binding source to hold dummy data
    BindingSource binding = new BindingSource();
    binding.DataSource = lstStaff;

    //bind datagridview to binding source
    dataGridView1.DataSource = binding;
}

Indent multiple lines quickly in vi

A quick way to do this using VISUAL MODE uses the same process as commenting a block of code.

This is useful if you would prefer not to change your shiftwidth or use any set directives and is flexible enough to work with TABS or SPACES or any other character.

  1. Position cursor at the beginning on the block
  2. v to switch to -- VISUAL MODE --
  3. Select the text to be indented
  4. Type : to switch to the prompt
  5. Replacing with 3 leading spaces:

    :'<,'>s/^/ /g

  6. Or replacing with leading tabs:

    :'<,'>s/^/\t/g

  7. Brief Explanation:

    '<,'> - Within the Visually Selected Range

    s/^/ /g - Insert 3 spaces at the beginning of every line within the whole range

    (or)

    s/^/\t/g - Insert Tab at the beginning of every line within the whole range

How to change progress bar's progress color in Android

To change horizontal ProgressBar color (in kotlin):

fun tintHorizontalProgress(progress: ProgressBar, @ColorInt color: Int = ContextCompat.getColor(progress.context, R.color.colorPrimary)){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        progress.progressTintList = ColorStateList.valueOf(color)
    } else{
        val layerDrawable = progress.progressDrawable as? LayerDrawable
        val progressDrawable = layerDrawable?.findDrawableByLayerId(android.R.id.progress)
        progressDrawable?.setColorFilter(color, PorterDuff.Mode.SRC_ATOP)
    }
}

To change indeterminate ProgressBar color:

fun tintIndeterminateProgress(progress: ProgressBar, @ColorInt color: Int = ContextCompat.getColor(progress.context, R.color.colorPrimary)){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        progress.indeterminateTintList = ColorStateList.valueOf(color)
    } else {
        (progress.indeterminateDrawable as? LayerDrawable)?.apply {
            if (numberOfLayers >= 2) {
                setId(0, android.R.id.progress)
                setId(1, android.R.id.secondaryProgress)
                val progressDrawable = findDrawableByLayerId(android.R.id.progress).mutate()
                progressDrawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP)
            }
        }
    }
}

And it finally normally tint pre-lollipop progressBars

tinted progress on api 19

Python - Module Not Found

I had same error. For those who run python scripts on different servers, please check if the python path is correctly specified in shebang. For me on each server it was located in different dirs.

Insert Data Into Tables Linked by Foreign Key

Use stored procedures.

And even assuming you would want not to use stored procedures - there is at most 3 commands to be run, not 4. Second getting id is useless, as you can do "INSERT INTO ... RETURNING".

endforeach in loops?

as an alternative syntax you can write foreach loops like so

foreach($arr as $item):
    //do stuff
endforeach;

This type of syntax is typically used when php is being used as a templating language as such

<?php foreach($arr as $item):?>
    <!--do stuff -->
<?php endforeach; ?>

How to get single value of List<object>

Define a class like this :

public class myclass {
       string id ;
       string title ;
       string content;
 }

 public class program {
        public void Main () {
               List<myclass> objlist = new List<myclass> () ;
               foreach (var value in objlist)  {
                       TextBox1.Text = value.id ;
                       TextBox2.Text= value.title;
                       TextBox3.Text= value.content ;
                }
         }
  }

I tried to draw a sketch and you can improve it in many ways. Instead of defining class "myclass", you can define struct.

Align a div to center

Try this, it helped me: wrap the div in tags, the problem is that it will center the content of the div also (if not coded otherwise). Hope that helps :)

The import javax.servlet can't be resolved

Add to pom.xml

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
</dependency>

How to format background color using twitter bootstrap?

Bootstrap default "contextual backgrounds" helper classes to change the background color:

.bg-primary
.bg-default
.bg-info
.bg-warning
.bg-danger

If you need set custom background color then, you can write your own custom classes in style.css( a custom css file) example below

.bg-pink
{
  background-color: #CE6F9E;
}

Get name of object or class

If you use standard IIFE (for example with TypeScript)

var Zamboch;
(function (_Zamboch) {
    (function (Web) {
        (function (Common) {
            var App = (function () {
                function App() {
                }
                App.prototype.hello = function () {
                    console.log('Hello App');
                };
                return App;
            })();
            Common.App = App;
        })(Web.Common || (Web.Common = {}));
        var Common = Web.Common;
    })(_Zamboch.Web || (_Zamboch.Web = {}));
    var Web = _Zamboch.Web;
})(Zamboch || (Zamboch = {}));

you could annotate the prototypes upfront with

setupReflection(Zamboch, 'Zamboch', 'Zamboch');

and then use _fullname and _classname fields.

var app=new Zamboch.Web.Common.App();
console.log(app._fullname);

annotating function here:

function setupReflection(ns, fullname, name) {
    // I have only classes and namespaces starting with capital letter
    if (name[0] >= 'A' && name[0] &lt;= 'Z') {
        var type = typeof ns;
        if (type == 'object') {
            ns._refmark = ns._refmark || 0;
            ns._fullname = fullname;
            var keys = Object.keys(ns);
            if (keys.length != ns._refmark) {
                // set marker to avoid recusion, just in case 
                ns._refmark = keys.length;
                for (var nested in ns) {
                    var nestedvalue = ns[nested];
                    setupReflection(nestedvalue, fullname + '.' + nested, nested);
                }
            }
        } else if (type == 'function' && ns.prototype) {
            ns._fullname = fullname;
            ns._classname = name;
            ns.prototype._fullname = fullname;
            ns.prototype._classname = name;
        }
    }
}

JsFiddle

Shadow Effect for a Text in Android?

TextView textv = (TextView) findViewById(R.id.textview1);
textv.setShadowLayer(1, 0, 0, Color.BLACK);

Send form data using ajax

can you try this :

function f (){
fname  = $("input[name='fname']").val();
lname  = $("input[name='fname']").val();
att=form.attr("action") ;
$.post(att ,{fname : fname , lname :lname}).done(function(data){
alert(data);
});
return true;
}

How can I erase all inline styles with javascript and leave only the styles specified in the css style sheet?

This can be accomplished in two steps:

1: select the element you want to change by either tagname, id, class etc.

var element = document.getElementsByTagName('h2')[0];

  1. remove the style attribute

element.removeAttribute('style');

How can I have a newline in a string in sh?

If you're using Bash, the solution is to use $'string', for example:

$ STR=$'Hello\nWorld'
$ echo "$STR" # quotes are required here!
Hello
World

If you're using pretty much any other shell, just insert the newline as-is in the string:

$ STR='Hello
> World'

Bash is pretty nice. It accepts more than just \n in the $'' string. Here is an excerpt from the Bash manual page:

   Words of the form $'string' are treated specially.  The word expands to
   string, with backslash-escaped characters replaced as specified by  the
   ANSI  C  standard.  Backslash escape sequences, if present, are decoded
   as follows:
          \a     alert (bell)
          \b     backspace
          \e
          \E     an escape character
          \f     form feed
          \n     new line
          \r     carriage return
          \t     horizontal tab
          \v     vertical tab
          \\     backslash
          \'     single quote
          \"     double quote
          \nnn   the eight-bit character whose value is  the  octal  value
                 nnn (one to three digits)
          \xHH   the  eight-bit  character  whose value is the hexadecimal
                 value HH (one or two hex digits)
          \cx    a control-x character

   The expanded result is single-quoted, as if the  dollar  sign  had  not
   been present.

   A double-quoted string preceded by a dollar sign ($"string") will cause
   the string to be translated according to the current  locale.   If  the
   current  locale  is  C  or  POSIX,  the dollar sign is ignored.  If the
   string is translated and replaced, the replacement is double-quoted.

Search and replace a particular string in a file using Perl

You could also do this:

#!/usr/bin/perl

use strict;
use warnings;

$^I = '.bak'; # create a backup copy 

while (<>) {
   s/<PREF>/ABCD/g; # do the replacement
   print; # print to the modified file
}

Invoke the script with by

./script.pl input_file

You will get a file named input_file, containing your changes, and a file named input_file.bak, which is simply a copy of the original file.

How to solve "Could not establish trust relationship for the SSL/TLS secure channel with authority"

I just dragged the certificate into the "Trusted Root Certification Authorities" folder and voila everything worked nicely.

Oh. And I first added the following from a Administrator Command Prompt:

netsh http add urlacl url=https://+:8732/Servicename user=NT-MYNDIGHET\INTERAKTIV

I am not sure of the name you need for the user (mine is norwegian as you can see !): user=NT-AUTHORITY/INTERACTIVE ?

You can see all existing urlacl's by issuing the command: netsh http show urlacl

Counting number of characters in a file through shell script

The following script is tested and gives exactly the results, that are expected

\#!/bin/bash

echo "Enter the file name"

read file

echo "enter the word to be found"

read word

count=0

for i in \`cat $file`

do

if [ $i == $word ]

then

count=\`expr $count + 1`

fi

done

echo "The number of words are $count"

Laravel Eloquent - distinct() and count() not working properly together

Based on Laravel docs for raw queries I was able to get count for a select field to work with this code in the product model.

public function scopeShowProductCount($query)
{
    $query->select(DB::raw('DISTINCT pid, COUNT(*) AS count_pid'))
          ->groupBy('pid')
          ->orderBy('count_pid', 'desc');
}

This facade worked to get the same result in the controller:

$products = DB::table('products')->select(DB::raw('DISTINCT pid, COUNT(*) AS count_pid'))->groupBy('pid')->orderBy('count_pid', 'desc')->get();

The resulting dump for both queries was as follows:

#attributes: array:2 [
  "pid" => "1271"
  "count_pid" => 19
],
#attributes: array:2 [
  "pid" => "1273"
  "count_pid" => 12
],
#attributes: array:2 [
  "pid" => "1275"
  "count_pid" => 7
]

Saving any file to in the database, just convert it to a byte array?

While you can store files in this fashion, it has significant tradeoffs:

  • Most DBs are not optimized for giant quantities of binary data, and query performance often degrades dramatically as the table bloats, even with indexes. (SQL Server 2008, with the FILESTREAM column type, is the exception to the rule.)
  • DB backup/replication becomes extremely slow.
  • It's a lot easier to handle a corrupted drive with 2 million images -- just replace the disk on the RAID -- than a DB table that becomes corrupted.
  • If you accidentally delete a dozen images on a filesystem, your operations guys can replace them pretty easily from a backup, and since the table index is tiny by comparison, it can be restored quickly. If you accidentally delete a dozen images in a giant database table, you have a long and painful wait to restore the DB from backup, paralyzing your entire system in the meantime.

These are just some of the drawbacks I can come up with off the top of my head. For tiny projects it may be worth storing files in this fashion, but if you're designing enterprise-grade software I would strongly recommend against it.

How to sort an associative array by its values in Javascript?

Here is a variation of ben blank's answer, if you don't like tuples.

This saves you a few characters.

var keys = [];
for (var key in sortme) {
  keys.push(key);
}

keys.sort(function(k0, k1) {
  var a = sortme[k0];
  var b = sortme[k1];
  return a < b ? -1 : (a > b ? 1 : 0);
});

for (var i = 0; i < keys.length; ++i) {
  var key = keys[i];
  var value = sortme[key];
  // Do something with key and value.
}

Static link of shared library function in gcc

Yeah, I know this is an 8 year-old question, but I was told that it was possible to statically link against a shared-object library and this was literally the top hit when I searched for more information about it.

To actually demonstrate that statically linking a shared-object library is not possible with ld (gcc's linker) -- as opposed to just a bunch of people insisting that it's not possible -- use the following gcc command:

gcc -o executablename objectname.o -Wl,-Bstatic -l:libnamespec.so

(Of course you'll have to compile objectname.o from sourcename.c, and you should probably make up your own shared-object library as well. If you do, use -Wl,--library-path,. so that ld can find your library in the local directory.)

The actual error you receive is:

/usr/bin/ld: attempted static link of dynamic object `libnamespec.so'
collect2: error: ld returned 1 exit status

Hope that helps.

SQL Server stored procedure creating temp table and inserting value

A SELECT INTO statement creates the table for you. There is no need for the CREATE TABLE statement before hand.

What is happening is that you create #ivmy_cash_temp1 in your CREATE statement, then the DB tries to create it for you when you do a SELECT INTO. This causes an error as it is trying to create a table that you have already created.

Either eliminate the CREATE TABLE statement or alter your query that fills it to use INSERT INTO SELECT format.

If you need a unique ID added to your new row then it's best to use SELECT INTO... since IDENTITY() only works with this syntax.

How to make an unaware datetime timezone aware in python

I wrote this at Nov 22 2011 , is Pyhton 2 only , never checked if it work on Python 3

I had use from dt_aware to dt_unaware

dt_unaware = dt_aware.replace(tzinfo=None)

and dt_unware to dt_aware

from pytz import timezone
localtz = timezone('Europe/Lisbon')
dt_aware = localtz.localize(dt_unware)

but answer before is also a good solution.

How to convert JTextField to String and String to JTextField?

// to string
String text = textField.getText();

// to JTextField
textField.setText(text);

You can also create a new text field: new JTextField(text)

Note that this is not conversion. You have two objects, where one has a property of the type of the other one, and you just set/get it.

Reference: javadocs of JTextField

Add animated Gif image in Iphone UIImageView

I know that an answer has already been approved, but its hard not to try to share that I've created an embedded framework that adds Gif support to iOS that feels just like if you were using any other UIKit Framework class.

Here's an example:

UIGifImage *gif = [[UIGifImage alloc] initWithData:imageData];
anUiImageView.image = gif;

Download the latest release from https://github.com/ObjSal/UIGifImage/releases

-- Sal

How to list all Git tags?

If you want to check you tag name locally, you have to go to the path where you have created tag(local path). Means where you have put your objects. Then type command:

git show --name-only <tagname>

It will show all the objects under that tag name. I am working in Teradata and object means view, table etc

How to change ProgressBar's progress indicator color in Android

If you only want to change the progress bar color, you can simply use a color filter in your Activity's onCreate() method:

ProgressBar progressbar = (ProgressBar) findViewById(R.id.progressbar);
int color = 0xFF00FF00;
progressbar.getIndeterminateDrawable().setColorFilter(color, PorterDuff.Mode.SRC_IN);
progressbar.getProgressDrawable().setColorFilter(color, PorterDuff.Mode.SRC_IN);

Idea from here.

You only need to do this for pre-lollipop versions. On Lollipop you can use the colorAccent style attribute.

Android customized button; changing text color

Use getColorStateList like this

setTextColor(resources.getColorStateList(R.color.button_states_color))

instead of getColor

setTextColor(resources.getColor(R.color.button_states_color))

How to get a list column names and datatypes of a table in PostgreSQL?

SELECT
        a.attname as "Column",
        pg_catalog.format_type(a.atttypid, a.atttypmod) as "Datatype"
    FROM
        pg_catalog.pg_attribute a
    WHERE
        a.attnum > 0
        AND NOT a.attisdropped
        AND a.attrelid = (
            SELECT c.oid
            FROM pg_catalog.pg_class c
                LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
            WHERE c.relname ~ '^(hello world)$'
                AND pg_catalog.pg_table_is_visible(c.oid)
        );

Change the hello world with your table name

More info on it : http://www.postgresql.org/docs/9.3/static/catalog-pg-attribute.html

Add carriage return to a string

string s2 = s1.Replace(",", ",\n") + ",....";

When is each sorting algorithm used?

@dsimcha wrote: Counting sort: When you are sorting integers with a limited range

I would change that to:

Counting sort: When you sort positive integers (0 - Integer.MAX_VALUE-2 due to the pigeonhole).

You can always get the max and min values as an efficiency heuristic in linear time as well.
Also you need at least n extra space for the intermediate array and it is stable obviously.

/**
* Some VMs reserve some header words in an array.
* Attempts to allocate larger arrays may result in
* OutOfMemoryError: Requested array size exceeds VM limit
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

(even though it actually will allow to MAX_VALUE-2) see: Do Java arrays have a maximum size?

Also I would explain that radix sort complexity is O(wn) for n keys which are integers of word size w. Sometimes w is presented as a constant, which would make radix sort better (for sufficiently large n) than the best comparison-based sorting algorithms, which all perform O(n log n) comparisons to sort n keys. However, in general w cannot be considered a constant: if all n keys are distinct, then w has to be at least log n for a random-access machine to be able to store them in memory, which gives at best a time complexity O(n log n). (from wikipedia)

How to pass arguments to a Dockerfile?

You are looking for --build-arg and the ARG instruction. These are new as of Docker 1.9. Check out https://docs.docker.com/engine/reference/builder/#arg. This will allow you to add ARG arg to the Dockerfile and then build with docker build --build-arg arg=2.3 ..

Python time measure function

Decorator method using decorator Python library:

import decorator

@decorator
def timing(func, *args, **kwargs):
    '''Function timing wrapper
        Example of using:
        ``@timing()``
    '''

    fn = '%s.%s' % (func.__module__, func.__name__)

    timer = Timer()
    with timer:
        ret = func(*args, **kwargs)

    log.info(u'%s - %0.3f sec' % (fn, timer.duration_in_seconds()))
    return ret

See post on my Blog:

post on mobilepro.pl Blog

my post on Google Plus

How to get difference between two dates in Year/Month/Week/Day?

Partly as a preparation for trying to answer this question correctly (and maybe even definitively...), partly to examine how much one can trust code that is pasted on SO, and partly as an exercise in finding bugs, I created a bunch of unit tests for this question, and applied them to many proposed solutions from this page and a couple of duplicates.

The results are conclusive: not a single one of the code contributions accurately answers the question. Update: I now have four correct solutions to this question, including my own, see updates below.

Code tested

From this question, I tested code by the following users: Mohammed Ijas Nasirudeen, ruffin, Malu MN, Dave, pk., Jani, lc.

These were all the answers which provided all three of years, months, and days in their code. Note that two of these, Dave and Jani, gave the total number of days and months, rather than the total number of months left after counting the years, and the total number of days left after counting the months. I think the answers are wrong in terms of what the OP seemed to want, but the unit tests obviously don't tell you much in these cases. (Note that in Jani's case this was my error and his code was actually correct - see Update 4 below)

The answers by Jon Skeet, Aghasoleimani, Mukesh Kumar, Richard, Colin, sheir, just i saw, Chalkey and Andy, were incomplete. This doesn't mean that the answers weren't any good, in fact several of them are useful contributions towards a solution. It just means that there wasn't code taking two DateTimes and returning 3 ints that I could properly test. Four of these do however talk about using TimeSpan. As many people have mentioned, TimeSpan doesn't return counts of anything larger than days.

The other answers I tested were from

  • question 3054715 - LukeH, ho1 and this. ___curious_geek
  • question 6260372 - Chuck Rostance and Jani (same answer as this question)
  • question 9 (!) - Dylan Hayes, Jon and Rajeshwaran S P

this.___curious_geek's answer is code on a page he linked to, which I don't think he wrote. Jani's answer is the only one which uses an external library, Time Period Library for .Net.

All other answers on all these questions seemed to be incomplete. Question 9 is about age in years, and the three answers are ones which exceeded the brief and calculated years, months and days. If anyone finds further duplicates of this question please let me know.

How I tested

Quite simply: I made an interface

public interface IDateDifference
{
  void SetDates(DateTime start, DateTime end);
  int GetYears();
  int GetMonths();
  int GetDays();

}

For each answer I wrote a class implementing this interface, using the copied and pasted code as a basis. Of course I had to adapt functions with different signatures etc, but I tried to make the minimal edits to do so, preserving all the logic code.

I wrote a bunch of NUnit tests in an abstract generic class

[TestFixture]
public abstract class DateDifferenceTests<DDC> where DDC : IDateDifference, new()

and added an empty derived class

public class Rajeshwaran_S_P_Test : DateDifferenceTests<Rajeshwaran_S_P>
{
}

to the source file for each IDateDifference class.

NUnit is clever enough to do the rest.

The tests

A couple of these were written in advance and the rest were written to try and break seemingly working implementations.

[TestFixture]
public abstract class DateDifferenceTests<DDC> where DDC : IDateDifference, new()
{
  protected IDateDifference ddClass;

  [SetUp]
  public void Init()
  {
    ddClass = new DDC();
  }

  [Test]
  public void BasicTest()
  {
    ddClass.SetDates(new DateTime(2012, 12, 1), new DateTime(2012, 12, 25));
    CheckResults(0, 0, 24);
  }

  [Test]
  public void AlmostTwoYearsTest()
  {
    ddClass.SetDates(new DateTime(2010, 8, 29), new DateTime(2012, 8, 14));
    CheckResults(1, 11, 16);
  }

  [Test]
  public void AlmostThreeYearsTest()
  {
    ddClass.SetDates(new DateTime(2009, 7, 29), new DateTime(2012, 7, 14));
    CheckResults(2, 11, 15);
  }

  [Test]
  public void BornOnALeapYearTest()
  {
    ddClass.SetDates(new DateTime(2008, 2, 29), new DateTime(2009, 2, 28));
    CheckControversialResults(0, 11, 30, 1, 0, 0);
  }

  [Test]
  public void BornOnALeapYearTest2()
  {
    ddClass.SetDates(new DateTime(2008, 2, 29), new DateTime(2009, 3, 1));
    CheckControversialResults(1, 0, 0, 1, 0, 1);
  }


  [Test]
  public void LongMonthToLongMonth()
  {
    ddClass.SetDates(new DateTime(2010, 1, 31), new DateTime(2010, 3, 31));
    CheckResults(0, 2, 0);
  }

  [Test]
  public void LongMonthToLongMonthPenultimateDay()
  {
    ddClass.SetDates(new DateTime(2009, 1, 31), new DateTime(2009, 3, 30));
    CheckResults(0, 1, 30);
  }

  [Test]
  public void LongMonthToShortMonth()
  {
    ddClass.SetDates(new DateTime(2009, 8, 31), new DateTime(2009, 9, 30));
    CheckControversialResults(0, 1, 0, 0, 0, 30);
  }

  [Test]
  public void LongMonthToPartWayThruShortMonth()
  {
    ddClass.SetDates(new DateTime(2009, 8, 31), new DateTime(2009, 9, 10));
    CheckResults(0, 0, 10);
  }

  private void CheckResults(int years, int months, int days)
  {
    Assert.AreEqual(years, ddClass.GetYears());
    Assert.AreEqual(months, ddClass.GetMonths());
    Assert.AreEqual(days, ddClass.GetDays());
  }

  private void CheckControversialResults(int years, int months, int days,
    int yearsAlt, int monthsAlt, int daysAlt)
  {
    // gives the right output but unhelpful messages
    bool success = ((ddClass.GetYears() == years
                     && ddClass.GetMonths() == months
                     && ddClass.GetDays() == days)
                    ||
                    (ddClass.GetYears() == yearsAlt
                     && ddClass.GetMonths() == monthsAlt
                     && ddClass.GetDays() == daysAlt));

    Assert.IsTrue(success);
  }
}

Most of the names are slightly silly and don't really explain why code might fail the test, however looking at the two dates and the answer(s) should be enough to understand the test.

There are two functions that do all the Asserts, CheckResults() and CheckControversialResults(). These work well to save typing and give the right results, but unfortunately they make it harder to see exactly what went wrong (because the Assert in CheckControversialResults() will fail with "Expected true", rather than telling you which value was incorrect. If anyone has a better way to do this (avoid writing the same checks each time, but have more useful error messages) please let me know.

CheckControversialResults() is used for a couple of cases where there seem to be two different opinions on what is right. I have an opinion of my own, but I thought I should be liberal in what I accepted here. The gist of this is deciding whether one year after Feb 29 is Feb 28 or Mar 1.

These tests are the crux of the matter, and there could very well be errors in them, so please do comment if you find one which is wrong. It would be also good to hear some suggestions for other tests to check any future iterations of answers.

No test involves time of day - all DateTimes are at midnight. Including times, as long as it's clear how rounding up and down to days works (I think it is), might show up even more flaws.

The results

The complete scoreboard of results is as follows:

ChuckRostance_Test 3 failures               S S S F S S F S F
Dave_Test 6 failures                        F F S F F F F S S
Dylan_Hayes_Test 9 failures                 F F F F F F F F F
ho1_Test 3 failures                         F F S S S S F S S
Jani_Test 6 failures                        F F S F F F F S S
Jon_Test 1 failure                          S S S S S S F S S
lc_Test 2 failures                          S S S S S F F S S
LukeH_Test 1 failure                        S S S S S S F S S
Malu_MN_Test 1 failure                      S S S S S S S F S
Mohammed_Ijas_Nasirudeen_Test 2 failures    F S S F S S S S S
pk_Test 6 failures                          F F F S S F F F S
Rajeshwaran_S_P_Test 7 failures             F F S F F S F F F
ruffin_Test 3 failures                      F S S F S S F S S
this_curious_geek_Test 2 failures           F S S F S S S S S

But note that Jani's solution was actually correct and passed all tests - see update 4 below.

The columns are in alphabetical order of test name:

  • AlmostThreeYearsTest
  • AlmostTwoYearsTest
  • BasicTest
  • BornOnALeapYearTest
  • BornOnALeapYearTest2
  • LongMonthToLongMonth
  • LongMonthToLongMonthPenultimateDay
  • LongMonthToPartWayThruShortMonth
  • LongMonthToShortMonth

Three answers failed only 1 test each, Jon's, LukeH's and Manu MN's. Bear in mind these tests were probably written specifically to address flaws in those answers.

Every test was passed by at least one piece of code, which is slightly reassuring that none of the tests are erroneous.

Some answers failed a lot of tests. I hope no-one feels this is a condemnation of that poster's efforts. Firstly the number of successes is fairly arbitrary as the tests don't evenly cover the problem areas of the question space. Secondly this is not production code - answers are posted so people can learn from them, not copy them exactly into their programs. Code which fails a lot of tests can still have great ideas in it. At least one piece which failed a lot of tests had a small bug in it which I didn't fix. I'm grateful to anyone who took the time to share their work with everyone else, for making this project so interesting.

My conclusions

There are three:

  1. Calendars are hard. I wrote nine tests, including three where two answers are possible. Some of the tests where I only had one answer might not be unanimously agreed with. Just thinking about exactly what we mean when we say '1 month later' or '2 years earlier' is tricky in a lot of situations. And none of this code had to deal with all the complexities of things like working out when leap years are. All of it uses library code to handle dates. If you imagine the 'spec' for telling time in days, weeks, months and years written out, there's all sorts of cruft. Because we know it pretty well since primary school, and use it everyday, we are blind to many of the idiosyncracies. The question is not an academic one - various types of decomposition of time periods into years, quarters and months are essential in accounting software for bonds and other financial products.

  2. Writing correct code is hard. There were a lot of bugs. In slightly more obscure topics or less popular questions than the chances of a bug existing without having been pointed out by a commenter are much, much higher than for this question. You should really never, never copy code from SO into your program without understanding exactly what it does. The flipside of this is that you probably shouldn't write code in your answer that is ready to be copied and pasted, but rather intelligent and expressive pseudo-code that allows someone to understand the solution and implement their own version (with their own bugs!)

  3. Unit tests are helpful. I am still meaning to post my own solution to this when I get round to it (for someone else to find the hidden, incorrect assumptions in!) Doing this was a great example of 'saving the bugs' by turning them into unit tests to fix the next version of the code with.

Update

The whole project is now at https://github.com/jwg4/date-difference This includes my own attempt jwg.cs, which passes all the tests I currently have, including a few new ones which check for proper time of day handling. Feel free to add either more tests to break this and other implementations or better code for answering the question.

Update 2

@MattJohnson has added an implementation which uses Jon Skeet's NodaTime. It passes all the current tests.

Update 3

@KirkWoll's answer to Difference in months between two dates has been added to the project on github. It passes all the current tests.

Update 4

@Jani pointed out in a comment that I had used his code wrongly. He did suggest methods that counted the years, months and days correctly, (alongside some which count the total number of days and months, not the remainders) however I mistakenly used the wrong ones in my test code. I have corrected my wrapper around his code and it now passes all tests. There are now four correct solutions, of which Jani's was the first. Two use libraries (Intenso.TimePeriod and NodaTime) and two are written from scratch.

What is the App_Data folder used for in Visual Studio?

From the documentation about ASP.NET Web Project Folder Structure in MSDN:

You can keep your Web project's files in any folder structure that is convenient for your application. To make it easier to work with your application, ASP.NET reserves certain file and folder names that you can use for specific types of content.

App_Data contains application data files including .mdf database files, XML files, and other data store files. The App_Data folder is used by ASP.NET to store an application's local database, such as the database for maintaining membership and role information. For more information, see Introduction to Membership and Understanding Role Management.

What are the main performance differences between varchar and nvarchar SQL Server data types?

For that last few years all of our projects have used NVARCHAR for everything, since all of these projects are multilingual. Imported data from external sources (e.g. an ASCII file, etc.) is up-converted to Unicode before being inserted into the database.

I've yet to encounter any performance-related issues from the larger indexes, etc. The indexes do use more memory, but memory is cheap.

Whether you use stored procedures or construct SQL on the fly ensure that all string constants are prefixed with N (e.g. SET @foo = N'Hello world.';) so the constant is also Unicode. This avoids any string type conversion at runtime.

YMMV.

How do you change video src using jQuery?

JQUERY

_x000D_
_x000D_
<script type="text/javascript">_x000D_
$(document).ready(function() {_x000D_
  var videoID = 'videoclip';_x000D_
  var sourceID = 'mp4video';_x000D_
  var newmp4 = 'media/video2.mp4';_x000D_
  var newposter = 'media/video-poster2.jpg';_x000D_
 _x000D_
  $('#videolink1').click(function(event) {_x000D_
    $('#'+videoID).get(0).pause();_x000D_
    $('#'+sourceID).attr('src', newmp4);_x000D_
    $('#'+videoID).get(0).load();_x000D_
     //$('#'+videoID).attr('poster', newposter); //Change video poster_x000D_
    $('#'+videoID).get(0).play();_x000D_
  });_x000D_
});
_x000D_
_x000D_
_x000D_

Before and After Suite execution hook in jUnit 4.x

Here, we

  • upgraded to JUnit 4.5,
  • wrote annotations to tag each test class or method which needed a working service,
  • wrote handlers for each annotation which contained static methods to implement the setup and teardown of the service,
  • extended the usual Runner to locate the annotations on tests, adding the static handler methods into the test execution chain at the appropriate points.

Is a DIV inside a TD a bad idea?

I have faced the problem by placing a <div> inside <td>.

I was unable to identify the div using document.getElementById() if i place that inside td. But outside, it was working fine.

Table scroll with HTML and CSS

<div style="overflow:auto">
    <table id="table2"></table>
</div>

Try this code for overflow table it will work only on div tag

Webdriver findElements By xpath

Instead of

css=#container

use

css=div.container:nth-of-type(1),css=div.container:nth-of-type(2)

android: changing option menu items programmatically

In case you have a BottomBar:

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    if (mBottomBar.getCurrentTabId() == R.id.tab_more) {
        getMenuInflater().inflate(R.menu.more_menu, menu);
    }

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.preferences:
            startActivity(new Intent(this, PreferenceActivity.class));
            break;
    }

    return super.onOptionsItemSelected(item);
}

Then you just need to call:

@Override
public void onBottomBarClick(int tabId) {
    supportInvalidateOptionsMenu();
}

String is immutable. What exactly is the meaning?

String is immutable it means that,the content of the String Object can't be change, once it is created. If you want to modify the content then you can go for StringBuffer/StringBuilder instead of String. StringBuffer and StringBuilder are mutable classes.

applying css to specific li class

I only see one color being specified (albeit you specify it in two different places.) Either you've omitted some of your style rules, or you simply didn't specify another color.

Runnable with a parameter?

theView.post(new Runnable() {
    String str;
    @Override                            
    public void run() {
        par.Log(str);                              
    }
    public Runnable init(String pstr) {
        this.str=pstr;
        return(this);
    }
}.init(str));

Create init function that returns object itself and initialize parameters with it.

Invert match with regexp

You can also do this (in python) by using re.split, and splitting based on your regular expression, thus returning all the parts that don't match the regex, splitting based on what doesn't match a regularexpression

Android: adbd cannot run as root in production builds

You have to grant the Superuser right to the shell app (com.anroid.shell). In my case, I use Magisk to root my phone Nexsus 6P (Oreo 8.1). So I can grant Superuser right in the Magisk Manager app, whih is in the left upper option menu.

Correct way to use StringBuilder in SQL

You are correct in guessing that the aim of using string builder is not achieved, at least not to its full extent.

However, when the compiler sees the expression "select id1, " + " id2 " + " from " + " table" it emits code which actually creates a StringBuilder behind the scenes and appends to it, so the end result is not that bad afterall.

But of course anyone looking at that code is bound to think that it is kind of retarded.

Importing modules from parent folder

Relative imports (as in from .. import mymodule) only work in a package. To import 'mymodule' that is in the parent directory of your current module:

import os,sys,inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir) 

import mymodule

edit: the __file__ attribute is not always given. Instead of using os.path.abspath(__file__) I now suggested using the inspect module to retrieve the filename (and path) of the current file

How can I determine if a String is non-null and not only whitespace in Groovy?

You could add a method to String to make it more semantic:

String.metaClass.getNotBlank = { !delegate.allWhitespace }

which let's you do:

groovy:000> foo = ''
===> 
groovy:000> foo.notBlank
===> false
groovy:000> foo = 'foo'
===> foo
groovy:000> foo.notBlank
===> true

How to run Ruby code from terminal?

You can run ruby commands in one line with the -e flag:

ruby -e "puts 'hi'"

Check the man page for more information.

How to set up Spark on Windows?

Here is a simple minimum script to run from any python console. It assumes that you have extracted the Spark libraries that you have downloaded into C:\Apache\spark-1.6.1.

This works in Windows without building anything and solves problems where Spark would complain about recursive pickling.

import sys
import os
spark_home = 'C:\Apache\spark-1.6.1'

sys.path.insert(0, os.path.join(spark_home, 'python'))
sys.path.insert(0, os.path.join(spark_home, 'python\lib\pyspark.zip')) 
sys.path.insert(0, os.path.join(spark_home, 'python\lib\py4j-0.9-src.zip')) 

# Start a spark context:
sc = pyspark.SparkContext()

# 
lines = sc.textFile(os.path.join(spark_home, "README.md")
pythonLines = lines.filter(lambda line: "Python" in line)
pythonLines.first()

How to add http:// if it doesn't exist in the URL

nickf's solution modified:

function addhttp($url) {
    if (!preg_match("@^https?://@i", $url) && !preg_match("@^ftps?://@i", $url)) {
        $url = "http://" . $url;
    }
    return $url;
}

VBScript -- Using error handling

I'm exceptionally new to VBScript, so this may not be considered best practice or there may be a reason it shouldn't be done this that way I'm not yet aware of, but this is the solution I came up with to trim down the amount of error logging code in my main code block.

Dim oConn, connStr
Set oConn = Server.CreateObject("ADODB.Connection")
connStr = "Provider=SQLOLEDB;Server=XX;UID=XX;PWD=XX;Databse=XX"

ON ERROR RESUME NEXT

oConn.Open connStr
If err.Number <> 0 Then : showError() : End If


Sub ShowError()

    'You could write the error details to the console...
    errDetail = "<script>" & _
    "console.log('Description: " & err.Description & "');" & _
    "console.log('Error number: " & err.Number & "');" & _
    "console.log('Error source: " & err.Source & "');" & _
    "</script>"

    Response.Write(errDetail)       

    '...you could display the error info directly in the page...
    Response.Write("Error Description: " & err.Description)
    Response.Write("Error Source: " & err.Source)
    Response.Write("Error Number: " & err.Number)

    '...or you could execute additional code when an error is thrown...
    'Insert error handling code here

    err.clear
End Sub

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

If you want them both on the same page and they'll both take up basically the whole page, then the best idea is to tell LaTeX to put them both on a page of their own!

\begin{figure}[p]

It would probably be against sound typographic principles (e.g., ugly) to have two figures on a page with only a few lines of text above or below them.


By the way, the reason that [!h] works is because it's telling LaTeX to override its usual restrictions on how much space should be devoted to floats on a page with text. As implied above, there's a reason the restrictions are there. Which isn't to say they can be loosened somewhat; see the FAQ on doing that.

Today's Date in Perl in MM/DD/YYYY format

If you like doing things the hard way:

my (undef,undef,undef,$mday,$mon,$year) = localtime;
$year = $year+1900;
$mon += 1;
if (length($mon)  == 1) {$mon = "0$mon";}
if (length($mday) == 1) {$mday = "0$mday";}
my $today = "$mon/$mday/$year";

accessing a variable from another class

Filename=url.java

public class url {

    public static final String BASEURL = "http://192.168.1.122/";

}

if u want to call the variable just use this:

url.BASEURL + "your code here";

background-image: url("images/plaid.jpg") no-repeat; wont show up

    <style>
    background: url(images/Untitled-2.fw.png);
background-repeat:no-repeat;
background-position:center;
background-size: cover;
    </style>

Python object.__repr__(self) should be an expression?

"but does that mean it should just be an example of the sort of expression you could use, or should it be an actual expression, that can be executed (eval etc..) to recreate the object? Or... should it be just a rehasing of the actual expression which was used, for pure information purposes?"

Wow, that's a lot of hand-wringing.

  1. An "an example of the sort of expression you could use" would not be a representation of a specific object. That can't be useful or meaningful.

  2. What is the difference between "an actual expression, that can ... recreate the object" and "a rehasing of the actual expression which was used [to create the object]"? Both are an expression that creates the object. There's no practical distinction between these. A repr call could produce either a new expression or the original expression. In many cases, they're the same.

Note that this isn't always possible, practical or desirable.

In some cases, you'll notice that repr() presents a string which is clearly not an expression of any kind. The default repr() for any class you define isn't useful as an expression.

In some cases, you might have mutual (or circular) references between objects. The repr() of that tangled hierarchy can't make sense.

In many cases, an object is built incrementally via a parser. For example, from XML or JSON or something. What would the repr be? The original XML or JSON? Clearly not, since they're not Python. It could be some Python expression that generated the XML. However, for a gigantic XML document, it might not be possible to write a single Python expression that was the functional equivalent of parsing XML.

How to workaround 'FB is not defined'?

You were very close with your original example. You could either use @jAndy's suggestion or:

if (typeof FB != 'undefined')

When is it appropriate to use UDP instead of TCP?

If a TCP packet is lost, it will be resent. That is not handy for applications that rely on data being handled in a specific order in real time.

Examples include video streaming and especially VoIP (e.g. Skype). In those instances, however, a dropped packet is not such a big deal: our senses aren't perfect, so we may not even notice. That is why these types of applications use UDP instead of TCP.

Change a Rails application to production

It is not a good way to run rails server in production environment by "rails server -e production", because then rails runs as a single-threaded application, and can only respond to one HTTP request at a time.

The best article about production environment for rails is Production Environments - Rails 3

How do I subscribe to all topics of a MQTT broker

Concrete example

mosquitto.org is very active (at the time of this posting). This is a nice smoke test for a MQTT subscriber linux device:

mosquitto_sub -h test.mosquitto.org -t "#" -v

The "#" is a wildcard for topics and returns all messages (topics): the server had a lot of traffic, so it returned a 'firehose' of messages.

If your MQTT device publishes a topic of irisys/V4D-19230005/ to the test MQTT broker , then you could filter the messages:

mosquitto_sub -h test.mosquitto.org -t "irisys/V4D-19230005/#" -v

Options:

  • -h the hostname (default MQTT port = 1883)
  • -t precedes the topic

Notepad++ incrementally replace

I was looking for the same feature today but couldn't do this in Notepad++. However, we have TextPad to our rescue. It worked for me.

In TextPad's replace dialog, turn on regex; then you could try replacing

<row id="1"/>

by

<row id="\i"/>

Have a look at this link for further amazing replace features of TextPad - http://sublimetext.userecho.com/topic/106519-generate-a-sequence-of-numbers-increment-replace/

Failed to load resource: the server responded with a status of 404 (Not Found) css

Use the following Code:-

../css/main.css

Note: The "../" is shorthand for "The containing directory", or "Up one directory".

If you don't know the previous folder this will be very helpful..

How do I create a file and write to it?

Reading collection with customers and saving to file, with JFilechooser.

private void writeFile(){

    JFileChooser fileChooser = new JFileChooser(this.PATH);
    int retValue = fileChooser.showDialog(this, "Save File");

    if (retValue == JFileChooser.APPROVE_OPTION){

        try (Writer fileWrite = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileChooser.getSelectedFile())))){

            this.customers.forEach((c) ->{
                try{
                    fileWrite.append(c.toString()).append("\n");
                }
                catch (IOException ex){
                    ex.printStackTrace();
                }
            });
        }
        catch (IOException e){
            e.printStackTrace();
        }
    }
}

Reading *.wav files in Python

You can accomplish this using the scikits.audiolab module. It requires NumPy and SciPy to function, and also libsndfile.

Note, I was only able to get it to work on Ubunutu and not on OSX.

from scikits.audiolab import wavread

filename = "testfile.wav"

data, sample_frequency,encoding = wavread(filename)

Now you have the wav data

How do you check if a variable is an array in JavaScript?

For those who code-golf, an unreliable test with fewest characters:

function isArray(a) {
  return a.map;
}

This is commonly used when traversing/flattening a hierarchy:

function golf(a) {
  return a.map?[].concat.apply([],a.map(golf)):a;
}

input: [1,2,[3,4,[5],6],[7,[8,[9]]]]
output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

curl POST format for CURLOPT_POSTFIELDS

EDIT: From php5 upwards, usage of http_build_query is recommended:

string http_build_query ( mixed $query_data [, string $numeric_prefix [, 
                          string $arg_separator [, int $enc_type = PHP_QUERY_RFC1738 ]]] )

Simple example from the manual:

<?php
$data = array('foo'=>'bar',
              'baz'=>'boom',
              'cow'=>'milk',
              'php'=>'hypertext processor');

echo http_build_query($data) . "\n";

/* output:
foo=bar&baz=boom&cow=milk&php=hypertext+processor
*/

?>

before php5:

From the manual:

CURLOPT_POSTFIELDS

The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with @ and use the full path. The filetype can be explicitly specified by following the filename with the type in the format ';type=mimetype'. This parameter can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data. As of PHP 5.2.0, files thats passed to this option with the @ prefix must be in array form to work.

So something like this should work perfectly (with parameters passed in a associative array):

function preparePostFields($array) {
  $params = array();

  foreach ($array as $key => $value) {
    $params[] = $key . '=' . urlencode($value);
  }

  return implode('&', $params);
}

Case-insensitive search in Rails model

user = Product.where(email: /^#{email}$/i).first

Format a datetime into a string with milliseconds

To get a date string with milliseconds (3 decimal places behind seconds), use this:

from datetime import datetime

print datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]

>>>> OUTPUT >>>>
2020-05-04 10:18:32.926

Note: For Python3, print requires parentheses:

print(datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])

Display fullscreen mode on Tkinter

Yeah mate i was trying to do the same in windows, and what helped me was a bit of lambdas with the root.state() method.

root = Tk()
root.bind('<Escape>', lambda event: root.state('normal'))
root.bind('<F11>', lambda event: root.state('zoomed'))

How can I install pip on Windows?

Updated at 2016 : Pip should already be included in Python 2.7.9+ or 3.4+, but if for whatever reason it is not there, you can use the following one-liner.

PS:

  1. This should already be satisfied in most cases but, if necessary, be sure that your environment variable PATH includes Python's folders (for example, Python 2.7.x on Windows default install: C:\Python27 and C:\Python27\Scripts, for Python 3.3x: C:\Python33 and C:\Python33\Scripts, etc)

  2. I encounter same problem and then found such perhaps easiest way (one liner!) mentioned on official website here: http://www.pip-installer.org/en/latest/installing.html

Can't believe there are so many lengthy (perhaps outdated?) answers out there. Feeling thankful to them but, please up-vote this short answer to help more new comers!

How can I stop .gitignore from appearing in the list of untracked files?

This seems to only work for your current directory to get Git to ignore all files from the repository.

update this file

.git/info/exclude 

with your wild card or filename

*pyc
*swp
*~

Java "?" Operator for checking null - What is it? (Not Ternary!)

There you have it, null-safe invocation in Java 8:

public void someMethod() {
    String userName = nullIfAbsent(new Order(), t -> t.getAccount().getUser()
        .getName());
}

static <T, R> R nullIfAbsent(T t, Function<T, R> funct) {
    try {
        return funct.apply(t);
    } catch (NullPointerException e) {
        return null;
    }
}

Automated testing for REST Api

I used SOAP UI for functional and automated testing. SOAP UI allows you to run the tests on the click of a button. There is also a spring controllers testing page created by Ted Young. I used this article to create Rest unit tests in our application.

How to find unused/dead code in java projects

I would instrument the running system to keep logs of code usage, and then start inspecting code that is not used for months or years.

For example if you are interested in unused classes, all classes could be instrumented to log when instances are created. And then a small script could compare these logs against the complete list of classes to find unused classes.

Of course, if you go at the method level you should keep performance in mind. For example, the methods could only log their first use. I dont know how this is best done in Java. We have done this in Smalltalk, which is a dynamic language and thus allows for code modification at runtime. We instrument all methods with a logging call and uninstall the logging code after a method has been logged for the first time, thus after some time no more performance penalties occur. Maybe a similar thing can be done in Java with static boolean flags...

GridView must be placed inside a form tag with runat="server" even after the GridView is within a form tag

Just want to add another way of doing this. I've seen multiple people on various related threads ask if you can use VerifyRenderingInServerForm without adding it to the parent page.

You actually can do this but it's a bit of a bodge.

First off create a new Page class which looks something like the following:

public partial class NoRenderPage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    { }

    public override void VerifyRenderingInServerForm(Control control)
    {
        //Allows for printing
    }

    public override bool EnableEventValidation
    {
        get { return false; }
        set { /*Do nothing*/ }
    }
}

Does not need to have an .ASPX associated with it.

Then in the control you wish to render you can do something like the following.

    StringWriter tw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(tw);

    var page = new NoRenderPage();
    page.DesignerInitialize();
    var form = new HtmlForm();
    page.Controls.Add(form);
    form.Controls.Add(pnl);
    controlToRender.RenderControl(hw);

Now you've got your original control rendered as HTML. If you need to, add the control back into it's original position. You now have the HTML rendered, the page as normal and no changes to the page itself.

Setting transparent images background in IrfanView

If you are using the batch conversion, in the window click "options" in the "Batch conversion settings-output format" and tick the two boxes "save transparent color" (one under "PNG" and the other under "ICO").

Finding current executable's path without /proc/self/exe

You can use argv[0] and analyze the PATH environment variable. Look at : A sample of a program that can find itself

Why don’t my SVG images scale using the CSS "width" property?

SVGs are different than bitmap images such as PNG etc. If an SVG has a viewBox - as yours appear to - then it will be scaled to fit it's defined viewport. It won't directly scale like a PNG would.

So increasing the width of the img won't make the icons any taller if the height is restricted. You'll just end up with the img horizontally centred in a wider box.

I believe your problem is that your SVGs have a fixed height defined in them. Open up the SVG files and make sure they either:

  1. have no width and height defined, or
  2. have width and height both set to "100%".

That should solve your problem. If it doesn't, post one of your SVGs into your question so we can see how it is defined.

Split bash string by newline characters

There is another way if all you want is the text up to the first line feed:

x='some
thing'

y=${x%$'\n'*}

After that y will contain some and nothing else (no line feed).

What is happening here?

We perform a parameter expansion substring removal (${PARAMETER%PATTERN}) for the shortest match up to the first ANSI C line feed ($'\n') and drop everything that follows (*).

Merging multiple PDFs using iTextSharp in c#.net

I found a very nice solution on this site : http://weblogs.sqlteam.com/mladenp/archive/2014/01/10/simple-merging-of-pdf-documents-with-itextsharp-5-4-5.aspx

I update the method in this mode :

    public static bool MergePDFs(IEnumerable<string> fileNames, string targetPdf)
    {
        bool merged = true;
        using (FileStream stream = new FileStream(targetPdf, FileMode.Create))
        {
            Document document = new Document();
            PdfCopy pdf = new PdfCopy(document, stream);
            PdfReader reader = null;
            try
            {
                document.Open();
                foreach (string file in fileNames)
                {
                    reader = new PdfReader(file);
                    pdf.AddDocument(reader);
                    reader.Close();
                }
            }
            catch (Exception)
            {
                merged = false;
                if (reader != null)
                {
                    reader.Close();
                }
            }
            finally
            {
                if (document != null)
                {
                    document.Close();
                }
            }
        }
        return merged;
    }

Quicksort: Choosing the pivot

It is entirely dependent on how your data is sorted to begin with. If you think it will be pseudo-random then your best bet is to either pick a random selection or choose the middle.

How do I get hour and minutes from NSDate?

Swift 2.0

    let dateNow = NSDate()
    let calendar = NSCalendar.currentCalendar()
    let hour = calendar.component(NSCalendarUnit.Hour, fromDate: dateNow)
    let minute = calendar.component(NSCalendarUnit.Minute, fromDate: dateNow)
    print(String(hour))
    print(String(minute))

Please do take note of the cast to String in the print statement, you can easily assign that value to variables, like this:

var hoursString = String(hour)
var minutesString = String(minute)

Then you can concatenate values like this:

var compoundString = "\(hour):\(minute)"
print(compoundString)

check if array is empty (vba excel)

@jeminar has the best solution above.

I cleaned it up a bit though.

I recommend adding this to a FunctionsArray module

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

Python + Django page redirect

It's simple:

from django.http import HttpResponseRedirect

def myview(request):
    ...
    return HttpResponseRedirect("/path/")

More info in the official Django docs

Update: Django 1.0

There is apparently a better way of doing this in Django now using generic views.

Example -

from django.views.generic.simple import redirect_to

urlpatterns = patterns('',   
    (r'^one/$', redirect_to, {'url': '/another/'}),

    #etc...
)

There is more in the generic views documentation. Credit - Carles Barrobés.

Update #2: Django 1.3+

In Django 1.5 redirect_to no longer exists and has been replaced by RedirectView. Credit to Yonatan

from django.views.generic import RedirectView

urlpatterns = patterns('',
    (r'^one/$', RedirectView.as_view(url='/another/')),
)

What is the maximum length of data I can put in a BLOB column in MySQL?

A BLOB can be 65535 bytes maximum. If you need more consider using a MEDIUMBLOB for 16777215 bytes or a LONGBLOB for 4294967295 bytes.

Hope, it will help you.

How do you select a particular option in a SELECT element in jQuery?

if you want to not use jQuery, you can use below code:

document.getElementById("mySelect").selectedIndex = "2";

Why fragments, and when to use fragments instead of activities?

Activities are the full screen components in the app with the toolbar, everything else are preferably Fragments. One full screen parent activity with a toolbar can have multiple panes, scrollable pages, dialogs, etc. (all fragments), all of which can be accessed from the parent and communicate via the parent.

Example:

Activity A, Activity B, Activity C:

  • All activities need to have same code repeated, to show a basic toolbar for example, or inherit from a parent activity (becomes cumbersome to manage).
  • To move from one activity to the other, either all of them need to be in memory (overhead) or one needs to be destroyed for the other to open.
  • Communication between activities can be done via Intents.

vs

Activity A, Fragment 1, Fragment 2, Fragment 3:

  • No code repetition, all screens have toolbars etc. from that one activity.
  • Several ways to move from one fragment to next - view pager, multi pane etc.
  • Activity has most data, so minimal inter-fragment communication needed. If still necessary, can be done via interfaces easily.
  • Fragments do not need to be full screen, lots of flexibility in designing them.
  • Fragments do not need to inflate layout if views are not necessary.
  • Several activities can use the same fragment.

Create a string with n characters

Since Java 11 you can simply use String.repeat(count) to solve your problem.

Returns a string whose value is the concatenation of this string repeated count times.

If this string is empty or count is zero then the empty string is returned.

So instead of a loop your code would just look like this:

" ".repeat(length);

How to get value at a specific index of array In JavaScript?

You can just use []:

var valueAtIndex1 = myValues[1];

Better way to revert to a previous SVN revision of a file?

svn merge -r 854:853 l3toks.dtx

or

svn merge -c -854 l3toks.dtx

The two commands are equivalent.

Can I pass a JavaScript variable to another browser window?

Yes, it can be done as long as both windows are on the same domain. The window.open() function will return a handle to the new window. The child window can access the parent window using the DOM element "opener".

Node - how to run app.js?

Node is complaining because there is no function called define, which your code tries to call on its very first line.

define comes from AMD, which is not used in standard node development.

It is possible that the developer you got your project from used some kind of trickery to use AMD in node. You should ask this person what special steps are necessary to run the code.

How to get controls in WPF to fill available space?

Well, I figured it out myself, right after posting, which is the most embarassing way. :)

It seems every member of a StackPanel will simply fill its minimum requested size.

In the DockPanel, I had docked things in the wrong order. If the TextBox or ListBox is the only docked item without an alignment, or if they are the last added, they WILL fill the remaining space as wanted.

I would love to see a more elegant method of handling this, but it will do.

round() for float in C++

It may be worth noting that if you wanted an integer result from the rounding you don't need to pass it through either ceil or floor. I.e.,

int round_int( double r ) {
    return (r > 0.0) ? (r + 0.5) : (r - 0.5); 
}

AssertNull should be used or AssertNotNull

assertNotNull asserts that the object is not null. If it is null the test fails, so you want that.

Tomcat view catalina.out log file

Try using this:

sudo tail -f /opt/tomcat/logs/catalina.out

Perl: Use s/ (replace) and return new string

print "bla: ", $_, "\n" if ($_ = $myvar) =~ s/a/b/g or 1;

Initializing array of structures

It's called designated initializer which is introduced in C99. It's used to initialize struct or arrays, in this example, struct.

Given

struct point { 
    int x, y;
};

the following initialization

struct point p = { .y = 2, .x = 1 };

is equivalent to the C89-style

struct point p = { 1, 2 };

Save attachments to a folder and rename them

This is my Save Attachments script. You select all the messages that you want the attachments saved from, and it will save a copy there. It also adds text to the message body indicating where the attachment is saved. You could easily change the folder name to include the date, but you would need to make sure the folder existed before starting to save files.

Public Sub SaveAttachments()
Dim objOL As Outlook.Application
Dim objMsg As Outlook.MailItem 'Object
Dim objAttachments As Outlook.Attachments
Dim objSelection As Outlook.Selection
Dim i As Long
Dim lngCount As Long
Dim strFile As String
Dim strFolderpath As String
Dim strDeletedFiles As String

' Get the path to your My Documents folder
strFolderpath = CreateObject("WScript.Shell").SpecialFolders(16)
On Error Resume Next

' Instantiate an Outlook Application object.
Set objOL = CreateObject("Outlook.Application")

' Get the collection of selected objects.
Set objSelection = objOL.ActiveExplorer.Selection

' Set the Attachment folder.
strFolderpath = strFolderpath & "\Attachments\"

' Check each selected item for attachments. If attachments exist,
' save them to the strFolderPath folder and strip them from the item.
For Each objMsg In objSelection

    ' This code only strips attachments from mail items.
    ' If objMsg.class=olMail Then
    ' Get the Attachments collection of the item.
    Set objAttachments = objMsg.Attachments
    lngCount = objAttachments.Count
    strDeletedFiles = ""

    If lngCount > 0 Then

        ' We need to use a count down loop for removing items
        ' from a collection. Otherwise, the loop counter gets
        ' confused and only every other item is removed.

        For i = lngCount To 1 Step -1

            ' Save attachment before deleting from item.
            ' Get the file name.
            strFile = objAttachments.Item(i).FileName

            ' Combine with the path to the Temp folder.
            strFile = strFolderpath & strFile

            ' Save the attachment as a file.
            objAttachments.Item(i).SaveAsFile strFile

            ' Delete the attachment.
            objAttachments.Item(i).Delete

            'write the save as path to a string to add to the message
            'check for html and use html tags in link
            If objMsg.BodyFormat <> olFormatHTML Then
                strDeletedFiles = strDeletedFiles & vbCrLf & "<file://" & strFile & ">"
            Else
                strDeletedFiles = strDeletedFiles & "<br>" & "<a href='file://" & _
                strFile & "'>" & strFile & "</a>"
            End If

            'Use the MsgBox command to troubleshoot. Remove it from the final code.
            'MsgBox strDeletedFiles

        Next i

        ' Adds the filename string to the message body and save it
        ' Check for HTML body
        If objMsg.BodyFormat <> olFormatHTML Then
            objMsg.Body = vbCrLf & "The file(s) were saved to " & strDeletedFiles & vbCrLf & objMsg.Body
        Else
            objMsg.HTMLBody = "<p>" & "The file(s) were saved to " & strDeletedFiles & "</p>" & objMsg.HTMLBody
        End If
        objMsg.Save
    End If
Next

ExitSub:

Set objAttachments = Nothing
Set objMsg = Nothing
Set objSelection = Nothing
Set objOL = Nothing
End Sub

Adding devices to team provisioning profile

There are two types of provisioning profiles.

  • development and
  • distribution

When app is live on app store then distribution profiles works and do not need any devices to be added.

Only development profiles need to add devices.In order to do so these are the steps-

  1. Login to developer.apple.com member centre.
  2. Go to Certificates, Identifiers & Profiles.
  3. Get UDID of your device and add it in the devices.
  4. Select a developer provisioning profile and edit it.
  5. Click on check box next to the device you just added.
  6. Generate and download the profile.
  7. Double click on it to install it.
  8. Connect your device and retry.

This worked for me hope it works for you.

How to read a list of files from a folder using PHP?

There is also a really simple way to do this with the help of the RecursiveTreeIterator class, answered here: https://stackoverflow.com/a/37548504/2032235

How do I find the number of arguments passed to a Bash script?

#!/bin/bash
echo "The number of arguments is: $#"
a=${@}
echo "The total length of all arguments is: ${#a}: "
count=0
for var in "$@"
do
    echo "The length of argument '$var' is: ${#var}"
    (( count++ ))
    (( accum += ${#var} ))
done
echo "The counted number of arguments is: $count"
echo "The accumulated length of all arguments is: $accum"

Pandas (python): How to add column to dataframe for index?

How about this:

from pandas import *

idx = Int64Index([171, 174, 173])
df = DataFrame(index = idx, data =([1,2,3]))
print df

It gives me:

     0
171  1
174  2
173  3

Is this what you are looking for?

Checking if a worksheet-based checkbox is checked

Building on the previous answers, you can leverage the fact that True is -1 and False is 0 and shorten your code like this:

Sub Button167_Click()
  Range("Y12").Value = _
    Abs(Worksheets(1).Shapes("Check Box 1").OLEFormat.Object.Value > 0)
End Sub

If the checkbox is checked, .Value = 1.

Worksheets(1).Shapes("Check Box 1").OLEFormat.Object.Value > 0 returns True.

Applying the Abs function converts True to 1.

If the checkbox is unchecked, .Value = -4146.

Worksheets(1).Shapes("Check Box 1").OLEFormat.Object.Value > 0 returns False.

Applying the Abs function converts False to 0.

Postfix is installed but how do I test it?

To check whether postfix is running or not

sudo postfix status

If it is not running, start it.

sudo postfix start

Then telnet to localhost port 25 to test the email id

ehlo localhost
mail from: root@localhost
rcpt to: your_email_id
data
Subject: My first mail on Postfix

Hi,
Are you there?
regards,
Admin
.

Do not forget the . at the end, which indicates end of line

How to search for an element in an stl list?

No, find() method is not a member of std::list. Instead, use std::find from <algorithm>

    std :: list < int > l;
    std :: list < int > :: iterator pos;

    l.push_back(1);
    l.push_back(2);
    l.push_back(3);
    l.push_back(4);
    l.push_back(5);
    l.push_back(6);

    int elem = 3;   
    pos = find(l.begin() , l.end() , elem);
    if(pos != l.end() )
        std :: cout << "Element is present. "<<std :: endl;
    else
        std :: cout << "Element is not present. "<<std :: endl;

System.out.println() shortcut on Intellij IDEA

Yeah, you can do it. Just open Settings -> Live Templates. Create new one with syso as abbreviation and System.out.println($END$); as Template text.

Try reinstalling `node-sass` on node 0.12?

Downgrading Node to 0.10.36 should do it per this thread on the node-sass github page: https://github.com/sass/node-sass/issues/490#issuecomment-70388754

If you have NVM you can just:

nvm install 0.10

If you don't, you can find NVM and instructions here: https://www.npmjs.com/package/nvm

iOS app with framework crashed on device, dyld: Library not loaded, Xcode 6 Beta

If have development pod Delete your app from simulator install from pod -> clean - > run again...

Adding custom HTTP headers using JavaScript

As already said, the easiest way is to use querystring.

But if you cannot, because of security reason, you should consider using cookies.

Install Application programmatically on Android

Try this - Write on Manifest:

uses-permission android:name="android.permission.INSTALL_PACKAGES"
        tools:ignore="ProtectedPermissions"

Write the Code:

File sdCard = Environment.getExternalStorageDirectory();
String fileStr = sdCard.getAbsolutePath() + "/Download";// + "app-release.apk";
File file = new File(fileStr, "app-release.apk");
Intent promptInstall = new Intent(Intent.ACTION_VIEW).setDataAndType(Uri.fromFile(file),
                        "application/vnd.android.package-archive");

startActivity(promptInstall);

Maven package/install without test (skip tests)

Below two commands are most useful

mvn clean package -Dmaven.test.skip=true 
mvn clean package -DskipTests

Thanks

Formatting html email for Outlook

I used VML(Vector Markup Language) based formatting in my email template. In VML Based you have write your code within comment I took help from this site.

https://litmus.com/blog/a-guide-to-bulletproof-buttons-in-email-design#supporttable

The most efficient way to implement an integer based power function pow(int, int)

If you want to get the value of an integer for 2 raised to the power of something it is always better to use the shift option:

pow(2,5) can be replaced by 1<<5

This is much more efficient.

How to import the class within the same directory or sub directory?

You can import the module and have access through its name if you don't want to mix functions and classes with yours

import util # imports util.py

util.clean()
util.setup(4)

or you can import the functions and classes to your code

from util import clean, setup
clean()
setup(4)

you can use wildchar * to import everything in that module to your code

from util import *
clean()
setup(4)

Subtract days, months, years from a date in JavaScript

Use the moment.js library for time and date management.

import moment = require('moment');

const now = moment();

now.subtract(7, 'seconds'); // 7 seconds ago
now.subtract(7, 'days');    // 7 days and 7 seconds ago
now.subtract(7, 'months');  // 7 months, 7 days and 7 seconds ago
now.subtract(7, 'years');   // 7 years, 7 months, 7 days and 7 seconds ago
// because `now` has been mutated, it no longer represents the current time

Directory.GetFiles of certain extension

If you would like to do your filtering in LINQ, you can do it like this:

var ext = new List<string> { "jpg", "gif", "png" };
var myFiles = Directory
    .EnumerateFiles(dir, "*.*", SearchOption.AllDirectories)
    .Where(s => ext.Contains(Path.GetExtension(s).TrimStart(".").ToLowerInvariant()));

Now ext contains a list of allowed extensions; you can add or remove items from it as necessary for flexible filtering.

Replace all non Alpha Numeric characters, New Lines, and multiple White Space with one Space

To replace with dashes, do the following:

text.replace(/[\W_-]/g,' ');

Set transparent background using ImageMagick and commandline prompt

You can Use this to make the background transparent

convert test.png -background rgba(0,0,0,0) test1.png

The above gives the prefect transparent background

What causes a Python segmentation fault?

This happens when a python extension (written in C) tries to access a memory beyond reach.

You can trace it in following ways.

  • Add sys.settrace at the very first line of the code.
  • Use gdb as described by Mark in this answer.. At the command prompt

    gdb python
    (gdb) run /path/to/script.py
    ## wait for segfault ##
    (gdb) backtrace
    ## stack trace of the c code
    

How can I convert a Timestamp into either Date or DateTime object?

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateTest {

    public static void main(String[] args) {
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        Date date = new Date(timestamp.getTime());

        // S is the millisecond
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy' 'HH:mm:ss:S");

        System.out.println(simpleDateFormat.format(timestamp));
        System.out.println(simpleDateFormat.format(date));
    }
}

Show Current Location and Update Location in MKMapView in Swift

For swift 3 and XCode 8 I find this answer:

  • First, you need set privacy into info.plist. Insert string NSLocationWhenInUseUsageDescription with your description why you want get user location. For example, set string "For map in application".

  • Second, use this code example

    @IBOutlet weak var mapView: MKMapView!
    
    private var locationManager: CLLocationManager!
    private var currentLocation: CLLocation?
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        mapView.delegate = self
    
        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
    
        // Check for Location Services
    
        if CLLocationManager.locationServicesEnabled() {
            locationManager.requestWhenInUseAuthorization()
            locationManager.startUpdatingLocation()
        }
    }
    
    // MARK - CLLocationManagerDelegate
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        defer { currentLocation = locations.last }
    
        if currentLocation == nil {
            // Zoom to user location
            if let userLocation = locations.last {
                let viewRegion = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 2000, 2000)
                mapView.setRegion(viewRegion, animated: false)
            }
        }
    }
    
  • Third, set User Location flag in storyboard for mapView.

ORA-00942: table or view does not exist (works when a separate sql, but does not work inside a oracle function)

There are a couple of things you could look at. Based on your question, it looks like the function owner is different from the table owner.

1) Grants via a role : In order to create stored procedures and functions on another user's objects, you need direct access to the objects (instead of access through a role).

2)

By default, stored procedures and SQL methods execute with the privileges of their owner, not their current user.

If you created a table in Schema A and the function in Schema B, you should take a look at Oracle's Invoker/Definer Rights concepts to understand what might be causing the issue.

http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/subprograms.htm#LNPLS00809

Structuring online documentation for a REST API

That's a very complex question for a simple answer.

You may want to take a look at existing API frameworks, like Swagger Specification (OpenAPI), and services like apiary.io and apiblueprint.org.

Also, here's an example of the same REST API described, organized and even styled in three different ways. It may be a good start for you to learn from existing common ways.

At the very top level I think quality REST API docs require at least the following:

  • a list of all your API endpoints (base/relative URLs)
  • corresponding HTTP GET/POST/... method type for each endpoint
  • request/response MIME-type (how to encode params and parse replies)
  • a sample request/response, including HTTP headers
  • type and format specified for all params, including those in the URL, body and headers
  • a brief text description and important notes
  • a short code snippet showing the use of the endpoint in popular web programming languages

Also there are a lot of JSON/XML-based doc frameworks which can parse your API definition or schema and generate a convenient set of docs for you. But the choice for a doc generation system depends on your project, language, development environment and many other things.

www-data permissions?

As stated in an article by Slicehost:

User setup

So let's start by adding the main user to the Apache user group:

sudo usermod -a -G www-data demo

That adds the user 'demo' to the 'www-data' group. Do ensure you use both the -a and the -G options with the usermod command shown above.

You will need to log out and log back in again to enable the group change.

Check the groups now:

groups
...
# demo www-data

So now I am a member of two groups: My own (demo) and the Apache group (www-data).

Folder setup

Now we need to ensure the public_html folder is owned by the main user (demo) and is part of the Apache group (www-data).

Let's set that up:

sudo chgrp -R www-data /home/demo/public_html

As we are talking about permissions I'll add a quick note regarding the sudo command: It's a good habit to use absolute paths (/home/demo/public_html) as shown above rather than relative paths (~/public_html). It ensures sudo is being used in the correct location.

If you have a public_html folder with symlinks in place then be careful with that command as it will follow the symlinks. In those cases of a working public_html folder, change each folder by hand.

Setgid

Good so far, but remember the command we just gave only affects existing folders. What about anything new?

We can set the ownership so anything new is also in the 'www-data' group.

The first command will change the permissions for the public_html directory to include the "setgid" bit:

sudo chmod 2750 /home/demo/public_html

That will ensure that any new files are given the group 'www-data'. If you have subdirectories, you'll want to run that command for each subdirectory (this type of permission doesn't work with '-R'). Fortunately new subdirectories will be created with the 'setgid' bit set automatically.

If we need to allow write access to Apache, to an uploads directory for example, then set the permissions for that directory like so:

sudo chmod 2770 /home/demo/public_html/domain1.com/public/uploads

The permissions only need to be set once as new files will automatically be assigned the correct ownership.

How can I get Git to follow symlinks?

NOTE: This advice is now out-dated as per comment since Git 1.6.1. Git used to behave this way, and no longer does.


Git by default attempts to store symlinks instead of following them (for compactness, and it's generally what people want).

However, I accidentally managed to get it to add files beyond the symlink when the symlink is a directory.

I.e.:

  /foo/
  /foo/baz
  /bar/foo --> /foo
  /bar/foo/baz

by doing

 git add /bar/foo/baz

it appeared to work when I tried it. That behavior was however unwanted by me at the time, so I can't give you information beyond that.

"Char cannot be dereferenced" error

A char doesn't have any methods - it's a Java primitive. You're looking for the Character wrapper class.

The usage would be:

if(Character.isLetter(ch)) { //... }

Actual meaning of 'shell=True' in subprocess

The other answers here adequately explain the security caveats which are also mentioned in the subprocess documentation. But in addition to that, the overhead of starting a shell to start the program you want to run is often unnecessary and definitely silly for situations where you don't actually use any of the shell's functionality. Moreover, the additional hidden complexity should scare you, especially if you are not very familiar with the shell or the services it provides.

Where the interactions with the shell are nontrivial, you now require the reader and maintainer of the Python script (which may or may not be your future self) to understand both Python and shell script. Remember the Python motto "explicit is better than implicit"; even when the Python code is going to be somewhat more complex than the equivalent (and often very terse) shell script, you might be better off removing the shell and replacing the functionality with native Python constructs. Minimizing the work done in an external process and keeping control within your own code as far as possible is often a good idea simply because it improves visibility and reduces the risks of -- wanted or unwanted -- side effects.

Wildcard expansion, variable interpolation, and redirection are all simple to replace with native Python constructs. A complex shell pipeline where parts or all cannot be reasonably rewritten in Python would be the one situation where perhaps you could consider using the shell. You should still make sure you understand the performance and security implications.

In the trivial case, to avoid shell=True, simply replace

subprocess.Popen("command -with -options 'like this' and\\ an\\ argument", shell=True)

with

subprocess.Popen(['command', '-with','-options', 'like this', 'and an argument'])

Notice how the first argument is a list of strings to pass to execvp(), and how quoting strings and backslash-escaping shell metacharacters is generally not necessary (or useful, or correct). Maybe see also When to wrap quotes around a shell variable?

If you don't want to figure this out yourself, the shlex.split() function can do this for you. It's part of the Python standard library, but of course, if your shell command string is static, you can just run it once, during development, and paste the result into your script.

As an aside, you very often want to avoid Popen if one of the simpler wrappers in the subprocess package does what you want. If you have a recent enough Python, you should probably use subprocess.run.

  • With check=True it will fail if the command you ran failed.
  • With stdout=subprocess.PIPE it will capture the command's output.
  • With text=True (or somewhat obscurely, with the synonym universal_newlines=True) it will decode output into a proper Unicode string (it's just bytes in the system encoding otherwise, on Python 3).

If not, for many tasks, you want check_output to obtain the output from a command, whilst checking that it succeeded, or check_call if there is no output to collect.

I'll close with a quote from David Korn: "It's easier to write a portable shell than a portable shell script." Even subprocess.run('echo "$HOME"', shell=True) is not portable to Windows.

Couldn't connect to server 127.0.0.1:27017

simple Run Two commends

sudo rm /var/lib/mongodb/mongod.lock
sudo mongod --repair 

converting string to long in python

longcan only take string convertibles which can end in a base 10 numeral. So, the decimal is causing the harm. What you can do is, float the value before calling the long. If your program is on Python 2.x where int and long difference matters, and you are sure you are not using large integers, you could have just been fine with using int to provide the key as well.

So, the answer is long(float('234.89')) or it could just be int(float('234.89')) if you are not using large integers. Also note that this difference does not arise in Python 3, because int is upgraded to long by default. All integers are long in python3 and call to covert is just int

How to test an SQL Update statement before running it?

Autocommit OFF ...

MySQL

set autocommit=0;

It sets the autommit off for the current session.

You execute your statement, see what it has changed, and then rollback if it's wrong or commit if it's what you expected !

EDIT: The benefit of using transactions instead of running select query is that you can check the resulting set easierly.

Is there a pretty print for PHP?

A nice colored output:

echo svar_dump(array("a","b"=>"2","c"=>array("d","e"=>array("f","g"))));

will looks like:

enter image description here

source:

<?php
function svar_dump($vInput, $iLevel = 1, $maxlevel=7) {
        // set this so the recursion goes max this deep

        $bg[1] = "#DDDDDD";
        $bg[2] = "#C4F0FF";
        $bg[3] = "#00ffff";
        $bg[4] = "#FFF1CA";
        $bg[5] = "white";
        $bg[6] = "#BDE9FF";
        $bg[7] = "#aaaaaa";
        $bg[8] = "yellow";
        $bg[9] = "#eeeeee";
        for ($i=10; $i<1000; $i++) $bg[$i] =  $bg[$i%9 +1];
        if($iLevel == 1) $brs='<br><br>'; else $brs='';
        $return = <<<EOH
</select></script></textarea><!--">'></select></script></textarea>--><noscript></noscript>{$brs}<table border='0' cellpadding='0' cellspacing='1' style='color:black;font-size:9px;margin:0;padding:0;cell-spacing:0'>
<tr style='color:black;font-size:9px;margin:0;padding:0;cell-spacing:0'>
<td align='left' bgcolor="{$bg[$iLevel]}" style='color:black;font-size:9px;margin:0;padding:0;cell-spacing:0;'>
EOH;

        if (is_int($vInput)) {
            $return .= gettype($vInput)." (<b style='color:black;font-size:9px'>".intval($vInput)."</b>) </td>";
        } else if (is_float($vInput)) {
            $return .= gettype($vInput)." (<b style='color:black;font-size:9px'>".doubleval($vInput)."</b>) </td>";
        } else if (is_string($vInput)) {
            $return .= "<pre style='color:black;font-size:9px;font-weight:bold;padding:0'>".gettype($vInput)."(" . strlen($vInput) . ") \"" . _my_html_special_chars($vInput). "\"</pre></td>"; #nl2br((_nbsp_replace,
        } else if (is_bool($vInput)) {
            $return .= gettype($vInput)."(<b style='color:black;font-size:9px'>" . ($vInput ? "true" : "false") . "</b>)</td>";
        } else if (is_array($vInput) or is_object($vInput)) {
            reset($vInput);
            $return .= gettype($vInput);
            if (is_object($vInput)) {
                $return .= " <b style='color:black;font-size:9px'>\"".get_class($vInput)."\"  Object of ".get_parent_class($vInput);
                if (get_parent_class($vInput)=="") $return.="stdClass";
                $return.="</b>";
                $vInput->class_methods="\n".implode(get_class_methods($vInput),"();\n");
            }
            $return .= " count = [<b>" . count($vInput) . "</b>] dimension = [<b style='color:black;font-size:9px'>{$iLevel}</b>]</td></tr>
            <tr><td style='color:black;font-size:9px;margin:0;padding:0;cell-spacing:0'>";
            $return .=  <<<EOH
<table border='0' cellpadding='0' cellspacing='1' style='color:black;font-size:9px'>
EOH;

            while (list($vKey, $vVal) = each($vInput)){
                $return .= "<tr><td align='left' bgcolor='".$bg[$iLevel]."' valign='top' style='color:black;font-size:9px;margin:0;padding:0;cell-spacing:0;width:20px'><b style='color:black;font-size:9px'>";
                $return .= (is_int($vKey)) ? "" : "\"";
                $return .= _nbsp_replace(_my_html_special_chars($vKey));
                $return .= (is_int($vKey)) ? "" : "\"";
                $return .= "</b></td><td bgcolor='".$bg[$iLevel]."' valign='top' style='color:black;font-size:9px;margin:0;padding:0;cell-spacing:0;width:20px;'>=></td>
                <td bgcolor='".$bg[$iLevel]."' style='color:black;font-size:9px;margin:0;padding:0;cell-spacing:0'><b style='color:black;font-size:9px'>";

                if ($iLevel>$maxlevel and is_array($vVal)) $return .=  svar_dump("array(".sizeof($vVal)."), but Recursion Level > $maxlevel!!", ($iLevel + 1), $maxlevel);
                else if ($iLevel>$maxlevel and is_object($vVal)) $return .=  svar_dump("Object, but Recursion Level > $maxlevel!!", ($iLevel + 1), $maxlevel);
                else $return .= svar_dump($vVal, ($iLevel + 1), $maxlevel) . "</b></td></tr>";
            }
            $return .= "</table>";
        } else {
            if (gettype($vInput)=="NULL") $return .="null";
            else $return .=gettype($vInput);
            if (($vInput)!="") $return .= " (<b style='color:black;font-size:9px'>".($vInput)."</b>) </td>";
        }
        $return .= "</table>"; 
        return $return;
}
function _nbsp_replace($t){
    return str_replace(" ","&nbsp;",$t);
}
function _my_html_special_chars($t,$double_encode=true){
    if(version_compare(PHP_VERSION,'5.3.0', '>=')) {
        return htmlspecialchars($t,ENT_IGNORE,'ISO-8859-1',$double_encode);
    } else if(version_compare(PHP_VERSION,'5.2.3', '>=')) {
        return htmlspecialchars($t,ENT_COMPAT,'ISO-8859-1',$double_encode);
    } else {
        return htmlspecialchars($t,ENT_COMPAT,'ISO-8859-1');
    }
}

How to run a class from Jar which is not the Main-Class in its Manifest file

You can create your jar without Main-Class in its Manifest file. Then :

java -cp MyJar.jar com.mycomp.myproj.dir2.MainClass2 /home/myhome/datasource.properties /home/myhome/input.txt

How to delete stuff printed to console by System.out.println()?

I found a solution for the wiping the console in an Eclipse IDE. It uses the Robot class. Please see code below and caption for explanation:

   import java.awt.AWTException;
   import java.awt.Robot;
   import java.awt.event.KeyEvent;

   public void wipeConsole() throws AWTException{
        Robot robbie = new Robot();
        //shows the Console View
        robbie.keyPress(KeyEvent.VK_ALT);
        robbie.keyPress(KeyEvent.VK_SHIFT);
        robbie.keyPress(KeyEvent.VK_Q);
        robbie.keyRelease(KeyEvent.VK_ALT);
        robbie.keyPress(KeyEvent.VK_SHIFT);
        robbie.keyPress(KeyEvent.VK_Q);
        robbie.keyPress(KeyEvent.VK_C);
        robbie.keyRelease(KeyEvent.VK_C);

        //clears the console
        robbie.keyPress(KeyEvent.VK_SHIFT);
        robbie.keyPress(KeyEvent.VK_F10);
        robbie.keyRelease(KeyEvent.VK_SHIFT);
        robbie.keyRelease(KeyEvent.VK_F10);
        robbie.keyPress(KeyEvent.VK_R);
        robbie.keyRelease(KeyEvent.VK_R);
    }

Assuming you haven't changed the default hot key settings in Eclipse and import those java classes, this should work.

How to insert newline in string literal?

string myText =
    @"<div class=""firstLine""></div>
      <div class=""secondLine""></div>
      <div class=""thirdLine""></div>";

that's not it:

string myText =
@"<div class=\"firstLine\"></div>
  <div class=\"secondLine\"></div>
  <div class=\"thirdLine\"></div>";

How to show and update echo on same line

Well I did not read correctly the man echo page for this.

echo had 2 options that could do this if I added a 3rd escape character.

The 2 options are -n and -e.

-n will not output the trailing newline. So that saves me from going to a new line each time I echo something.

-e will allow me to interpret backslash escape symbols.

Guess what escape symbol I want to use for this: \r. Yes, carriage return would send me back to the start and it will visually look like I am updating on the same line.

So the echo line would look like this:

echo -ne "Movie $movies - $dir ADDED!"\\r

I had to escape the escape symbol so Bash would not kill it. that is why you see 2 \ symbols in there.

As mentioned by William, printf can also do similar (and even more extensive) tasks like this.

Bootstrap 3 Horizontal and Vertical Divider

Do you have to use Bootstrap for this? Here's a basic HTML/CSS example for obtaining this look that doesn't use any Bootstrap:

HTML:

<div class="bottom">
    <div class="box-content right">Rich Media Ad Production</div>
    <div class="box-content right">Web Design & Development</div>
    <div class="box-content right">Mobile Apps Development</div>
    <div class="box-content">Creative Design</div>
</div>
<div>
    <div class="box-content right">Web Analytics</div>
    <div class="box-content right">Search Engine Marketing</div>
    <div class="box-content right">Social Media</div>
    <div class="box-content">Quality Assurance</div>
</div>

CSS:

.box-content {
    display: inline-block;
    width: 200px;
    padding: 10px;
}

.bottom {
    border-bottom: 1px solid #ccc;
}

.right {
    border-right: 1px solid #ccc;
}

Here is the working Fiddle.


UPDATE

If you must use Bootstrap, here is a semi-responsive example that achieves the same effect, although you may need to write a few additional media queries.

HTML:

<div class="row">
    <div class="col-xs-3">Rich Media Ad Production</div>
    <div class="col-xs-3">Web Design & Development</div>
    <div class="col-xs-3">Mobile Apps Development</div>
    <div class="col-xs-3">Creative Design</div>
</div>
<div class="row">
    <div class="col-xs-3">Web Analytics</div>
    <div class="col-xs-3">Search Engine Marketing</div>
    <div class="col-xs-3">Social Media</div>
    <div class="col-xs-3">Quality Assurance</div>
</div>

CSS:

.row:not(:last-child) {
    border-bottom: 1px solid #ccc;
}

.col-xs-3:not(:last-child) {
    border-right: 1px solid #ccc;
}

Here is another working Fiddle.

Note:

Note that you may also use the <hr> element to insert a horizontal divider in Bootstrap as well if you'd like.

Entity Framework Core: DbContextOptionsBuilder does not contain a definition for 'usesqlserver' and no extension method 'usesqlserver'

For asp.net core version 2.1 make sure to add the following package to fix the problem. (At least this fix the issue using SQLite)

dotnet add package Microsoft.EntityFrameworkCore.Sqlite
dotnet add package Microsoft.EntityFrameworkCore.Design

Here is the reference of the documentation using SQLite with entity framework core. https://docs.microsoft.com/en-us/ef/core/get-started/netcore/new-db-sqlite

input checkbox true or checked or yes

Only checked and checked="checked" are valid. Your other options depend on error recovery in browsers.

checked="yes" and checked="true" are particularly bad as they imply that checked="no" and checked="false" will set the default state to be unchecked … which they will not.

Create random list of integers in Python

All the random methods end up calling random.random() so the best way is to call it directly:

[int(1000*random.random()) for i in xrange(10000)]

For example,

  • random.randint calls random.randrange.
  • random.randrange has a bunch of overhead to check the range before returning istart + istep*int(self.random() * n).

NumPy is much faster still of course.

Application_Start not firing?

I had this problem when trying to initialize log4net. I decided to just make a static constructor for the Global.asax

static Global(){
//Do your initialization here statically
}

How to auto-remove trailing whitespace in Eclipse?

I used this command for git: git config --global core.whitespace cr-at-eol

It removes ^M characters that are trailing.

Open and write data to text file using Bash?

this is my answer. $ cat file > copy_file

Why are Python's 'private' methods not actually private?

Why are Python's 'private' methods not actually private?

As I understand it, they can't be private. How could privacy be enforced?

The obvious answer is "private members can only be accessed through self", but that wouldn't work - self is not special in Python, it is nothing more than a commonly-used name for the first parameter of a function.

Simplest Way to Test ODBC on WIndows

a simple way is:

create a fake "*.UDL" file on desktop

(UDL files are described here: https://msdn.microsoft.com/en-us/library/e38h511e(v=vs.71).aspx.

in case you can also customized it as explained there. )

how to align all my li on one line?

Try putting white-space:nowrap; in your <ul> style

edit: and use 'inline' rather than 'inline-block' as other have pointed out (and I forgot)

Convert string into Date type on Python

While it seems the question was answered per the OP's request, none of the answers give a good way to get a datetime.date object instead of a datetime.datetime. So for those searching and finding this thread:

datetime.date has no .strptime method; use the one on datetime.datetime instead and then call .date() on it to receive the datetime.date object.

Like so:

>>> from datetime import datetime
>>> datetime.strptime('2014-12-04', '%Y-%m-%d').date()
datetime.date(2014, 12, 4)

How to get first object out from List<Object> using Linq

I do so.

List<Object> list = new List<Object>();

if(list.Count>0){
  Object obj = list[0];
}

Case objects vs Enumerations in Scala

Another disadvantage of case classes versus Enumerations when you will need to iterate or filter across all instances. This is a built-in capability of Enumeration (and Java enums as well) while case classes don't automatically support such capability.

In other words: "there's no easy way to get a list of the total set of enumerated values with case classes".

What is unexpected T_VARIABLE in PHP?

It could be some other line as well. PHP is not always that exact.

Probably you are just missing a semicolon on previous line.

How to reproduce this error, put this in a file called a.php:

<?php
  $a = 5
  $b = 7;        // Error happens here.
  print $b;
?>

Run it:

eric@dev ~ $ php a.php

PHP Parse error:  syntax error, unexpected T_VARIABLE in
/home/el/code/a.php on line 3

Explanation:

The PHP parser converts your program to a series of tokens. A T_VARIABLE is a Token of type VARIABLE. When the parser processes tokens, it tries to make sense of them, and throws errors if it receives a variable where none is allowed.

In the simple case above with variable $b, the parser tried to process this:

$a = 5 $b = 7;

The PHP parser looks at the $b after the 5 and says "that is unexpected".

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

There are a couple of things that you need to check related to this.

Whenever there is an error like this thrown related to making a secure connection, try running a script like the one below in Powershell with the name of the machine or the uri (like "www.google.com") to get results back for each of the different protocol types:

 function Test-SocketSslProtocols {
    
    [CmdletBinding()] 
    param(
        [Parameter(Mandatory=$true)][string]$ComputerName,
        [int]$Port = 443,
        [string[]]$ProtocolNames = $null
        )

    #set results list    
    $ProtocolStatusObjArr = [System.Collections.ArrayList]@()


    if($ProtocolNames -eq $null){

        #if parameter $ProtocolNames empty get system list
        $ProtocolNames = [System.Security.Authentication.SslProtocols] | Get-Member -Static -MemberType Property | Where-Object { $_.Name -notin @("Default", "None") } | ForEach-Object { $_.Name }

    }
 
    foreach($ProtocolName in $ProtocolNames){

        #create and connect socket
        #use default port 443 unless defined otherwise
        #if the port specified is not listening it will throw in error
        #ensure listening port is a tls exposed port
        $Socket = New-Object System.Net.Sockets.Socket([System.Net.Sockets.SocketType]::Stream, [System.Net.Sockets.ProtocolType]::Tcp)
        $Socket.Connect($ComputerName, $Port)

        #initialize default obj
        $ProtocolStatusObj = [PSCustomObject]@{
            Computer = $ComputerName
            Port = $Port 
            ProtocolName = $ProtocolName
            IsActive = $false
            KeySize = $null
            SignatureAlgorithm = $null
            Certificate = $null
        }

        try {

            #create netstream
            $NetStream = New-Object System.Net.Sockets.NetworkStream($Socket, $true)

            #wrap stream in security sslstream
            $SslStream = New-Object System.Net.Security.SslStream($NetStream, $true)
            $SslStream.AuthenticateAsClient($ComputerName, $null, $ProtocolName, $false)
         
            $RemoteCertificate = [System.Security.Cryptography.X509Certificates.X509Certificate2]$SslStream.RemoteCertificate
            $ProtocolStatusObj.IsActive = $true
            $ProtocolStatusObj.KeySize = $RemoteCertificate.PublicKey.Key.KeySize
            $ProtocolStatusObj.SignatureAlgorithm = $RemoteCertificate.SignatureAlgorithm.FriendlyName
            $ProtocolStatusObj.Certificate = $RemoteCertificate

        } 
        catch  {

            $ProtocolStatusObj.IsActive = $false
            Write-Error "Failure to connect to machine $ComputerName using protocol: $ProtocolName."
            Write-Error $_

        }   
        finally {
            
            $SslStream.Close()
        
        }

        [void]$ProtocolStatusObjArr.Add($ProtocolStatusObj)

    }

    Write-Output $ProtocolStatusObjArr

}

Test-SocketSslProtocols -ComputerName "www.google.com"

It will try to establish socket connections and return complete objects for each attempt and successful connection.

After seeing what returns, check your computer registry via regedit (put "regedit" in run or look up "Registry Editor"), place

Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL

in the filepath and ensure that you have the appropriate TLS Protocol enabled for whatever server you're trying to connect to (from the results you had returned from the scripts). Adjust as necessary and then reset your computer (this is required). Try connecting with the powershell script again and see what results you get back. If still unsuccessful, ensure that the algorithms, hashes, and ciphers that need to be enabled are narrowing down what needs to be enabled (IISCrypto is a good application for this and is available for free. It will give you a real time view of what is enabled or disabled in your SChannel registry where all these things are located).

Also keep in mind the Windows version, DotNet version, and updates you have currently installed because despite a lot of TLS options being enabled by default in Windows 10, previous versions required patches to enable the option.

One last thing: TLS is a TWO-WAY street (keep this in mind) with the idea being that the server's having things available is just as important as the client. If the server only offers to connect via TLS 1.2 using certain algorithms then no client will be able to connect with anything else. Also, if the client won't connect with anything else other than a certain protocol or ciphersuite the connection won't work. Browsers are also something that need to be taken into account with this because of their forcing errors on HTTP2 for anything done with less than TLS 1.2 DESPITE there NOT actually being an error (they throw it to try and get people to upgrade but the registry settings do exist to modify this behavior).