Programs & Examples On #Cellrenderer

Change the background color of a row in a JTable

Resumee of Richard Fearn's answer , to make each second line gray:

jTable.setDefaultRenderer(Object.class, new DefaultTableCellRenderer()
{
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
    {
        final Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        c.setBackground(row % 2 == 0 ? Color.LIGHT_GRAY : Color.WHITE);
        return c;
    }
});

Horizontal ListView in Android?

I've done a lot of searching for a solution to this problem. The short answer is, there is no good solution, without overriding private methods and that sort of thing. The best thing I found was to implement it myself from scratch by extending AdapterView. It's pretty miserable. See my SO question about horizontal ListViews.

LaTex left arrow over letter in math mode

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

\overleftarrow{blahblahblah}

LaTeX output

Failed to resolve: com.android.support:appcompat-v7:28.0

Ensure that your buildToolsVersion version tallies with your app compact version.

In order to find both installed compileSdkVersion and buildToolsVersion go to Tools > SDK Manager. This will pull up a window that will allow you to manage your compileSdkVersion and your buildToolsVersion.

To see the exact version breakdowns ensure you have the Show Package Details checkbox checked.

android {
    compileSdkVersion 28
    buildToolsVersion "28.0.3" (HERE)
    defaultConfig {
        applicationId "com.example.truecitizenquiz"
        minSdkVersion 14
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0' (HERE)
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

How to send an object from one Android Activity to another using Intents?

By far the easiest way IMHO to parcel objects. You just add an annotation tag above the object you wish to make parcelable.

An example from the library is below https://github.com/johncarl81/parceler

@Parcel
public class Example {
    String name;
    int age;

    public Example(){ /*Required empty bean constructor*/ }

    public Example(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public String getName() { return name; }

    public int getAge() { return age; }
}

Writing a Python list of lists to a csv file

How about dumping the list of list into pickle and restoring it with pickle module? It's quite convenient.

>>> import pickle
>>> 
>>> mylist = [1, 'foo', 'bar', {1, 2, 3}, [ [1,4,2,6], [3,6,0,10]]]
>>> with open('mylist', 'wb') as f:
...     pickle.dump(mylist, f) 


>>> with open('mylist', 'rb') as f:
...      mylist = pickle.load(f)
>>> mylist
[1, 'foo', 'bar', {1, 2, 3}, [[1, 4, 2, 6], [3, 6, 0, 10]]]
>>> 

dropzone.js - how to do something after ALL files are uploaded

I up-voted you as your method is simple. I did make only a couple of slight amends as sometimes the event fires even though there are no bytes to send - On my machine it did it when I clicked the remove button on a file.

myDropzone.on("totaluploadprogress", function(totalPercentage, totalBytesToBeSent, totalBytesSent ){
            if(totalPercentage >= 100 && totalBytesSent) {
                // All done! Call func here
            }
        });

How to get all the AD groups for a particular user?

The following example is from the Code Project article, (Almost) Everything In Active Directory via C#:

// userDn is a Distinguished Name such as:
// "LDAP://CN=Joe Smith,OU=Sales,OU=domain,OU=com"
public ArrayList Groups(string userDn, bool recursive)
{
    ArrayList groupMemberships = new ArrayList();
    return AttributeValuesMultiString("memberOf", userDn,
        groupMemberships, recursive);
}

public ArrayList AttributeValuesMultiString(string attributeName,
     string objectDn, ArrayList valuesCollection, bool recursive)
{
    DirectoryEntry ent = new DirectoryEntry(objectDn);
    PropertyValueCollection ValueCollection = ent.Properties[attributeName];
    IEnumerator en = ValueCollection.GetEnumerator();

    while (en.MoveNext())
    {
        if (en.Current != null)
        {
            if (!valuesCollection.Contains(en.Current.ToString()))
            {
                valuesCollection.Add(en.Current.ToString());
                if (recursive)
                {
                    AttributeValuesMultiString(attributeName, "LDAP://" +
                    en.Current.ToString(), valuesCollection, true);
                }
            }
        }
    }
    ent.Close();
    ent.Dispose();
    return valuesCollection;
}

Just call the Groups method with the Distinguished Name for the user, and pass in the bool flag to indicate if you want to include nested / child groups memberships in your resulting ArrayList:

ArrayList groups = Groups("LDAP://CN=Joe Smith,OU=Sales,OU=domain,OU=com", true);
foreach (string groupName in groups)
{
    Console.WriteLine(groupName);
}

If you need to do any serious level of Active Directory programming in .NET I highly recommend bookmarking & reviewing the Code Project article I mentioned above.

Install php-zip on php 5.6 on Ubuntu

Try either

  • sudo apt-get install php-zip or
  • sudo apt-get install php5.6-zip

Then, you might have to restart your web server.

  • sudo service apache2 restart or
  • sudo service nginx restart

If you are installing on centos or fedora OS then use yum in place of apt-get. example:-

sudo yum install php-zip or sudo yum install php5.6-zip and sudo service httpd restart

How to read file from res/raw by name

Here are two approaches you can read raw resources using Kotlin.

You can get it by getting the resource id. Or, you can use string identifier in which you can programmatically change the filename with incrementation.

Cheers mate

// R.raw.data_post

this.context.resources.openRawResource(R.raw.data_post)
this.context.resources.getIdentifier("data_post", "raw", this.context.packageName)

Is there a no-duplicate List implementation out there?

You should seriously consider dhiller's answer:

  1. Instead of worrying about adding your objects to a duplicate-less List, add them to a Set (any implementation), which will by nature filter out the duplicates.
  2. When you need to call the method that requires a List, wrap it in a new ArrayList(set) (or a new LinkedList(set), whatever).

I think that the solution you posted with the NoDuplicatesList has some issues, mostly with the contains() method, plus your class does not handle checking for duplicates in the Collection passed to your addAll() method.

How to downgrade or install an older version of Cocoapods

PROMPT> gem uninstall cocoapods

Select gem to uninstall:
 1. cocoapods-0.32.1
 2. cocoapods-0.33.1
 3. cocoapods-0.36.0.beta.2
 4. cocoapods-0.38.2
 5. cocoapods-0.39.0
 6. cocoapods-1.0.0
 7. All versions
> 6
Successfully uninstalled cocoapods-1.0.0
PROMPT> gem install cocoapods -v 0.39.0
Successfully installed cocoapods-0.39.0
Parsing documentation for cocoapods-0.39.0
Done installing documentation for cocoapods after 1 seconds
1 gem installed
PROMPT> pod --version
0.39.0
PROMPT>

How to query all the GraphQL type fields without writing a long query?

I faced this same issue when I needed to load location data that I had serialized into the database from the google places API. Generally I would want the whole thing so it works with maps but I didn't want to have to specify all of the fields every time.

I was working in Ruby so I can't give you the PHP implementation but the principle should be the same.

I defined a custom scalar type called JSON which just returns a literal JSON object.

The ruby implementation was like so (using graphql-ruby)

module Graph
  module Types
    JsonType = GraphQL::ScalarType.define do
      name "JSON"
      coerce_input -> (x) { x }
      coerce_result -> (x) { x }
    end
  end
end

Then I used it for our objects like so

field :location, Types::JsonType

I would use this very sparingly though, using it only where you know you always need the whole JSON object (as I did in my case). Otherwise it is defeating the object of GraphQL more generally speaking.

How to search a string in multiple files and return the names of files in Powershell?

This should give the location of the files that contain your pattern:

Get-ChildItem -Recurse | Select-String "dummy" -List | Select Path

How can I use grep to find a word inside a folder?

Another option that I like to use:

find folder_name -type f -exec grep your_text  {} \;

-type f returns you only files and not folders

-exec and {} runs the grep on the files that were found in the search (the exact syntax is "-exec command {}").

Java switch statement: Constant expression required, but it IS constant

Below code is self-explanatory, We can use an enum with a switch case:

/**
 *
 */
enum ClassNames {
    STRING(String.class, String.class.getSimpleName()),
    BOOLEAN(Boolean.class, Boolean.class.getSimpleName()),
    INTEGER(Integer.class, Integer.class.getSimpleName()),
    LONG(Long.class, Long.class.getSimpleName());
    private Class typeName;
    private String simpleName;
    ClassNames(Class typeName, String simpleName){
        this.typeName = typeName;
        this.simpleName = simpleName;
    }
}

Based on the class values from the enum can be mapped:

 switch (ClassNames.valueOf(clazz.getSimpleName())) {
        case STRING:
            String castValue = (String) keyValue;
            break;
        case BOOLEAN:
            break;
        case Integer:
            break;
        case LONG:
            break;
        default:
            isValid = false;

    }

Hope it helps :)

How do I change select2 box height

Quick and easy, add this to your page:

<style>
    .select2-results {
        max-height: 500px;
    }
</style>

.htaccess - how to force "www." in a generic way?

This won't work with subdomains.

domain.com correctly gets redirected to www.domain.com

but

images.domain.com gets redirected to www.images.domain.com

Instead of checking if the subdomain is "not www", check if there are two dots:

RewriteCond %{HTTP_HOST} ^(.*)$ [NC]
RewriteCond %{HTTP_HOST} !^(.*)\.(.*)\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ HTTP%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

How to make the corners of a button round?

You can also use the card layout like below

  <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="60dp"
        app:cardCornerRadius="30dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"

            >

            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center"
                android:text="Template"

                />

        </LinearLayout>

    </androidx.cardview.widget.CardView>

IF EXISTS in T-SQL

There's no need for "else" in this case:

IF EXISTS(SELECT *  FROM  table1  WHERE Name='John' ) return 1
return 0

Call An Asynchronous Javascript Function Synchronously

Take a look at JQuery Promises:

http://api.jquery.com/promise/

http://api.jquery.com/jQuery.when/

http://api.jquery.com/deferred.promise/

Refactor the code:


    var dfd = new jQuery.Deferred();


    function callBack(data) {
       dfd.notify(data);
    }

    // do the async call.
    myAsynchronousCall(param1, callBack);

    function doSomething(data) {
     // do stuff with data...
    }

    $.when(dfd).then(doSomething);


jQuery calculate sum of values in all text fields

A tad more generic copy/paste function for your project.

sumjq = function(selector) {
    var sum = 0;
    $(selector).each(function() {
        sum += Number($(this).text());
    });
    return sum;
}

console.log(sumjq('.price'));

Android + Pair devices via bluetooth programmatically

if you have the BluetoothDevice object you can create bond(pair) from api 19 onwards with bluetoothDevice.createBond() method.

Edit

for callback, if the request was accepted or denied you will have to create a BroadcastReceiver with BluetoothDevice.ACTION_BOND_STATE_CHANGED action

How to Increase Import Size Limit in phpMyAdmin

You can increase the limit from php.ini file. If you are using windows, you will the get php.ini file from C:\xampp\php directory.

Now changes the following lines & set your limit

post_max_size = 128M
upload_max_filesize = 128M 
max_execution_time = 2000
max_input_time = 3000
memory_limit = 256M

Extend contigency table with proportions (percentages)

Here's a tidyverse version:

library(tidyverse)
data(diamonds)

(as.data.frame(table(diamonds$cut)) %>% rename(Count=1,Freq=2) %>% mutate(Perc=100*Freq/sum(Freq)))

Or if you want a handy function:

getPercentages <- function(df, colName) {
  df.cnt <- df %>% select({{colName}}) %>% 
    table() %>%
    as.data.frame() %>% 
    rename({{colName}} :=1, Freq=2) %>% 
    mutate(Perc=100*Freq/sum(Freq))
}

Now you can do:

diamonds %>% getPercentages(cut)

or this:

df=diamonds %>% group_by(cut) %>% group_modify(~.x %>% getPercentages(clarity))
ggplot(df,aes(x=clarity,y=Perc))+geom_col()+facet_wrap(~cut)

running multiple bash commands with subprocess

If you're only running the commands in one shot then you can just use subprocess.check_output convenience function:

def subprocess_cmd(command):
    output = subprocess.check_output(command, shell=True)
    print output

Convert string to buffer Node

You can use Buffer.from() to convert a string to buffer. More information on this can be found here

var buf = Buffer.from('some string', 'encoding');

for example

var buf = Buffer.from(bStr, 'utf-8');

SQL Server Pivot Table with multiple column aggregates

I used your own pivot as a nested query and came to this result:

SELECT
  [sub].[chardate],
  SUM(ISNULL([Australia], 0)) AS [Transactions Australia],
  SUM(CASE WHEN [Australia] IS NOT NULL THEN [TotalAmount] ELSE 0 END) AS [Amount Australia],
  SUM(ISNULL([Austria], 0)) AS [Transactions Austria],
  SUM(CASE WHEN [Austria] IS NOT NULL THEN [TotalAmount] ELSE 0 END) AS [Amount Austria]
FROM
(
  select * 
  from  mytransactions
  pivot (sum (totalcount) for country in ([Australia], [Austria])) as pvt
) AS [sub]
GROUP BY
  [sub].[chardate],
  [sub].[numericmonth]
ORDER BY 
  [sub].[numericmonth] ASC

Here is the Fiddle.

Import Certificate to Trusted Root but not to Personal [Command Line]

If there are multiple certificates in a pfx file (key + corresponding certificate and a CA certificate) then this command worked well for me:

certutil -importpfx c:\somepfx.pfx this works but still a password is needed to be typed in manually for private key. Including -p and "password" cause error too many arguments for certutil on XP

How to generate random number in Bash?

There is $RANDOM. I don't know exactly how it works. But it works. For testing, you can do :

echo $RANDOM

Server.MapPath - Physical path given, virtual path expected

if you already know your folder is: E:\ftproot\sales then you do not need to use Server.MapPath, this last one is needed if you only have a relative virtual path like ~/folder/folder1 and you want to know the real path in the disk...

JSON character encoding

If you're using StringEntity try this, using your choice of character encoding. It handles foreign characters as well.

How to append one DataTable to another DataTable

The datatype in the same columns name must be equals.

dataTable1.Merge(dataTable2);

After that the result is:

dataTable1 = dataTable1 + dataTable2

Status bar and navigation bar appear over my view's bounds in iOS 7

If you want the view to have the translucent nav bar (which is kind of nice) you have to setup a contentInset or similar.

Here is how I do it:

// Check if we are running on ios7
if([[[[UIDevice currentDevice] systemVersion] componentsSeparatedByString:@"."][0] intValue] >= 7) {
      CGRect statusBarViewRect = [[UIApplication sharedApplication] statusBarFrame];
      float heightPadding = statusBarViewRect.size.height+self.navigationController.navigationBar.frame.size.height;

      myContentView.contentInset = UIEdgeInsetsMake(heightPadding, 0.0, 0.0, 0.0);
}

Create folder with batch but only if it doesn't already exist

You just use this: if not exist "C:\VTS\" mkdir C:\VTS it wll create a directory only if the folder does not exist.

Note that this existence test will return true only if VTS exists and is a directory. If it is not there, or is there as a file, the mkdir command will run, and should cause an error. You might want to check for whether VTS exists as a file as well.

Spring AMQP + RabbitMQ 3.3.5 ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN

I made exactly what @grepit made.

But I had to made some changes in my Java code:

In Producer and Receiver project I altered:

ConnectionFactory factory = new ConnectionFactory();
factory.setHost("your-host-ip");
factory.setUsername("username-you-created");
factory.setPassword("username-password");

        

Doing that, you are connecting an specific host as the user you have created. It works for me!

Same Navigation Drawer in different Activities

With @Kevin van Mierlo 's answer, you are also capable of implementing several drawers. For instance, the default menu located on the left side (start), and a further optional menu, located on the right side, which is only shown when determinate fragments are loaded.

I've been able to do that.

How to unpack an .asar file?

https://www.electronjs.org/apps/asarui

UI for Asar, Extract All, or drag extract file/directory

URLEncoder not able to translate space character

This class perform application/x-www-form-urlencoded-type encoding rather than percent encoding, therefore replacing with + is a correct behaviour.

From javadoc:

When encoding a String, the following rules apply:

  • The alphanumeric characters "a" through "z", "A" through "Z" and "0" through "9" remain the same.
  • The special characters ".", "-", "*", and "_" remain the same.
  • The space character " " is converted into a plus sign "+".
  • All other characters are unsafe and are first converted into one or more bytes using some encoding scheme. Then each byte is represented by the 3-character string "%xy", where xy is the two-digit hexadecimal representation of the byte. The recommended encoding scheme to use is UTF-8. However, for compatibility reasons, if an encoding is not specified, then the default encoding of the platform is used.

String replacement in batch file

I was able to use Joey's Answer to create a function:

Use it as:

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION

SET "MYTEXT=jump over the chair"
echo !MYTEXT!
call:ReplaceText "!MYTEXT!" chair table RESULT
echo !RESULT!

GOTO:EOF

And these Functions to the bottom of your Batch File.

:FUNCTIONS
@REM FUNCTIONS AREA
GOTO:EOF
EXIT /B

:ReplaceText
::Replace Text In String
::USE:
:: CALL:ReplaceText "!OrginalText!" OldWordToReplace NewWordToUse  Result
::Example
::SET "MYTEXT=jump over the chair"
::  echo !MYTEXT!
::  call:ReplaceText "!MYTEXT!" chair table RESULT
::  echo !RESULT!
::
:: Remember to use the "! on the input text, but NOT on the Output text.
:: The Following is Wrong: "!MYTEXT!" !chair! !table! !RESULT!
:: ^^Because it has a ! around the chair table and RESULT
:: Remember to add quotes "" around the MYTEXT Variable when calling.
:: If you don't add quotes, it won't treat it as a single string
::
set "OrginalText=%~1"
set "OldWord=%~2"
set "NewWord=%~3"
call set OrginalText=%%OrginalText:!OldWord!=!NewWord!%%
SET %4=!OrginalText!
GOTO:EOF

And remember you MUST add "SETLOCAL ENABLEDELAYEDEXPANSION" to the top of your batch file or else none of this will work properly.

SETLOCAL ENABLEDELAYEDEXPANSION
@REM # Remember to add this to the top of your batch file.

How can I limit possible inputs in a HTML5 "number" element?

Lets say you wanted the maximum allowed value to be 1000 - either typed or with the spinner.

You restrict the spinner values using: type="number" min="0" max="1000"

and restrict what is typed by the keyboard with javascript: onkeyup="if(parseInt(this.value)>1000){ this.value =1000; return false; }"

<input type="number" min="0" max="1000" onkeyup="if(parseInt(this.value)>1000){ this.value =1000; return false; }">

How can I render Partial views in asp.net mvc 3?

Create your partial view something like:

@model YourModelType
<div>
  <!-- HTML to render your object -->
</div>

Then in your view use:

@Html.Partial("YourPartialViewName", Model)

If you do not want a strongly typed partial view remove the @model YourModelType from the top of the partial view and it will default to a dynamic type.

Update

The default view engine will search for partial views in the same folder as the view calling the partial and then in the ~/Views/Shared folder. If your partial is located in a different folder then you need to use the full path. Note the use of ~/ in the path below.

@Html.Partial("~/Views/Partials/SeachResult.cshtml", Model)

Parsing arguments to a Java command line program

Simple code for command line in java:

class CMDLineArgument
{
    public static void main(String args[])
    {
        String name=args[0];
        System.out.println(name);
    }
}

Obtain form input fields using jQuery?

$('#myForm').submit(function() {
    // get all the inputs into an array.
    var $inputs = $('#myForm :input');

    // not sure if you wanted this, but I thought I'd add it.
    // get an associative array of just the values.
    var values = {};
    $inputs.each(function() {
        values[this.name] = $(this).val();
    });

});

Thanks to the tip from Simon_Weaver, here is another way you could do it, using serializeArray:

var values = {};
$.each($('#myForm').serializeArray(), function(i, field) {
    values[field.name] = field.value;
});

Note that this snippet will fail on <select multiple> elements.

It appears that the new HTML 5 form inputs don't work with serializeArray in jQuery version 1.3. This works in version 1.4+

Difference between static STATIC_URL and STATIC_ROOT on Django

STATICFILES_DIRS: You can keep the static files for your project here e.g. the ones used by your templates.

STATIC_ROOT: leave this empty, when you do manage.py collectstatic, it will search for all the static files on your system and move them here. Your static file server is supposed to be mapped to this folder wherever it is located. Check it after running collectstatic and you'll find the directory structure django has built.

--------Edit----------------

As pointed out by @DarkCygnus, STATIC_ROOT should point at a directory on your filesystem, the folder should be empty since it will be populated by Django.

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

or

STATIC_ROOT = '/opt/web/project/static_files'

--------End Edit -----------------

STATIC_URL: '/static/' is usually fine, it's just a prefix for static files.

Set a persistent environment variable from cmd.exe

Indeed SET TEST_VARIABLE=value works for current process only, so SETX is required. A quick example for permanently storing an environment variable at user level.

  1. In cmd, SETX TEST_VARIABLE etc. Not applied yet (echo %TEST_VARIABLE% shows %TEST_VARIABLE%,
  2. Quick check: open cmd, echo %TEST_VARIABLE% shows etc.
  3. GUI check: System Properties -> Advanced -> Environment variables -> User variables for -> you should see Varible TEST_VARIABLE with value etc.

How to dump only specific tables from MySQL?

If you're in local machine then use this command

/usr/local/mysql/bin/mysqldump -h127.0.0.1 --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;

For remote machine, use below one

/usr/local/mysql/bin/mysqldump -h [remoteip] --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;

1064 error in CREATE TABLE ... TYPE=MYISAM

As documented under CREATE TABLE Syntax:

Note
The older TYPE option was synonymous with ENGINE. TYPE was deprecated in MySQL 4.0 and removed in MySQL 5.5. When upgrading to MySQL 5.5 or later, you must convert existing applications that rely on TYPE to use ENGINE instead.

Therefore, you want:

CREATE TABLE dave_bannedwords(
  id   INT(11)     NOT NULL AUTO_INCREMENT,
  word VARCHAR(60) NOT NULL DEFAULT '',
  PRIMARY KEY (id),
  KEY id(id) -- this is superfluous in the presence of your PK, ergo unnecessary
) ENGINE = MyISAM ;

Getting the ID of the element that fired an event

Though it is mentioned in other posts, I wanted to spell this out:

$(event.target).id is undefined

$(event.target)[0].id gives the id attribute.

event.target.id also gives the id attribute.

this.id gives the id attribute.

and

$(this).id is undefined.

The differences, of course, is between jQuery objects and DOM objects. "id" is a DOM property so you have to be on the DOM element object to use it.

(It tripped me up, so it probably tripped up someone else)

Stop embedded youtube iframe?

Here's a pure javascript solution,

<iframe 
width="100%" 
height="443" 
class="yvideo" 
id="p1QgNF6J1h0"
src="http://www.youtube.com/embed/p1QgNF6J1h0?rel=0&controls=0&hd=1&showinfo=0&enablejsapi=1"
frameborder="0" 
allowfullscreen>
</iframe>
<button id="myStopClickButton">Stop</button>


<script>
document.getElementById("myStopClickButton").addEventListener("click",    function(evt){
var video = document.getElementsByClassName("yvideo");
for (var i=0; i<video.length; i++) {
   video.item(i).contentWindow.postMessage('{"event":"command","func":"stopVideo","args":""}', '*');
}

});

How can I modify a saved Microsoft Access 2007 or 2010 Import Specification?

Tim Lentine's answer works IF you have yours specs saved. Your question did not specify that, it only stated you had imported the data. His method would not save your specs that way.

The way to save the spec of that current import is to re-open the import, hit "apend" and that will allow you to use your current import settings that MS Access picked up. (This is useful if your want to keep the import specs from an Excel format you worked on prior to importing into MS ACCESS.)

Once you're in the apend option, use Tim's instructions, which is using the advanced option and "Save As." From there, simply click cancel, and you can now import any other similar data to various tables, etc.

Removing a non empty directory programmatically in C or C++

//======================================================
// Recursely Delete files using:
//   Gnome-Glib & C++11
//======================================================

#include <iostream>
#include <string>
#include <glib.h>
#include <glib/gstdio.h>

using namespace std;

int DirDelete(const string& path)
{
   const gchar*    p;
   GError*   gerr;
   GDir*     d;
   int       r;
   string    ps;
   string    path_i;
   cout << "open:" << path << "\n";
   d        = g_dir_open(path.c_str(), 0, &gerr);
   r        = -1;

   if (d) {
      r = 0;

      while (!r && (p=g_dir_read_name(d))) {
          ps = string{p};
          if (ps == "." || ps == "..") {
            continue;
          }

          path_i = path + string{"/"} + p;


          if (g_file_test(path_i.c_str(), G_FILE_TEST_IS_DIR) != 0) {
            cout << "recurse:" << path_i << "\n";
            r = DirDelete(path_i);
          }
          else {
            cout << "unlink:" << path_i << "\n";
            r = g_unlink(path_i.c_str());
          }
      }

      g_dir_close(d);
   }

   if (r == 0) {
      r = g_rmdir(path.c_str());
     cout << "rmdir:" << path << "\n";

   }

   return r;
}

How to calculate UILabel width based on text length?

In iOS8 sizeWithFont has been deprecated, please refer to

CGSize yourLabelSize = [yourLabel.text sizeWithAttributes:@{NSFontAttributeName : [UIFont fontWithName:yourLabel.font size:yourLabel.fontSize]}];

You can add all the attributes you want in sizeWithAttributes. Other attributes you can set:

- NSForegroundColorAttributeName
- NSParagraphStyleAttributeName
- NSBackgroundColorAttributeName
- NSShadowAttributeName

and so on. But probably you won't need the others

CSS background image URL failing to load

source URL for image can be a URL on a website like http://www.google.co.il/images/srpr/nav_logo73.png or https://https.openbsd.org/images/tshirt-26_front.gif or if you want to use a local file try this: url("file:///MacintoshHDOriginal/Users/lowri/Desktop/acgnx/image s/images/acgn-site-background-X_07.jpg")

Converting JSON String to Dictionary Not List

The best way to Load JSON Data into Dictionary is You can user the inbuilt json loader.

Below is the sample snippet that can be used.

import json
f = open("data.json")
data = json.load(f))
f.close()
type(data)
print(data[<keyFromTheJsonFile>])

jQuery click function doesn't work after ajax call?

Here's the FIDDLE

Same code as yours but it will work on dynamically created elements.

$(document).on('click', '.deletelanguage', function () {
    alert("success");
    $('#LangTable').append(' <br>------------<br> <a class="deletelanguage">Now my class is deletelanguage. click me to test it is not working.</a>');
});

Connect Android to WiFi Enterprise network EAP(PEAP)

Finally, I've defeated my CiSCO EAP-FAST corporate wifi network, and all our Android devices are now able to connect to it.

The walk-around I've performed in order to gain access to this kind of networks from an Android device are easiest than you can imagine.

There's a Wifi Config Editor in the Google Play Store you can use to "activate" the secondary CISCO Protocols when you are setting up a EAP wifi connection.

Its name is Wifi Config Advanced Editor.

  • First, you have to setup your wireless network manually as close as you can to your "official" corporate wifi parameters.

  • Save it.

  • Go to the WCE and edit the parameters of the network you have created in the previous step.

  • There are 3 or 4 series of settings you should activate in order to force the Android device to use them as a way to connect (the main site I think you want to visit is Enterprise Configuration, but don't forget to check all the parameters to change them if needed.
    As a suggestion, even if you have a WPA2 EAP-FAST Cipher, try LEAP in your setup. It worked for me as a charm.

  • When you finished to edit the config, go to the main Android wifi controller, and force to connect to this network.

  • Do not Edit the network again with the Android wifi interface.

I have tested it on Samsung Galaxy 1 and 2, Note mobile devices, and on a Lenovo Thinkpad Tablet.

laravel 5.4 upload image

if ($request->hasFile('input_img')) {
    if($request->file('input_img')->isValid()) {
        try {
            $file = $request->file('input_img');
            $name = time() . '.' . $file->getClientOriginalExtension();

            $request->file('input_img')->move("fotoupload", $name);
        } catch (Illuminate\Filesystem\FileNotFoundException $e) {

        }
    } 
}

or follow
https://laracasts.com/discuss/channels/laravel/image-upload-file-does-not-working
or
https://laracasts.com/series/whats-new-in-laravel-5-3/episodes/12

How many concurrent requests does a single Flask process receive?

When running the development server - which is what you get by running app.run(), you get a single synchronous process, which means at most 1 request is being processed at a time.

By sticking Gunicorn in front of it in its default configuration and simply increasing the number of --workers, what you get is essentially a number of processes (managed by Gunicorn) that each behave like the app.run() development server. 4 workers == 4 concurrent requests. This is because Gunicorn uses its included sync worker type by default.

It is important to note that Gunicorn also includes asynchronous workers, namely eventlet and gevent (and also tornado, but that's best used with the Tornado framework, it seems). By specifying one of these async workers with the --worker-class flag, what you get is Gunicorn managing a number of async processes, each of which managing its own concurrency. These processes don't use threads, but instead coroutines. Basically, within each process, still only 1 thing can be happening at a time (1 thread), but objects can be 'paused' when they are waiting on external processes to finish (think database queries or waiting on network I/O).

This means, if you're using one of Gunicorn's async workers, each worker can handle many more than a single request at a time. Just how many workers is best depends on the nature of your app, its environment, the hardware it runs on, etc. More details can be found on Gunicorn's design page and notes on how gevent works on its intro page.

Git fetch remote branch

Let's say that your remote is [email protected] and you want its random_branch branch. The process should be as follows:

  1. First check the list of your remotes by

    git remote -v

  2. If you don't have the [email protected] remote in the above command's output, you would add it by

    git remote add xyz [email protected]

  3. Now you can fetch the contents of that remote by

    git fetch xyz

  4. Now checkout the branch of that remote by

    git checkout -b my_copy_random_branch xyz/random_branch

  5. Check the branch list by

    git branch -a

The local branch my_copy_random_branch would be tracking the random_branch branch of your remote.

How to ignore whitespace in a regular expression subject string?

While the accepted answer is technically correct, a more practical approach, if possible, is to just strip whitespace out of both the regular expression and the search string.

If you want to search for "my cats", instead of:

myString.match(/m\s*y\s*c\s*a\*st\s*s\s*/g)

Just do:

myString.replace(/\s*/g,"").match(/mycats/g)

Warning: You can't automate this on the regular expression by just replacing all spaces with empty strings because they may occur in a negation or otherwise make your regular expression invalid.

How do I capture SIGINT in Python?

Yet Another Snippet

Referred main as the main function and exit_gracefully as the CTRL + c handler

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        pass
    finally:
        exit_gracefully()

In android how to set navigation drawer header image and name programmatically in class file?

NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.addHeaderView(yourview);

How to Export-CSV of Active Directory Objects?

HI you can try this...

Try..

$Ad = Get-ADUser -SearchBase "OU=OUi,DC=company,DC=com"  -Filter * -Properties employeeNumber | ? {$_.employeenumber -eq ""}
$Ad | Sort-Object -Property sn, givenName | Select * | Export-Csv c:\scripts\ceridian\NoClockNumber_2013_02_12.csv -NoTypeInformation

Or

$Ad = Get-ADUser -SearchBase "OU=OUi,DC=company,DC=com"  -Filter * -Properties employeeNumber | ? {$_.employeenumber -eq $null}
$Ad | Sort-Object -Property sn, givenName | Select * | Export-Csv c:\scripts\cer

Hope it works for you.

How to convert BigInteger to String in java

You want to use BigInteger.toByteArray()

String msg = "Hello there!";
BigInteger bi = new BigInteger(msg.getBytes());
System.out.println(new String(bi.toByteArray())); // prints "Hello there!"

The way I understand it is that you're doing the following transformations:

  String  -----------------> byte[] ------------------> BigInteger
          String.getBytes()         BigInteger(byte[])

And you want the reverse:

  BigInteger ------------------------> byte[] ------------------> String
             BigInteger.toByteArray()          String(byte[])

Note that you probably want to use overloads of String.getBytes() and String(byte[]) that specifies an explicit encoding, otherwise you may run into encoding issues.

How can I stop Chrome from going into debug mode?

For anyone that's searching why their chrome debugger is automatically jumping to sources tab on every page load, event though all of the breakpoints/pauses/etc have been disabled.

For me it was the "breakOnLoad": true line in VS Code launch.json config.

ESLint not working in VS Code?

In my case ESLint was disabled in my workspace. I had to enable it in vscode extensions settings.

How to return the output of stored procedure into a variable in sql server

That depends on the nature of the information you want to return.

If it is a single integer value, you can use the return statement

 create proc myproc
 as 
 begin
     return 1
 end
 go
 declare @i int
 exec @i = myproc

If you have a non integer value, or a number of scalar values, you can use output parameters

create proc myproc
  @a int output,
  @b varchar(50) output
as
begin
  select @a = 1, @b='hello'
end
go
declare @i int, @j varchar(50)
exec myproc @i output, @j output

If you want to return a dataset, you can use insert exec

create proc myproc
as 
begin
     select name from sysobjects
end
go

declare @t table (name varchar(100))
insert @t (name)
exec myproc

You can even return a cursor but that's just horrid so I shan't give an example :)

How to make a vertical line in HTML

I needed an inline vertical line, so I tricked a button into becoming a line.

<button type="button" class="v_line">l</button>

.v_line {
         width: 0px;
         padding: .5em .5px;
         background-color: black;
         margin: 0px; 4px;
        }

TypeScript hashmap/dictionary interface

var x : IHash = {};
x['key1'] = 'value1';
x['key2'] = 'value2';

console.log(x['key1']);
// outputs value1

console.log(x['key2']);
// outputs value2

If you would like to then iterate through your dictionary, you can use.

Object.keys(x).forEach((key) => {console.log(x[key])});

Object.keys returns all the properties of an object, so it works nicely for returning all the values from dictionary styled objects.

You also mentioned a hashmap in your question, the above definition is for a dictionary style interface. Therefore the keys will be unique, but the values will not.

You could use it like a hashset by just assigning the same value to the key and its value.

if you wanted the keys to be unique and with potentially different values, then you just have to check if the key exists on the object before adding to it.

var valueToAdd = 'one';
if(!x[valueToAdd])
   x[valueToAdd] = valueToAdd;

or you could build your own class to act as a hashset of sorts.

Class HashSet{
  private var keys: IHash = {};
  private var values: string[] = [];

  public Add(key: string){
    if(!keys[key]){
      values.push(key);
      keys[key] = key;
    }
  }

  public GetValues(){
    // slicing the array will return it by value so users cannot accidentally
    // start playing around with your array
    return values.slice();
  }
}

Conditional Formatting using Excel VBA code

I think I just discovered a way to apply overlapping conditions in the expected way using VBA. After hours of trying out different approaches I found that what worked was changing the "Applies to" range for the conditional format rule, after every single one was created!

This is my working example:

Sub ResetFormatting()
' ----------------------------------------------------------------------------------------
' Written by..: Julius Getz Mørk
' Purpose.....: If conditional formatting ranges are broken it might cause a huge increase
'               in duplicated formatting rules that in turn will significantly slow down
'               the spreadsheet.
'               This macro is designed to reset all formatting rules to default.
' ---------------------------------------------------------------------------------------- 

On Error GoTo ErrHandler

' Make sure we are positioned in the correct sheet
WS_PROMO.Select

' Disable Events
Application.EnableEvents = False

' Delete all conditional formatting rules in sheet
Cells.FormatConditions.Delete

' CREATE ALL THE CONDITIONAL FORMATTING RULES:

' (1) Make negative values red
With Cells(1, 1).FormatConditions.add(xlCellValue, xlLess, "=0")
    .Font.Color = -16776961
    .StopIfTrue = False
End With

' (2) Highlight defined good margin as green values
With Cells(1, 1).FormatConditions.add(xlCellValue, xlGreater, "=CP_HIGH_MARGIN_DEFINITION")
    .Font.Color = -16744448
    .StopIfTrue = False
End With

' (3) Make article strategy "D" red
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""D""")
    .Font.Bold = True
    .Font.Color = -16776961
    .StopIfTrue = False
End With

' (4) Make article strategy "A" blue
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""A""")
    .Font.Bold = True
    .Font.Color = -10092544
    .StopIfTrue = False
End With

' (5) Make article strategy "W" green
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""W""")
    .Font.Bold = True
    .Font.Color = -16744448
    .StopIfTrue = False
End With

' (6) Show special cost in bold green font
With Cells(1, 1).FormatConditions.add(xlCellValue, xlNotEqual, "=0")
    .Font.Bold = True
    .Font.Color = -16744448
    .StopIfTrue = False
End With

' (7) Highlight duplicate heading names. There can be none.
With Cells(1, 1).FormatConditions.AddUniqueValues
    .DupeUnique = xlDuplicate
    .Font.Color = -16383844
    .Interior.Color = 13551615
    .StopIfTrue = False
End With

' (8) Make heading rows bold with yellow background
With Cells(1, 1).FormatConditions.add(Type:=xlExpression, Formula1:="=IF($B8=""H"";TRUE;FALSE)")
    .Font.Bold = True
    .Interior.Color = 13434879
    .StopIfTrue = False
End With

' Modify the "Applies To" ranges
Cells.FormatConditions(1).ModifyAppliesToRange Range("O8:P507")
Cells.FormatConditions(2).ModifyAppliesToRange Range("O8:O507")
Cells.FormatConditions(3).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(4).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(5).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(6).ModifyAppliesToRange Range("E8:E507")
Cells.FormatConditions(7).ModifyAppliesToRange Range("A7:AE7")
Cells.FormatConditions(8).ModifyAppliesToRange Range("B8:L507")


ErrHandler:
Application.EnableEvents = False

End Sub

Onclick function based on element id

Make sure your code is in DOM Ready as pointed by rocket-hazmat

.click()

$('#RootNode').click(function(){
  //do something
});

document.getElementById("RootNode").onclick = function(){//do something}


.on()

Use event Delegation/

$(document).on("click", "#RootNode", function(){
   //do something
});


Try

Wrap Code in Dom Ready

$(document).ready(function(){
    $('#RootNode').click(function(){
     //do something
    });
});

Failed binder transaction when putting an bitmap dynamically in a widget

The Binder transaction buffer has a limited fixed size, currently 1Mb, which is shared by all transactions in progress for the process. Consequently this exception can be thrown when there are many transactions in progress even when most of the individual transactions are of moderate size.

refer this link

How do you make an anchor link non-clickable or disabled?

You could use the onclick event to disable the click action:

<a href='' id='ThisLink' onclick='return false'>some text</a>

Or you could just use something other than an <a> tag.

Finding three elements in an array whose sum is closest to a given number

Another solution that checks and fails early:

public boolean solution(int[] input) {
        int length = input.length;

        if (length < 3) {
            return false;
        }

        // x + y + z = 0  => -z = x + y
        final Set<Integer> z = new HashSet<>(length);
        int zeroCounter = 0, sum; // if they're more than 3 zeros we're done

        for (int element : input) {
            if (element < 0) {
                z.add(element);
            }

            if (element == 0) {
                ++zeroCounter;
                if (zeroCounter >= 3) {
                    return true;
                }
            }
        }

        if (z.isEmpty() || z.size() == length || (z.size() + zeroCounter == length)) {
            return false;
        } else {
            for (int x = 0; x < length; ++x) {
                for (int y = x + 1; y < length; ++y) {
                    sum = input[x] + input[y]; // will use it as inverse addition
                    if (sum < 0) {
                        continue;
                    }
                    if (z.contains(sum * -1)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

I added some unit tests here: GivenArrayReturnTrueIfThreeElementsSumZeroTest.

If the set is using too much space I can easily use a java.util.BitSet that will use O(n/w) space.

How do you sort a dictionary by value?

Use LINQ:

Dictionary<string, int> myDict = new Dictionary<string, int>();
myDict.Add("one", 1);
myDict.Add("four", 4);
myDict.Add("two", 2);
myDict.Add("three", 3);

var sortedDict = from entry in myDict orderby entry.Value ascending select entry;

This would also allow for great flexibility in that you can select the top 10, 20 10%, etc. Or if you are using your word frequency index for type-ahead, you could also include StartsWith clause as well.

Use jQuery to change an HTML tag?

I came up with an approach where you use a string representation of your jQuery object and replace the tag name using regular expressions and basic JavaScript. You will not loose any content and don't have to loop over each attribute/property.

/*
 * replaceTag
 * @return {$object} a new object with replaced opening and closing tag
 */
function replaceTag($element, newTagName) {

  // Identify opening and closing tag
  var oldTagName = $element[0].nodeName,
    elementString = $element[0].outerHTML,
    openingRegex = new RegExp("^(<" + oldTagName + " )", "i"),
    openingTag = elementString.match(openingRegex),
    closingRegex = new RegExp("(<\/" + oldTagName + ">)$", "i"),
    closingTag = elementString.match(closingRegex);

  if (openingTag && closingTag && newTagName) {
    // Remove opening tag
    elementString = elementString.slice(openingTag[0].length);
    // Remove closing tag
    elementString = elementString.slice(0, -(closingTag[0].length));
    // Add new tags
    elementString = "<" + newTagName + " " + elementString + "</" + newTagName + ">";
  }

  return $(elementString);
}

Finally, you can replace the existing object/node as follows:

var $newElement = replaceTag($rankingSubmit, 'a');
$('#not-an-a-element').replaceWith($newElement);

How to copy and paste worksheets between Excel workbooks?

easiest way:

Dim newBook As Workbook  
Set newBook = Workbooks.Add

Sheets("Sheet1").Copy Before:=newBook.Sheets(1)

What are the uses of "using" in C#?

The using keyword defines the scope for the object and then disposes of the object when the scope is complete. For example.

using (Font font2 = new Font("Arial", 10.0f))
{
    // use font2
}

See here for the MSDN article on the C# using keyword.

How can I remove punctuation from input text in Java?

I don't like to use regex, so here is another simple solution.

public String removePunctuations(String s) {
    String res = "";
    for (Character c : s.toCharArray()) {
        if(Character.isLetterOrDigit(c))
            res += c;
    }
    return res;
}

Note: This will include both Letters and Digits

Is there a C++ decompiler?

I haven't seen any decompilers that generate C++ code. I've seen a few experimental ones that make a reasonable attempt at generating C code, but they tended to be dependent on matching the code-generation patterns of a particular compiler (that may have changed, it's been awhile since I last looked into this). Of course any symbolic information will be gone. Google for "decompiler".

How to convert SecureString to System.String?

In my opinion, extension methods are the most comfortable way to solve this.

I took Steve in CO's excellent answer and put it into an extension class as follows, together with a second method I added to support the other direction (string -> secure string) as well, so you can create a secure string and convert it into a normal string afterwards:

public static class Extensions
{
    // convert a secure string into a normal plain text string
    public static String ToPlainString(this System.Security.SecureString secureStr)
    {
        String plainStr=new System.Net.NetworkCredential(string.Empty, secureStr).Password;
        return plainStr;
    }

    // convert a plain text string into a secure string
    public static System.Security.SecureString ToSecureString(this String plainStr)
    {
        var secStr = new System.Security.SecureString(); secStr.Clear();
        foreach (char c in plainStr.ToCharArray())
        {
            secStr.AppendChar(c);
        }
        return secStr;
    }
}

With this, you can now simply convert your strings back and forth like so:

// create a secure string
System.Security.SecureString securePassword = "MyCleverPwd123".ToSecureString(); 
// convert it back to plain text
String plainPassword = securePassword.ToPlainString();  // convert back to normal string

But keep in mind the decoding method should only be used for testing.

How do I get bootstrap-datepicker to work with Bootstrap 3?

I also use Stefan Petre’s http://www.eyecon.ro/bootstrap-datepicker and it does not work with Bootstrap 3 without modification. Note that http://eternicode.github.io/bootstrap-datepicker/ is a fork of Stefan Petre's code.

You have to change your markup (the sample markup will not work) to use the new CSS and form grid layout in Bootstrap 3. Also, you have to modify some CSS and JavaScript in the actual bootstrap-datepicker implementation.

Here is my solution:

<div class="form-group row">
  <div class="col-xs-8">
    <label class="control-label">My Label</label>
    <div class="input-group date" id="dp3" data-date="12-02-2012" data-date-format="mm-dd-yyyy">
      <input class="form-control" type="text" readonly="" value="12-02-2012">
      <span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
    </div>
  </div>
</div>

CSS changes in datepicker.css on lines 176-177:

.input-group.date .input-group-addon i,
.input-group.date .input-group-addon i {

Javascript change in datepicker-bootstrap.js on line 34:

this.component = this.element.is('.date') ? this.element.find('.input-group-addon') : false;

UPDATE

Using the newer code from http://eternicode.github.io/bootstrap-datepicker/ the changes are as follows:

CSS changes in datepicker.css on lines 446-447:

.input-group.date .input-group-addon i,
.input-group.date .input-group-addon i {

Javascript change in datepicker-bootstrap.js on line 46:

 this.component = this.element.is('.date') ? this.element.find('.input-group-addon, .btn') : false;

Finally, the JavaScript to enable the datepicker (with some options):

 $(".input-group.date").datepicker({ autoclose: true, todayHighlight: true });

Tested with Bootstrap 3.0 and JQuery 1.9.1. Note that this fork is better to use than the other as it is more feature rich, has localization support and auto-positions the datepicker based on the control position and window size, avoiding the picker going off the screen which was a problem with the older version.

What is the difference between <p> and <div>?

<p> represents a paragraph and <div> represents a 'division', I suppose the main difference is that divs are semantically 'meaningless', where as a <p> is supposed to represent something relating to the text itself.

You wouldn't want to have nested <p>s for example, since that wouldn't make much semantic sense (except in the sense of quotations) Whereas people use nested <div>s for page layout.

According to Wikipedia

In HTML, the span and div elements are used where parts of a document cannot be semantically described by other HTML elements.

How to remove responsive features in Twitter Bootstrap 3?

Look at www.goo.gl/2SIOJj it is a work in progress but it may help you.

I use cookie to define if i want desktop or responsive version. In the footer of the page you can find two spans and in general.js is the script to handle the clicks.

        <div class="col-xs-6" style="text-align:center;"><span class="make_desktop">Desktop</span></div>
        <div class="col-xs-6" style="text-align:center;"><span class="make_responsive">Mobile</span></div>

function setMobDeskCookie(c_name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays === null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value + "; path=/";
    window.location.reload();
}

$(function() {
    $(".make_desktop").click(function() {
        setMobDeskCookie('deskmob', 1, 3650);
    });
    $(".make_responsive").click(function() {
        setMobDeskCookie('deskmob', 0, 3650);
    });
});`enter code here`

i ended up splitting all my custom css into two files i don't use bootstrap navigation but my own so that is majority of my custom styles, so it will not resolve your entire problem but it works for me

and i also created non-responsive.css that forces the grid to maintain the large screen version

in case u select mobile i would load / echo

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">  
<!-- Bootstrap core CSS and JS -->
        <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
        <link href="/themes/responsive_lime/bootstrap-3_1_1/css/bootstrap.css" rel="stylesheet">
        <script src="/themes/responsive_lime/bootstrap-3_1_1/js/bootstrap.min.js"></script>

and load these stylesheets
<link rel="stylesheet" type="text/css" media="screen,print" href="/themes/responsive_lime/css/style.css?modified=14-06-2014-12-27-40" />
<link rel="stylesheet" type="text/css" media="screen,print" href="/themes/responsive_lime/css/style-responsive.css?modified=1402758346" />

in case you select desktop i would load /echo

<meta name="viewport" content="width=1024">    


        <!-- Bootstrap core CSS and JS -->
        <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
        <link href="/themes/responsive_lime/bootstrap-3_1_1/css/bootstrap.css" rel="stylesheet">
        <script src="/themes/responsive_lime/bootstrap-3_1_1/js/bootstrap.min.js"></script>

        <!-- Main CSS -->
        <link rel="stylesheet" type="text/css" media="screen,print" href="/themes/responsive_lime/css/style.css?modified=14-06-2014-12-27-40" />
<link rel="stylesheet" type="text/css" media="screen,print" href="/themes/responsive_lime/css/non-responsive.css?modified=1402758635" />

the non-responsive.css is the one that has overrides for bootstrap my concern is layout so there is not much in there, given that i handle the navigation in my own way so css for it and the other bits is in my other css files

please note that my setup does behave as desktop even on desktop browsers unlike some other solutions i have seen that will only ignore the viewport that seems to have wotked only on mobile devices for me

How do I grep for all non-ASCII characters?

The following code works:

find /tmp | perl -ne 'print if /[^[:ascii:]]/'

Replace /tmp with the name of the directory you want to search through.

select rows in sql with latest date for each ID repeated multiple times

Have you tried the following:

SELECT ID, COUNT(*), max(date)
FROM table 
GROUP BY ID;

How can I make a div stick to the top of the screen once it's been scrolled to?

You could use simply css, positioning your element as fixed:

.fixedElement {
    background-color: #c0c0c0;
    position:fixed;
    top:0;
    width:100%;
    z-index:100;
}

Edit: You should have the element with position absolute, once the scroll offset has reached the element, it should be changed to fixed, and the top position should be set to zero.

You can detect the top scroll offset of the document with the scrollTop function:

$(window).scroll(function(e){ 
  var $el = $('.fixedElement'); 
  var isPositionFixed = ($el.css('position') == 'fixed');
  if ($(this).scrollTop() > 200 && !isPositionFixed){ 
    $el.css({'position': 'fixed', 'top': '0px'}); 
  }
  if ($(this).scrollTop() < 200 && isPositionFixed){
    $el.css({'position': 'static', 'top': '0px'}); 
  } 
});

When the scroll offset reached 200, the element will stick to the top of the browser window, because is placed as fixed.

Find a private field with Reflection?

You can do it just like with a property:

FieldInfo fi = typeof(Foo).GetField("_bar", BindingFlags.NonPublic | BindingFlags.Instance);
if (fi.GetCustomAttributes(typeof(SomeAttribute)) != null)
    ...

Find Locked Table in SQL Server

sp_lock

When reading sp_lock information, use the OBJECT_NAME( ) function to get the name of a table from its ID number, for example:

SELECT object_name(16003073)

EDIT :

There is another proc provided by microsoft which reports objects without the ID translation : http://support.microsoft.com/kb/q255596/

Linux / Bash, using ps -o to get process by specific name?

Sometimes you need to grep the process by name - in that case:

ps aux | grep simple-scan

Example output:

simple-scan  1090  0.0  0.1   4248  1432 ?        S    Jun11   0:00

Why can't I push to this bare repository?

git push --all

is the canonical way to push everything to a new bare repository.

Another way to do the same thing is to create your new, non-bare repository and then make a bare clone with

git clone --bare

then use

git remote add origin <new-remote-repo>

in the original (non-bare) repository.

Recursion in Python? RuntimeError: maximum recursion depth exceeded while calling a Python object

The error is a stack overflow. That should ring a bell on this site, right? It occurs because a call to poruszanie results in another call to poruszanie, incrementing the recursion depth by 1. The second call results in another call to the same function. That happens over and over again, each time incrementing the recursion depth.

Now, the usable resources of a program are limited. Each function call takes a certain amount of space on top of what is called the stack. If the maximum stack height is reached, you get a stack overflow error.

Replace part of a string with another string

There's a function to find a substring within a string (find), and a function to replace a particular range in a string with another string (replace), so you can combine those to get the effect you want:

bool replace(std::string& str, const std::string& from, const std::string& to) {
    size_t start_pos = str.find(from);
    if(start_pos == std::string::npos)
        return false;
    str.replace(start_pos, from.length(), to);
    return true;
}

std::string string("hello $name");
replace(string, "$name", "Somename");

In response to a comment, I think replaceAll would probably look something like this:

void replaceAll(std::string& str, const std::string& from, const std::string& to) {
    if(from.empty())
        return;
    size_t start_pos = 0;
    while((start_pos = str.find(from, start_pos)) != std::string::npos) {
        str.replace(start_pos, from.length(), to);
        start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
    }
}

set value of input field by php variable's value

inside the Form, You can use this code. Replace your variable name (i use $variable)

<input type="text" value="<?php echo (isset($variable))?$variable:'';?>">

Add Legend to Seaborn point plot

I tried using Adam B's answer, however, it didn't work for me. Instead, I found the following workaround for adding legends to pointplots.

import matplotlib.patches as mpatches
red_patch = mpatches.Patch(color='#bb3f3f', label='Label1')
black_patch = mpatches.Patch(color='#000000', label='Label2')

In the pointplots, the color can be specified as mentioned in previous answers. Once these patches corresponding to the different plots are set up,

plt.legend(handles=[red_patch, black_patch])

And the legend ought to appear in the pointplot.

How to create custom config section in app.config?

Import namespace :

using System.Configuration;

Create ConfigurationElement Company :

public class Company : ConfigurationElement
{

        [ConfigurationProperty("name", IsRequired = true)]
        public string Name
        {
            get
            {
                return this["name"] as string;
            }
        }
            [ConfigurationProperty("code", IsRequired = true)]
        public string Code
        {
            get
            {
                return this["code"] as string;
            }
        }
}

ConfigurationElementCollection:

public class Companies
        : ConfigurationElementCollection
    {
        public Company this[int index]
        {
            get
            {
                return base.BaseGet(index) as Company ;
            }
            set
            {
                if (base.BaseGet(index) != null)
                {
                    base.BaseRemoveAt(index);
                }
                this.BaseAdd(index, value);
            }
        }

       public new Company this[string responseString]
       {
            get { return (Company) BaseGet(responseString); }
            set
            {
                if(BaseGet(responseString) != null)
                {
                    BaseRemoveAt(BaseIndexOf(BaseGet(responseString)));
                }
                BaseAdd(value);
            }
        }

        protected override System.Configuration.ConfigurationElement CreateNewElement()
        {
            return new Company();
        }

        protected override object GetElementKey(System.Configuration.ConfigurationElement element)
        {
            return ((Company)element).Name;
        }
    }

and ConfigurationSection:

public class RegisterCompaniesConfig
        : ConfigurationSection
    {

        public static RegisterCompaniesConfig GetConfig()
        {
            return (RegisterCompaniesConfig)System.Configuration.ConfigurationManager.GetSection("RegisterCompanies") ?? new RegisterCompaniesConfig();
        }

        [System.Configuration.ConfigurationProperty("Companies")]
            [ConfigurationCollection(typeof(Companies), AddItemName = "Company")]
        public Companies Companies
        {
            get
            {
                object o = this["Companies"];
                return o as Companies ;
            }
        }

    }

and you must also register your new configuration section in web.config (app.config):

<configuration>       
    <configSections>
          <section name="Companies" type="blablabla.RegisterCompaniesConfig" ..>

then you load your config with

var config = RegisterCompaniesConfig.GetConfig();
foreach(var item in config.Companies)
{
   do something ..
}

Android Material and appcompat Manifest merger failed

Follow these steps:

  • Goto Refactor and Click Migrate to AndroidX
  • Click Do Refactor

continuous page numbering through section breaks

You can check out this post on SuperUser.

Word starts page numbering over for each new section by default.

I do it slightly differently than the post above that goes through the ribbon menus, but in both methods you have to go through the document to each section's beginning.

My method:

  • open up the footer (or header if that's where your page number is)
  • drag-select the page number
  • right-click on it
  • hit Format Page Numbers
  • click on the Continue from Previous Section radio button under Page numbering

I find this right-click method to be a little faster. Also, usually if I insert the page numbers first before I start making any new sections, this problem doesn't happen in the first place.

How to overwrite existing files in batch?

you need to simply add /Y

xcopy /s c:\mmyinbox\test.doc C:\myoutbox /Y

and if you're using path with spaces, try this

xcopy /s "c:\mmyinbox\test.doc" "C:\myoutbox" /Y

Are there best practices for (Java) package organization?

Are there best practices with regards to the organisation of packages in Java and what goes in them?

Not really no. There are lots of ideas, and lots opinions, but real "best practice" is to use your common sense!

(Please read No best Practices for a perspective on "best practices" and the people who promote them.)

However, there is one principal that probably has broad acceptance. Your package structure should reflect your application's (informal) module structure, and you should aim to minimize (or ideally entirely avoid) any cyclic dependencies between modules.

(Cyclic dependencies between classes in a package / module are just fine, but inter-package cycles tend to make it hard understand your application's architecture, and can be a barrier to code reuse. In particular, if you use Maven you will find that cyclic inter-package / inter-module dependencies mean that the whole interconnected mess has to be one Maven artifact.)

I should also add that there is one widely accepted best practice for package names. And that is that your package names should start with your organization's domain name in reverse order. If you follow this rule, you reduce the likelihood of problems caused by your (full) class names clashing with other peoples'.

How do I change UIView Size?

This can be achieved in various methods in Swift 3.0 Worked on Latest version MAY- 2019

Directly assign the Height & Width values for a view:

userView.frame.size.height = 0

userView.frame.size.width = 10

Assign the CGRect for the Frame

userView.frame =  CGRect(x:0, y: 0, width:0, height:0)

Method Details:

CGRect(x: point of X, y: point of Y, width: Width of View, height: Height of View)

Using an Extension method for CGRECT

Add following extension code in any swift file,

extension CGRect {

    init(_ x:CGFloat, _ y:CGFloat, _ w:CGFloat, _ h:CGFloat) {

        self.init(x:x, y:y, width:w, height:h)
    }
}

Use the following code anywhere in your application for the view to set the size parameters

userView.frame =  CGRect(1, 1, 20, 45)

How do I render a Word document (.doc, .docx) in the browser using JavaScript?

I think I have an idea. This has been doing my nut in too and I'm still having trouble getting it to display in Chrome.

Save document(name.docx) in word as single file webpage (name.mht) In your html use

<iframe src= "name.mht" width="100%" height="800"> </iframe>

Alter the heights and widths as you see fit.

NSOperation vs Grand Central Dispatch

GCD is a low-level C-based API that enables very simple use of a task-based concurrency model. NSOperation and NSOperationQueue are Objective-C classes that do a similar thing. NSOperation was introduced first, but as of 10.5 and iOS 2, NSOperationQueue and friends are internally implemented using GCD.

In general, you should use the highest level of abstraction that suits your needs. This means that you should usually use NSOperationQueue instead of GCD, unless you need to do something that NSOperationQueue doesn't support.

Note that NSOperationQueue isn't a "dumbed-down" version of GCD; in fact, there are many things that you can do very simply with NSOperationQueue that take a lot of work with pure GCD. (Examples: bandwidth-constrained queues that only run N operations at a time; establishing dependencies between operations. Both very simple with NSOperation, very difficult with GCD.) Apple's done the hard work of leveraging GCD to create a very nice object-friendly API with NSOperation. Take advantage of their work unless you have a reason not to.

Caveat: On the other hand, if you really just need to send off a block, and don't need any of the additional functionality that NSOperationQueue provides, there's nothing wrong with using GCD. Just be sure it's the right tool for the job.

How to iterate for loop in reverse order in swift?

Updated for Swift 3

The answer below is a summary of the available options. Choose the one that best fits your needs.

reversed: numbers in a range

Forward

for index in 0..<5 {
    print(index)
}

// 0
// 1
// 2
// 3
// 4

Backward

for index in (0..<5).reversed() {
    print(index)
}

// 4
// 3
// 2
// 1
// 0

reversed: elements in SequenceType

let animals = ["horse", "cow", "camel", "sheep", "goat"]

Forward

for animal in animals {
    print(animal)
}

// horse
// cow
// camel
// sheep
// goat

Backward

for animal in animals.reversed() {
    print(animal)
}

// goat
// sheep
// camel
// cow
// horse

reversed: elements with an index

Sometimes an index is needed when iterating through a collection. For that you can use enumerate(), which returns a tuple. The first element of the tuple is the index and the second element is the object.

let animals = ["horse", "cow", "camel", "sheep", "goat"]

Forward

for (index, animal) in animals.enumerated() {
    print("\(index), \(animal)")
}

// 0, horse
// 1, cow
// 2, camel
// 3, sheep
// 4, goat

Backward

for (index, animal) in animals.enumerated().reversed()  {
    print("\(index), \(animal)")
}

// 4, goat
// 3, sheep
// 2, camel
// 1, cow
// 0, horse

Note that as Ben Lachman noted in his answer, you probably want to do .enumerated().reversed() rather than .reversed().enumerated() (which would make the index numbers increase).

stride: numbers

Stride is way to iterate without using a range. There are two forms. The comments at the end of the code show what the range version would be (assuming the increment size is 1).

startIndex.stride(to: endIndex, by: incrementSize)      // startIndex..<endIndex
startIndex.stride(through: endIndex, by: incrementSize) // startIndex...endIndex

Forward

for index in stride(from: 0, to: 5, by: 1) {
    print(index)
}

// 0
// 1
// 2
// 3
// 4

Backward

Changing the increment size to -1 allows you to go backward.

for index in stride(from: 4, through: 0, by: -1) {
    print(index)
}

// 4
// 3
// 2
// 1
// 0

Note the to and through difference.

stride: elements of SequenceType

Forward by increments of 2

let animals = ["horse", "cow", "camel", "sheep", "goat"]

I'm using 2 in this example just to show another possibility.

for index in stride(from: 0, to: 5, by: 2) {
    print("\(index), \(animals[index])")
}

// 0, horse
// 2, camel
// 4, goat

Backward

for index in stride(from: 4, through: 0, by: -1) {
    print("\(index), \(animals[index])")
}

// 4, goat
// 3, sheep 
// 2, camel
// 1, cow  
// 0, horse 

Notes

Hiding button using jQuery

You can use the .hide() function bound to a click handler:

$('#Comanda').click(function() {
    $(this).hide();
});

How to remove trailing whitespaces with sed?

You can use the in place option -i of sed for Linux and Unix:

sed -i 's/[ \t]*$//' "$1"

Be aware the expression will delete trailing t's on OSX (you can use gsed to avoid this problem). It may delete them on BSD too.

If you don't have gsed, here is the correct (but hard-to-read) sed syntax on OSX:

sed -i '' -E 's/[ '$'\t'']+$//' "$1"

Three single-quoted strings ultimately become concatenated into a single argument/expression. There is no concatenation operator in bash, you just place strings one after the other with no space in between.

The $'\t' resolves as a literal tab-character in bash (using ANSI-C quoting), so the tab is correctly concatenated into the expression.

How can I use a C++ library from node.js?

You could use emscripten to compile C++ code into js.

Passing data between view controllers

If you want to pass data from ViewControlerOne to ViewControllerTwo, try these...

Do these in ViewControlerOne.h:

 @property (nonatomic, strong) NSString *str1;

Do these in ViewControllerTwo.h:

 @property (nonatomic, strong) NSString *str2;

Synthesize str2 in ViewControllerTwo.m:

@interface ViewControllerTwo ()
@end
@implementation ViewControllerTwo
@synthesize str2;

Do these in ViewControlerOne.m:

 - (void)viewDidLoad
 {
   [super viewDidLoad];

   // Data or string you wants to pass in ViewControllerTwo...
   self.str1 = @"hello world";
 }

O the buttons click event, do this:

-(IBAction)ButtonClicked
{
  // Navigation on buttons click event from ViewControlerOne to ViewControlerTwo with transferring data or string..
  ViewControllerTwo *objViewTwo = [self.storyboard instantiateViewControllerWithIdentifier:@"ViewControllerTwo"];
  obj.str2 = str1;
  [self.navigationController pushViewController: objViewTwo animated:YES];
}

Do these in ViewControllerTwo.m:

- (void)viewDidLoad
{
  [super viewDidLoad];
  NSLog(@"%@", str2);
}

Ajax using https on an http page

http://example.com/ may resolve to a different VirtualHost than https://example.com/ (which, as the Host header is not sent, responds to the default for that IP), so the two are treated as separate domains and thus subject to crossdomain JS restrictions.

JSON callbacks may let you avoid this.

Real mouse position in canvas

You need to get the mouse position relative to the canvas

To do that you need to know the X/Y position of the canvas on the page.

This is called the canvas’s “offset”, and here’s how to get the offset. (I’m using jQuery in order to simplify cross-browser compatibility, but if you want to use raw javascript a quick Google will get that too).

    var canvasOffset=$("#canvas").offset();
    var offsetX=canvasOffset.left;
    var offsetY=canvasOffset.top;

Then in your mouse handler, you can get the mouse X/Y like this:

  function handleMouseDown(e){
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);
}

Here is an illustrating code and fiddle that shows how to successfully track mouse events on the canvas:

http://jsfiddle.net/m1erickson/WB7Zu/

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>

<script>
$(function(){

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");

    var canvasOffset=$("#canvas").offset();
    var offsetX=canvasOffset.left;
    var offsetY=canvasOffset.top;

    function handleMouseDown(e){
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);
      $("#downlog").html("Down: "+ mouseX + " / " + mouseY);

      // Put your mousedown stuff here

    }

    function handleMouseUp(e){
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);
      $("#uplog").html("Up: "+ mouseX + " / " + mouseY);

      // Put your mouseup stuff here
    }

    function handleMouseOut(e){
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);
      $("#outlog").html("Out: "+ mouseX + " / " + mouseY);

      // Put your mouseOut stuff here
    }

    function handleMouseMove(e){
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);
      $("#movelog").html("Move: "+ mouseX + " / " + mouseY);

      // Put your mousemove stuff here

    }

    $("#canvas").mousedown(function(e){handleMouseDown(e);});
    $("#canvas").mousemove(function(e){handleMouseMove(e);});
    $("#canvas").mouseup(function(e){handleMouseUp(e);});
    $("#canvas").mouseout(function(e){handleMouseOut(e);});

}); // end $(function(){});
</script>

</head>

<body>
    <p>Move, press and release the mouse</p>
    <p id="downlog">Down</p>
    <p id="movelog">Move</p>
    <p id="uplog">Up</p>
    <p id="outlog">Out</p>
    <canvas id="canvas" width=300 height=300></canvas>

</body>
</html>

Fixing the order of facets in ggplot

There are a couple of good solutions here.

Similar to the answer from Harpal, but within the facet, so doesn't require any change to underlying data or pre-plotting manipulation:

# Change this code:
facet_grid(.~size) + 
# To this code:
facet_grid(~factor(size, levels=c('50%','100%','150%','200%')))

This is flexible, and can be implemented for any variable as you change what element is faceted, no underlying change in the data required.

HTML span align center not working?

On top of all the other explanations, I believe you're using equal "=" sign, instead of colon ":":

<span style="border:1px solid red;text-align=center">

It should be:

<span style="border:1px solid red;text-align:center">

How can I create a carriage return in my C# string

string myHTML = "some words " + Environment.NewLine + "more words");

Difference between / and /* in servlet mapping url pattern

I'd like to supplement BalusC's answer with the mapping rules and an example.

Mapping rules from Servlet 2.5 specification:

  1. Map exact URL
  2. Map wildcard paths
  3. Map extensions
  4. Map to the default servlet

In our example, there're three servlets. / is the default servlet installed by us. Tomcat installs two servlets to serve jsp and jspx. So to map http://host:port/context/hello

  1. No exact URL servlets installed, next.
  2. No wildcard paths servlets installed, next.
  3. Doesn't match any extensions, next.
  4. Map to the default servlet, return.

To map http://host:port/context/hello.jsp

  1. No exact URL servlets installed, next.
  2. No wildcard paths servlets installed, next.
  3. Found extension servlet, return.

Google MAP API Uncaught TypeError: Cannot read property 'offsetWidth' of null

I had the same issue but the problem was that zoom was not defined within the options object given to Google Maps.

What is difference between XML Schema and DTD?

As many people have mentioned before, XML Schema utilize an XML-based syntax and DTDs have a unique syntax. DTD doesn't support datatypes, which does matter.

Lets see a very simple example in which university has multiple students and each student has two elements "name" and "year". Please note that I have uses "// --> " in my code just for comments.

enter image description here

Now I will write this example both in DTD and in XSD.

DTD

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE university[              // --> university as root element 
<!ELEMENT university (student*)>   // --> university has  * = Multiple students
<!ELEMENT student (name,year)>     // --> Student has elements name and year
<!ELEMENT name (#PCDATA)>          // --> name as Parsed character data
<!ELEMENT year (#PCDATA)>          // --> year as Parsed character data
]>

<university>
    <student>
        <name>
            John Niel             //---> I can also use an Integer,not good
        </name>
        <year>
            2000                 //---> I can also use a string,not good
        </year>
    </student>
</university>

XML Schema Definition (XSD)

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">

<xsd:complexType name ="uniType">                    //--> complex datatype uniType
 <xsd:sequence>
  <xsd:element ref="student" maxOccurs="unbounded"/> //--> has unbounded no.of students
 </xsd:sequence>
</xsd:complexType>

<xsd:complexType name="stuType">                     //--> complex datatype stuType
 <xsd:sequence>
  <xsd:element ref="name"/>                          //--> has element name
  <xsd:element ref="year"/>                          //--> has element year
 </xsd:sequence>
</xsd:complexType>

<xsd:element name="university" type="uniType"/>       //--> university of type UniType 
<xsd:element name="student" type="stuType"/>          //--> student of type stuType
<xsd:element name="name" type="xsd:string"/>          //--> name of datatype string
<xsd:element name="year" type="xsd:integer"/>         //--> year of datatype integer
</xsd:schema>



<?xml version="1.0" encoding="UTF-8"?>
<university>
    <student>
        <name>
            John Niel          
        </name>
        <year>
            2000                      //--> only an Integer value is allowed
        </year>
    </student>
</university>

Why is my JavaScript function sometimes "not defined"?

Verify your code with JSLint. It will usually find a ton of small errors, so the warning "JSLint may hurt your feelings" is pretty spot on. =)

Checkboxes in web pages – how to make them bigger?

Here's a trick that works in most recent browsers (IE9+) as a CSS only solution that can be improved with javascript to support IE8 and below.

<div>
  <input type="checkbox" id="checkboxID" name="checkboxName" value="whatever" />
  <label for="checkboxID"> </label>
</div>

Style the label with what you want the checkbox to look like

#checkboxID
{
  position: absolute fixed;
  margin-right: 2000px;
  right: 100%;
}
#checkboxID + label
{
  /* unchecked state */
}
#checkboxID:checked + label
{
  /* checked state */
}

For javascript, you'll be able to add classes to the label to show the state. Also, it would be wise to use the following function:

$('label[for]').live('click', function(e){
  $('#' + $(this).attr('for') ).click();
  return false;
});

EDIT to modify #checkboxID styles

Pandas : compute mean or std (standard deviation) over entire dataframe

You could convert the dataframe to be a single column with stack (this changes the shape from 5x3 to 15x1) and then take the standard deviation:

df.stack().std()         # pandas default degrees of freedom is one

Alternatively, you can use values to convert from a pandas dataframe to a numpy array before taking the standard deviation:

df.values.std(ddof=1)    # numpy default degrees of freedom is zero

Unlike pandas, numpy will give the standard deviation of the entire array by default, so there is no need to reshape before taking the standard deviation.

A couple of additional notes:

  • The numpy approach here is a bit faster than the pandas one, which is generally true when you have the option to accomplish the same thing with either numpy or pandas. The speed difference will depend on the size of your data, but numpy was roughly 10x faster when I tested a few different sized dataframes on my laptop (numpy version 1.15.4 and pandas version 0.23.4).

  • The numpy and pandas approaches here will not give exactly the same answers, but will be extremely close (identical at several digits of precision). The discrepancy is due to slight differences in implementation behind the scenes that affect how the floating point values get rounded.

Can't install nuget package because of "Failed to initialize the PowerShell host"

Set the execution policy to Bypass instead of Unrestricted or RemoteSigned; this tutorial gives fuller instructions. Also, if you are having trouble using PowerShell to change the policy then the author shows you how to change it in Regedit.

How to add lines to end of file on Linux

The easiest way is to redirect the output of the echo by >>:

echo 'VNCSERVERS="1:root"' >> /etc/sysconfig/configfile
echo 'VNCSERVERARGS[1]="-geometry 1600x1200"' >> /etc/sysconfig/configfile

The name 'model' does not exist in current context in MVC3

While you declare the model at the top of the view using code like this:

@model MyModel

you need to capitalise your references to it below, for example:

@Html.Encode(Model.MyDisplayValue)

I believe a missing web.config in the Views folder would be the major cause of this, but if that is fixed and the problem still persists, check that you are using Model, not model to refer to it in the source.

Runnable with a parameter?

I use the following class which implements the Runnable interface. With this class you can easily create new threads with arguments

public abstract class RunnableArg implements Runnable {

    Object[] m_args;

    public RunnableArg() {
    }

    public void run(Object... args) {
        setArgs(args);
        run();
    }

    public void setArgs(Object... args) {
        m_args = args;
    }

    public int getArgCount() {
        return m_args == null ? 0 : m_args.length;
    }

    public Object[] getArgs() {
        return m_args;
    }
}

How do I check out a specific version of a submodule using 'git submodule'?

Step 1: Add the submodule

   git submodule add git://some_repository.git some_repository

Step 2: Fix the submodule to a particular commit

By default the new submodule will be tracking HEAD of the master branch, but it will NOT be updated as you update your primary repository. In order to change the submodule to track a particular commit or different branch, change directory to the submodule folder and switch branches just like you would in a normal repository.

   git checkout -b some_branch origin/some_branch

Now the submodule is fixed on the development branch instead of HEAD of master.

From Two Guys Arguing — Tie Git Submodules to a Particular Commit or Branch .

jQuery Validate - Enable validation for hidden fields

The validation was working for me on form submission, but it wasn't doing the reactive event driven validation on input to the chosen select lists.

To fix this I added the following to manually trigger the jquery validation event that gets added by the library:

$(".chosen-select").each(function() {
  $(this).chosen().on("change", function() {
    $(this).parents(".form-group").find("select.form-control").trigger("focusout.validate");
  });
});

jquery.validate will now add the .valid class to the underlying select list.

Caveat: This does require a consistent html pattern for your form inputs. In my case, each input filed is wrapped in a div.form-group, and each input has .form-control.

Add a user control to a wpf window

You need to add a reference inside the window tag. Something like:

xmlns:controls="clr-namespace:YourCustomNamespace.Controls;assembly=YourAssemblyName"

(When you add xmlns:controls=" intellisense should kick in to make this bit easier)

Then you can add the control with:

<controls:CustomControlClassName ..... />

How to git clone a specific tag

git clone -b 13.1rc1-Gotham  --depth 1  https://github.com/xbmc/xbmc.git
Cloning into 'xbmc'...
remote: Counting objects: 17977, done.
remote: Compressing objects: 100% (13473/13473), done.
Receiving objects:  36% (6554/17977), 19.21 MiB | 469 KiB/s    

Will be faster than :

git clone https://github.com/xbmc/xbmc.git
Cloning into 'xbmc'...
remote: Reusing existing pack: 281705, done.
remote: Counting objects: 533, done.
remote: Compressing objects: 100% (177/177), done.
Receiving objects:  14% (40643/282238), 55.46 MiB | 578 KiB/s

Or

git clone -b 13.1rc1-Gotham  https://github.com/xbmc/xbmc.git
Cloning into 'xbmc'...
remote: Reusing existing pack: 281705, done.
remote: Counting objects: 533, done.
remote: Compressing objects: 100% (177/177), done.
Receiving objects:  12% (34441/282238), 20.25 MiB | 461 KiB/s

Please initialize the log4j system properly. While running web service

You can configure log4j.properties like above answers, or use org.apache.log4j.BasicConfigurator

public class FooImpl implements Foo {

    private static final Logger LOGGER = Logger.getLogger(FooBar.class);

    public Object createObject() {
        BasicConfigurator.configure();
        LOGGER.info("something");
        return new Object();
    }
}

So under the table, configure do:

  configure() {
    Logger root = Logger.getRootLogger();
    root.addAppender(new ConsoleAppender(
           new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN)));
  }

COPYing a file in a Dockerfile, no such file or directory?

It is possibly caused by you are referring file1/file2/file3 as an absolute path which is not in build context, Docker only search the path in build context.

E.g. if you use COPY /home/yourname/file1, Docker build interprets it as ${docker build working directory}/home/yourname/file1, if no file with same name here, no file or directory error is thrown.

Refer to One of the docker issue

How to parse JSON response from Alamofire API in Swift?

like above mention you can use SwiftyJSON library and get your values like i have done below

Alamofire.request(.POST, "MY URL", parameters:parameters, encoding: .JSON) .responseJSON
{
    (request, response, data, error) in

var json = JSON(data: data!)

       println(json)   
       println(json["productList"][1])                 

}

my json product list return from script

{ "productList" :[

{"productName" : "PIZZA","id" : "1","productRate" : "120.00","productDescription" : "PIZZA AT 120Rs","productImage" : "uploads\/pizza.jpeg"},

{"productName" : "BURGER","id" : "2","productRate" : "100.00","productDescription" : "BURGER AT Rs 100","productImage" : "uploads/Burgers.jpg"}    
  ]
}

output :

{
  "productName" : "BURGER",
  "id" : "2",
  "productRate" : "100.00",
  "productDescription" : "BURGER AT Rs 100",
  "productImage" : "uploads/Burgers.jpg"
}

Awaiting multiple Tasks with different results

var dn = await Task.WhenAll<dynamic>(FeedCat(),SellHouse(),BuyCar());

if you want to access Cat, you do this:

var ct = (Cat)dn[0];

This is very simple to do and very useful to use, there is no need to go after a complex solution.

How can I pass parameters to a partial view in mvc 4

Here is an extension method that will convert an object to a ViewDataDictionary.

public static ViewDataDictionary ToViewDataDictionary(this object values)
{
    var dictionary = new ViewDataDictionary();
    foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(values))
    {
        dictionary.Add(property.Name, property.GetValue(values));
    }
    return dictionary;
}

You can then use it in your view like so:

@Html.Partial("_MyPartial", new
{
    Property1 = "Value1",
    Property2 = "Value2"
}.ToViewDataDictionary())

Which is much nicer than the new ViewDataDictionary { { "Property1", "Value1" } , { "Property2", "Value2" }} syntax.

Then in your partial view, you can use ViewBag to access the properties from a dynamic object rather than indexed properties, e.g.

<p>@ViewBag.Property1</p>
<p>@ViewBag.Property2</p>

When to use extern in C++

It is useful when you share a variable between a few modules. You define it in one module, and use extern in the others.

For example:

in file1.cpp:

int global_int = 1;

in file2.cpp:

extern int global_int;
//in some function
cout << "global_int = " << global_int;

Most efficient way to get table row count

if you directly get get max number by writing select query then there may chance that your query will give wrong value. e.g. if your table has 5 records so your increment id will be 6 and if I delete record no 5 the your table has 4 records with max id is 4 in this case you will get 5 as next increment id. insted to that you can get info from mysql defination itself. by writing following code in php

<?
$tablename      = "tablename";
$next_increment     = 0;
$qShowStatus        = "SHOW TABLE STATUS LIKE '$tablename'";
$qShowStatusResult  = mysql_query($qShowStatus) or die ( "Query failed: " . mysql_error() . "<br/>" . $qShowStatus );

$row = mysql_fetch_assoc($qShowStatusResult);
$next_increment = $row['Auto_increment'];

echo "next increment number: [$next_increment]";
?>

Cannot access mongodb through browser - It looks like you are trying to access MongoDB over HTTP on the native driver port

MongoDB has a simple web based administrative port at 28017 by default.

There is no HTTP access at the default port of 27017 (which is what the error message is trying to suggest). The default port is used for native driver access, not HTTP traffic.

To access MongoDB, you'll need to use a driver like the MongoDB native driver for NodeJS. You won't "POST" to MongoDB directly (but you might create a RESTful API using express which uses the native drivers). Instead, you'll use a wrapper library that makes accessing MongoDB convenient. You might also consider using Mongoose (which uses the native driver) which adds an ORM-like model for MongoDB in NodeJS.

If you can't get to the web interface, it may be disabled. Normally, I wouldn't expect that you'd need it for doing development unless you're checking logs and such.

How to make Java honor the DNS Caching Timeout?

So I decided to look at the java source code because I found official docs a bit confusing. And what I found (for OpenJDK 11) mostly aligns with what others have written. What is important is the order of evaluation of properties.

InetAddressCachePolicy.java (I'm omitting some boilerplate for readability):


String tmpString = Security.getProperty("networkaddress.cache.ttl");
if (tmpString != null) {
   tmp = Integer.valueOf(tmpString);
   return;
}
...
String tmpString = System.getProperty("sun.net.inetaddr.ttl");
if (tmpString != null) {
   tmp = Integer.valueOf(tmpString);
   return;
}
...
if (tmp != null) {
  cachePolicy = tmp < 0 ? FOREVER : tmp;
  propertySet = true;
} else {
  /* No properties defined for positive caching. If there is no
  * security manager then use the default positive cache value.
  */
  if (System.getSecurityManager() == null) {
    cachePolicy = 30;
  }
}

You can clearly see that the security property is evaluated first, system property second and if any of them is set cachePolicy value is set to that number or -1 (FOREVER) if they hold a value that is bellow -1. If nothing is set it defaults to 30 seconds. As it turns out for OpenJDK that is almost always the case because by default java.security does not set that value, only a negative one.

#networkaddress.cache.ttl=-1 <- this line is commented out
networkaddress.cache.negative.ttl=10

BTW if the networkaddress.cache.negative.ttl is not set (removed from the file) the default inside the java class is 0. Documentation is wrong in this regard. This is what tripped me over.

How to get form input array into PHP array

However, VolkerK's solution is the best to avoid miss couple between email and username. So you have to generate HTML code with PHP like this:

<? foreach ($i = 0; $i < $total_data; $i++) : ?>
    <input type="text" name="name[<?= $i ?>]" />
    <input type="text" name="email[<?= $i ?>]" />
<? endforeach; ?>

Change $total_data to suit your needs. To show it, just like this:

$output = array_map(create_function('$name, $email', 'return "The name is $name and email is $email, thank you.";'), $_POST['name'], $_POST['email']);
echo implode('<br>', $output);

Assuming the data was sent using POST method.

How do I turn off PHP Notices?

You are looking for:

php -d error_reporting="E_ERROR | E_WARNING | E_PARSE"

grid controls for ASP.NET MVC?

Try: http://mvcjqgridcontrol.codeplex.com/ It's basically a MVC-compliant jQuery Grid wrapper with full .Net support

pass JSON to HTTP POST Request

you can pass the json object as the body(third argument) of the fetch request.

What is the difference between smoke testing and sanity testing?

Smoke tests are tests which aim is to check if everything was build correctly. I mean here integration, connections. So you check from technically point of view if you can make wider tests. You have to execute some test cases and check if the results are positive.

Sanity tests in general have the same aim - check if we can make further test. But in sanity test you focus on business value so you execute some test cases but you check the logic.

In general people say smoke tests for both above because they are executed in the same time (sanity after smoke tests) and their aim is similar.

Sizing elements to percentage of screen width/height

if you are using GridView you can use something like Ian Hickson's solution.

crossAxisCount: MediaQuery.of(context).size.width <= 400.0 ? 3 : MediaQuery.of(context).size.width >= 1000.0 ? 5 : 4

How do I undo the most recent local commits in Git?

$ git commit -m 'Initial commit'
$ git add forgotten_file
$ git commit --amend

It’s important to understand that when you’re amending your last commit, you’re not so much fixing it as replacing it entirely with a new, improved commit that pushes the old commit out of the way and puts the new commit in its place. Effectively, it’s as if the previous commit never happened, and it won’t show up in your repository history.

The obvious value to amending commits is to make minor improvements to your last commit, without cluttering your repository history with commit messages of the form, “Oops, forgot to add a file” or “Darn, fixing a typo in last commit”.

2.4 Git Basics - Undoing Things

How do I POST form data with UTF-8 encoding by using curl?

You CAN use UTF-8 in the POST request, all you need is to specify the charset in your request.

You should use this request:

curl -X POST -H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" --data-ascii "content=derinhält&date=asdf" http://myserverurl.com/api/v1/somemethod

SSH Port forwarding in a ~/.ssh/config file?

You can use the LocalForward directive in your host yam section of ~/.ssh/config:

LocalForward 5901 computer.myHost.edu:5901

Can you test google analytics on a localhost address?

This question remains valid today, however the technology has changed. The old Urchin tracker is deprecated and obsolete. The new asynchronous Google Analytics tracking code uses slightly different code to achieve the same results.

Google Analytics Classic - Asynchronous Syntax - ga.js

The current syntax for setting the tracking domain to none on google analytics looks like this:

_gaq.push(['_setDomainName', 'none']);

Google analytics will then fire off the _utm.gif tracker request on localhost. You can verify this by opening the developer tools in your favorite browser and watching the network requests during page load. If it is working you will see a request for _utm.gif in the network requests list.

Updated 2013 for Universal Analytics - analytics.js

Google released a new version of analytics called "Universal Analytics" (late 2012 or early 2013). As I write, this the program is still in BETA so the above code is still recommended for most users with existing installations of Google Analytics.

However, for new developments using the new analytics.js code, the Google Analytics, Advanced Configuration - Web Tracking Documentation shows that we can test Universal Analytics on localhost with this new code:

ga('create', 'UA-XXXX-Y', {
  'cookieDomain': 'none'
});

Check out the linked documentation for more details on advanced configuration of Universal Analytics.

Update 2019

Both Global Site Tag - gtag.js and Universal Analytics - analytics.js will detect localhost automatically. You do not need to make any change to the configuration.

If gtag.js detects that you're running a server locally (e.g. localhost), it automatically sets the cookie_domain to 'none'.

- developers.google.com

nodeJs callbacks simple example

A callback is a function passed as an parameter to a Higher Order Function (wikipedia). A simple implementation of a callback would be:

const func = callback => callback('Hello World!');

To call the function, simple pass another function as argument to the function defined.

func(string => console.log(string));

How can I uninstall npm modules in Node.js?

In case you are on Windows, run CMD as administrator and type:

npm -g uninstall <package name>

Why does an image captured using camera intent gets rotated on some devices on Android?

This maybe goes without saying but always remember that you can handle some of these image handling issues on your server. I used responses like the ones contained in this thread to handle the immediate display of the image. However my application requires images to be stored on the server (this is probably a common requirement if you want the image to persist as users switch phones).

The solutions contained in many of the threads concerning this topic don't discuss the lack of persistence of the EXIF data which doesn't survive the Bitmap's image compression, meaning you'll need to rotate the image each time your server loads it. Alternatively, you can send the EXIF orientation data to your server, and then rotate the image there if needed.

It was easier for me to create a permanent solution on a server because I didn't have to worry about Android's clandestine file paths.

Pure Javascript listen to input value change

instead of id use title to identify your element and write the code as below.

$(document).ready(()=>{

 $("input[title='MyObject']").change(()=>{
        console.log("Field has been changed...")
    })  
});

Logout button php

When you want to destroy a session completely, you need to do more then just

session_destroy();

First, you should unset any session variables. Then you should destroy the session followed by closing the write of the session. This can be done by the following:

<?php
session_start();
unset($_SESSION);
session_destroy();
session_write_close();
header('Location: /');
die;
?>

The reason you want have a separate script for a logout is so that you do not accidently execute it on the page. So make a link to your logout script, then the header will redirect to the root of your site.

Edit:

You need to remove the () from your exit code near the top of your script. it should just be

exit;

Android: how to refresh ListView contents?

You don't have to create a new adapter to update your ListView's contents. Simply store your Adapter in a field and update your list with the following code:

mAdapter.setList(yourNewList);
mAdapter.notifyDataSetChanged();

To clarify that, your Activity should look like that:

private YourAdapter mAdapter;

protected void onCreate(...) {

    ...

    mAdapter = new YourAdapter(this);
    setListAdapter(mAdapter);

    updateData();
}

private void updateData() {
    List<Data> newData = getYourNewData();
    mAdapter.setList(yourNewList);
    mAdapter.notifyDataSetChanged();
}

How do you strip a character out of a column in SQL Server?

This is done using the REPLACE function

To strip out "somestring" from "SomeColumn" in "SomeTable" in the SELECT query:

SELECT REPLACE([SomeColumn],'somestring','') AS [SomeColumn]  FROM [SomeTable]

To update the table and strip out "somestring" from "SomeColumn" in "SomeTable"

UPDATE [SomeTable] SET [SomeColumn] = REPLACE([SomeColumn], 'somestring', '')

Xcode: failed to get the task for process

Just had the same problem - app was being installed OK, but won't run from Xcode with the "process launch failed: failed to get the task for process".

Turns out my development certificate expired during the night. Regenerating the certificate and the provisioning profiles solved the problem.

How to compare variables to undefined, if I don’t know whether they exist?

if (document.getElementById('theElement')) // do whatever after this

For undefined things that throw errors, test the property name of the parent object instead of just the variable name - so instead of:

if (blah) ...

do:

if (window.blah) ...

Escaping single quote in PHP when inserting into MySQL

You should just pass the variable (or data) inside "mysql_real_escape_string(trim($val))"

where $val is the data which is troubling you.

How to convert byte[] to InputStream?

Should be easy to find in the javadocs...

byte[] byteArr = new byte[] { 0xC, 0xA, 0xF, 0xE };
InputStream is = new ByteArrayInputStream(byteArr);

How to config routeProvider and locationProvider in angularJS?

Following is how one can configure $locationProvider using requireBase=false flag to avoid setting base href <head><base href="/"></head>:

var app = angular.module("hwapp", ['ngRoute']);

app.config(function($locationProvider){
    $locationProvider.html5Mode({
        enabled: true,
        requireBase: false
    }) 
});

remove first element from array and return the array minus the first element

This should remove the first element, and then you can return the remaining:

_x000D_
_x000D_
var myarray = ["item 1", "item 2", "item 3", "item 4"];_x000D_
    _x000D_
myarray.shift();_x000D_
alert(myarray);
_x000D_
_x000D_
_x000D_

As others have suggested, you could also use slice(1);

_x000D_
_x000D_
var myarray = ["item 1", "item 2", "item 3", "item 4"];_x000D_
  _x000D_
alert(myarray.slice(1));
_x000D_
_x000D_
_x000D_

How can I display my windows user name in excel spread sheet using macros?

Range("A1").value = Environ("Username")

This is better than Application.Username, which doesn't always supply the Windows username. Thanks to Kyle for pointing this out.

  • Application Username is the name of the User set in Excel > Tools > Options
  • Environ("Username") is the name you registered for Windows; see Control Panel >System

What's the best way to parse command line arguments?

argparse is the way to go. Here is a short summary of how to use it:

1) Initialize

import argparse

# Instantiate the parser
parser = argparse.ArgumentParser(description='Optional app description')

2) Add Arguments

# Required positional argument
parser.add_argument('pos_arg', type=int,
                    help='A required integer positional argument')

# Optional positional argument
parser.add_argument('opt_pos_arg', type=int, nargs='?',
                    help='An optional integer positional argument')

# Optional argument
parser.add_argument('--opt_arg', type=int,
                    help='An optional integer argument')

# Switch
parser.add_argument('--switch', action='store_true',
                    help='A boolean switch')

3) Parse

args = parser.parse_args()

4) Access

print("Argument values:")
print(args.pos_arg)
print(args.opt_pos_arg)
print(args.opt_arg)
print(args.switch)

5) Check Values

if args.pos_arg > 10:
    parser.error("pos_arg cannot be larger than 10")

Usage

Correct use:

$ ./app 1 2 --opt_arg 3 --switch

Argument values:
1
2
3
True

Incorrect arguments:

$ ./app foo 2 --opt_arg 3 --switch
usage: convert [-h] [--opt_arg OPT_ARG] [--switch] pos_arg [opt_pos_arg]
app: error: argument pos_arg: invalid int value: 'foo'

$ ./app 11 2 --opt_arg 3
Argument values:
11
2
3
False
usage: app [-h] [--opt_arg OPT_ARG] [--switch] pos_arg [opt_pos_arg]
convert: error: pos_arg cannot be larger than 10

Full help:

$ ./app -h

usage: app [-h] [--opt_arg OPT_ARG] [--switch] pos_arg [opt_pos_arg]

Optional app description

positional arguments:
  pos_arg            A required integer positional argument
  opt_pos_arg        An optional integer positional argument

optional arguments:
  -h, --help         show this help message and exit
  --opt_arg OPT_ARG  An optional integer argument
  --switch           A boolean switch

How to add a classname/id to React-Bootstrap Component?

If you look at the code for the component you can see that it uses the className prop passed to it to combine with the row class to get the resulting set of classes (<Row className="aaa bbb"... works).Also, if you provide the id prop like <Row id="444" ... it will actually set the id attribute for the element.

How can I autoformat/indent C code in vim?

Their is a tool called indent. You can download it with apt-get install indent, then run indent my_program.c.

How do I use a char as the case in a switch-case?

charAt gets a character from a string, and you can switch on them since char is an integer type.

So to switch on the first char in the String hello,

switch (hello.charAt(0)) {
  case 'a': ... break;
}

You should be aware though that Java chars do not correspond one-to-one with code-points. See codePointAt for a way to reliably get a single Unicode codepoints.

How do I initialize a byte array in Java?

Using a function converting an hexa string to byte[], you could do

byte[] CDRIVES = hexStringToByteArray("e04fd020ea3a6910a2d808002b30309d");

I'd suggest you use the function defined by Dave L in Convert a string representation of a hex dump to a byte array using Java?

I insert it here for maximum readability :

public static byte[] hexStringToByteArray(String s) {
    int len = s.length();
    byte[] data = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                             + Character.digit(s.charAt(i+1), 16));
    }
    return data;
}

If you let CDRIVES static and final, the performance drop is irrelevant.

Make Https call using HttpClient

Simply specify HTTPS in the URI.

new Uri("https://foobar.com/");

Foobar.com will need to have a trusted SSL cert or your calls will fail with untrusted error.

EDIT Answer: ClientCertificates with HttpClient

WebRequestHandler handler = new WebRequestHandler();
X509Certificate2 certificate = GetMyX509Certificate();
handler.ClientCertificates.Add(certificate);
HttpClient client = new HttpClient(handler);

EDIT Answer2: If the server you are connecting to has disabled SSL, TLS 1.0, and 1.1 and you are still running .NET framework 4.5(or below) you need to make a choice

  1. Upgrade to .Net 4.6+ (Supports TLS 1.2 by default)
  2. Add registry changes to instruct 4.5 to connect over TLS1.2 ( See: salesforce writeup for compat and keys to change OR checkout IISCrypto see Ronald Ramos answer comments)
  3. Add application code to manually configure .NET to connect over TLS1.2 (see Ronald Ramos answer)

How do I find the length/number of items present for an array?

I'm not sure that i know exactly what you mean.

But to get the length of an initialized array,

doesn't strlen(string) work ??

Delete all items from a c++ std::vector

If you keep pointers in container and don't want to bother with manually destroying of them, then use boost shared_ptr. Here is sample for std::vector, but you can use it for any other STL container (set, map, queue, ...)

#include <iostream>
#include <vector>
#include <boost/shared_ptr.hpp>

struct foo
{
    foo( const int i_x ) : d_x( i_x )
    {
        std::cout << "foo::foo " << d_x << std::endl;
    }

    ~foo()
    {
        std::cout << "foo::~foo " << d_x << std::endl;
    }

    int d_x;
};

typedef boost::shared_ptr< foo > smart_foo_t;

int main()
{
    std::vector< smart_foo_t > foos;
    for ( int i = 0; i < 10; ++i )
    {
        smart_foo_t f( new foo( i ) );
        foos.push_back( f );
    }

    foos.clear();

    return 0;
}

Formatting html email for Outlook

You should definitely check out the MSDN on what Outlook will support in regards to css and html. The link is here: http://msdn.microsoft.com/en-us/library/aa338201(v=office.12).aspx. If you do not have at least office 2007 you really need to upgrade as there are major differences between 2007 and previous editions. Also try saving the resulting email to file and examine it with firefox you will see what is being changed by outlook and possibly have a more specific question to ask. You can use Word to view the email as a sort of preview as well (but you won't get info on what styles are/are not being applied.

Ant: How to execute a command for each file in directory?

Short Answer

Use <foreach> with a nested <FileSet>

Foreach requires ant-contrib.

Updated Example for recent ant-contrib:

<target name="foo">
  <foreach target="bar" param="theFile">
    <fileset dir="${server.src}" casesensitive="yes">
      <include name="**/*.java"/>
      <exclude name="**/*Test*"/>
    </fileset>
  </foreach>
</target>

<target name="bar">
  <echo message="${theFile}"/>
</target>

This will antcall the target "bar" with the ${theFile} resulting in the current file.

"Invalid signature file" when attempting to run a .jar

I had a similar problem. The reason was that I was compiling using a JDK with a different JRE than the default one in my Windows box.

Using the correct java.exe solved my problem.

default web page width - 1024px or 980px?

even there is no right or wrong answer for this question , but I personally prefer 960px width . since all modern monitors support at least 1024 × 768 pixel resolution. 960 is divisible by 2, 3, 4, 5, 6, 8, 10, 12, 15, 16, 20, 24, 30, 32, 40, 48, 60, 64, 80, 96, 120, 160, 192, 240, 320 and 480. This makes it a highly flexible base number to work with.

see this article that shows most popular screens resolutions 2013-2014 in US and UK : http://www.hobo-web.co.uk/best-screen-size/

Single vs Double quotes (' vs ")

I'm newbie here but I use single quote mark only when I use double quote mark inside the first one. If I'm not clear I show You example:

<p align="center" title='One quote mark at the beginning so now I can
"cite".'> ... </p>

I hope I helped.

Splitting on last delimiter in Python string?

Use .rsplit() or .rpartition() instead:

s.rsplit(',', 1)
s.rpartition(',')

str.rsplit() lets you specify how many times to split, while str.rpartition() only splits once but always returns a fixed number of elements (prefix, delimiter & postfix) and is faster for the single split case.

Demo:

>>> s = "a,b,c,d"
>>> s.rsplit(',', 1)
['a,b,c', 'd']
>>> s.rsplit(',', 2)
['a,b', 'c', 'd']
>>> s.rpartition(',')
('a,b,c', ',', 'd')

Both methods start splitting from the right-hand-side of the string; by giving str.rsplit() a maximum as the second argument, you get to split just the right-hand-most occurrences.

Return index of highest value in an array

Function taken from http://www.php.net/manual/en/function.max.php

function max_key($array) {
    foreach ($array as $key => $val) {
        if ($val == max($array)) return $key; 
    }
}

$arr = array (
    '11' => 14,
    '10' => 9,
    '12' => 7,
    '13' => 7,
    '14' => 4,
    '15' => 6
);

die(var_dump(max_key($arr)));

Works like a charm

Comparing arrays for equality in C++

if (iar1 == iar2)

Here iar1 and iar2 are decaying to pointers to the first elements of the respective arrays. Since they are two distinct arrays, the pointer values are, of course, different and your comparison tests not equal.

To do an element-wise comparison, you must either write a loop; or use std::array instead

std::array<int, 5> iar1 {1,2,3,4,5};
std::array<int, 5> iar2 {1,2,3,4,5};

if( iar1 == iar2 ) {
  // arrays contents are the same

} else {
  // not the same

}

Access-Control-Allow-Origin and Angular.js $http

@Swapnil Niwane

I was able to solve this issue by calling an ajax request and formatting the data to 'jsonp'.

$.ajax({
          method: 'GET',
          url: url,
          defaultHeaders: {
              'Content-Type': 'application/json',
              "Access-Control-Allow-Origin": "*",
              'Accept': 'application/json'
           },

          dataType: 'jsonp',

          success: function (response) {
            console.log("success ");
            console.log(response);
          },
          error: function (xhr) {
            console.log("error ");
            console.log(xhr);
          }
});

How to resize a VirtualBox vmdk file

vmdk's :

  • Rather fixed size allocation (step 1,2).
  • Even after expansion, not readily available inside the vmdk's OS (step 3,4,5)

STEPS:

1) convert to ".vdi" first - VBoxManage clonehd v1.vmdk v1.vdi --format vdi

2) expand the size using command-line (Ref: tvial's blog for step by step info)

OR

expand from the Virtual Media Manager in VirtualBox.

[ NOW - INSIDE VM ]

3) Expand the size of drive, with new allocation (e.g. for Ubuntu running on virtual-machine : use GParted) enter image description here enter image description here

4) Extend the filesystem - lvextend -L +50G <file-system-identifier>

ILLUSTRATION:

$ lsblk
NAME                       MAJ:MIN RM   SIZE RO TYPE MOUNTPOINT
...
sda                          8:0    0   200G  0 disk 
+-sda1                       8:1    0   200G  0 part 
  +-myfs-vg-cloud          253:0    0    99G  0 lvm  /
  +-myfs-vg-swap-1         253:1    0   980M  0 lvm  [SWAP]


$ lvextend -L +100G /dev/mapper/myfs-vg-cloud

$ lsblk
NAME                       MAJ:MIN RM   SIZE RO TYPE MOUNTPOINT
...
sda                          8:0    0   200G  0 disk 
+-sda1                       8:1    0   200G  0 part 
  +-myfs-vg-cloud          253:0    0   199G  0 lvm  /
  +-myfs-vg-swap-1         253:1    0   980M  0 lvm  [SWAP]

5) Extend the "/home" - resize2fs <file-system-identifier>

ILLUSTRATION:

$ df -h /home/
Filesystem                        Size  Used Avail Use% Mounted on
/dev/mapper/myfs-vg-cloud         97G   87G  6.0G  94%   /

$ resize2fs /dev/mapper/myfs-vg-cloud

$ df -h /home/
Filesystem                        Size  Used Avail Use% Mounted on
/dev/mapper/myfs-vg-cloud         196G   87G  101G  47%  /

Your system must now be ready to use, with extended allocations !!

What does it mean when MySQL is in the state "Sending data"?

This is quite a misleading status. It should be called "reading and filtering data".

This means that MySQL has some data stored on the disk (or in memory) which is yet to be read and sent over. It may be the table itself, an index, a temporary table, a sorted output etc.

If you have a 1M records table (without an index) of which you need only one record, MySQL will still output the status as "sending data" while scanning the table, despite the fact it has not sent anything yet.

how to call scalar function in sql server 2008

Your syntax is for table valued function which return a resultset and can be queried like a table. For scalar function do

 select  dbo.fun_functional_score('01091400003') as [er]

How to determine the IP address of a Solaris system

The following shell script gives a nice tabular result of interfaces and IP addresses (excluding the loopback interface) It has been tested on a Solaris box

/usr/sbin/ifconfig -a | awk '/flags/ {printf $1" "} /inet/ {print $2}' | grep -v lo

ce0: 10.106.106.108
ce0:1: 10.106.106.23
ce0:2: 10.106.106.96
ce1: 10.106.106.109

Linux error while loading shared libraries: cannot open shared object file: No such file or directory

Update
While what I write below is true as a general answer about shared libraries, I think the most frequent cause of these sorts of message is because you've installed a package, but not installed the "-dev" version of that package.


Well, it's not lying - there is no libpthread_rt.so.1 in that listing. You probably need to re-configure and re-build it so that it depends on the library you have, or install whatever provides libpthread_rt.so.1.

Generally, the numbers after the .so are version numbers, and you'll often find that they are symlinks to each other, so if you have version 1.1 of libfoo.so, you'll have a real file libfoo.so.1.0, and symlinks foo.so and foo.so.1 pointing to the libfoo.so.1.0. And if you install version 1.1 without removing the other one, you'll have a libfoo.so.1.1, and libfoo.so.1 and libfoo.so will now point to the new one, but any code that requires that exact version can use the libfoo.so.1.0 file. Code that just relies on the version 1 API, but doesn't care if it's 1.0 or 1.1 will specify libfoo.so.1. As orip pointed out in the comments, this is explained well at http://tldp.org/HOWTO/Program-Library-HOWTO/shared-libraries.html.

In your case, you might get away with symlinking libpthread_rt.so.1 to libpthread_rt.so. No guarantees that it won't break your code and eat your TV dinners, though.

How do I set environment variables from Java?

It turns out that the solution from @pushy/@anonymous/@Edward Campbell does not work on Android because Android is not really Java. Specifically, Android does not have java.lang.ProcessEnvironment at all. But it turns out to be easier in Android, you just need to do a JNI call to POSIX setenv():

In C/JNI:

JNIEXPORT jint JNICALL Java_com_example_posixtest_Posix_setenv
  (JNIEnv* env, jclass clazz, jstring key, jstring value, jboolean overwrite)
{
    char* k = (char *) (*env)->GetStringUTFChars(env, key, NULL);
    char* v = (char *) (*env)->GetStringUTFChars(env, value, NULL);
    int err = setenv(k, v, overwrite);
    (*env)->ReleaseStringUTFChars(env, key, k);
    (*env)->ReleaseStringUTFChars(env, value, v);
    return err;
}

And in Java:

public class Posix {

    public static native int setenv(String key, String value, boolean overwrite);

    private void runTest() {
        Posix.setenv("LD_LIBRARY_PATH", "foo", true);
    }
}

How to add Web API to an existing ASP.NET MVC 4 Web Application project?

As soon as you add a "WebApi Controller" under controllers folder, Visual Studio takes care of dependencies automatically;

Visual Studio has added the full set of dependencies for ASP.NET Web API 2 to project 'MyTestProject'.

The Global.asax.cs file in the project may require additional changes to enable ASP.NET Web API.

  1. Add the following namespace references:

    using System.Web.Http; using System.Web.Routing;

  2. If the code does not already define an Application_Start method, add the following method:

    protected void Application_Start() { }

  3. Add the following lines to the beginning of the Application_Start method:

    GlobalConfiguration.Configure(WebApiConfig.Register);

How to deep merge instead of shallow merge?

function isObject(obj) {
    return obj !== null && typeof obj === 'object';
}
const isArray = Array.isArray;

function isPlainObject(obj) {
    return isObject(obj) && (
        obj.constructor === Object  // obj = {}
        || obj.constructor === undefined // obj = Object.create(null)
    );
}

function mergeDeep(target, ...sources){
    if (!sources.length) return target;
    const source = sources.shift();

    if (isPlainObject(source) || isArray(source)) {
        for (const key in source) {
            if (isPlainObject(source[key]) || isArray(source[key])) {
                if (isPlainObject(source[key]) && !isPlainObject(target[key])) {
                    target[key] = {};
                }else if (isArray(source[key]) && !isArray(target[key])) {
                    target[key] = [];
                }
                mergeDeep(target[key], source[key]);
            } else if (source[key] !== undefined && source[key] !== '') {
                target[key] = source[key];
            }
        }
    }

    return mergeDeep(target, ...sources);
}

// test...
var source = {b:333};
var source2 = {c:32, arr: [33,11]}
var n = mergeDeep({a:33}, source, source2);
source2.arr[1] = 22;
console.log(n.arr); // out: [33, 11]

Convert DateTime to long and also the other way around

From long to DateTime: new DateTime(long ticks)

From DateTime to long: DateTime.Ticks

Issue with adding common code as git submodule: "already exists in the index"

You need to remove your submodule git repository (projectfolder in this case) first for git path.

rm -rf projectfolder

git rm -r projectfolder

and then add submodule

git submodule add <git_submodule_repository> projectfolder

How to find which version of TensorFlow is installed in my system?

I installed the Tensorflow 0.12rc from source, and the following command gives me the version info:

python -c 'import tensorflow as tf; print(tf.__version__)'  # for Python 2
python3 -c 'import tensorflow as tf; print(tf.__version__)'  # for Python 3

The following figure shows the output:

enter image description here

Cannot push to Git repository on Bitbucket

I found the solution that worked best for me was breaking up the push into smaller chunks.

and removing the large screenshot image files (10mb+) from the commits

Security wasnt an issue in the end more about limits of bin files

Aborting a shell script if any command returns a non-zero value

I am just throwing in another one for reference since there was an additional question to Mark Edgars input and here is an additional example and touches on the topic overall:

[[ `cmd` ]] && echo success_else_silence

Which is the same as cmd || exit errcode as someone showed.

For example, I want to make sure a partition is unmounted if mounted:

[[ `mount | grep /dev/sda1` ]] && umount /dev/sda1

Brew doctor says: "Warning: /usr/local/include isn't writable."

Take ownership of it and everything in it.

Mac OS High Sierra or newer: (ty to Kirk in the comments below)

$ sudo chown -R $(whoami) $(brew --prefix)/*

Previous versions of macos:

$ sudo chown -R $USER:admin /usr/local/include

Then do another

$ brew doctor

SQL LIKE condition to check for integer?

That will select (by a regex) every book which has a title starting with a number, is that what you want?

SELECT * FROM books WHERE title ~ '^[0-9]'

if you want integers which start with specific digits, you could use:

SELECT * FROM books WHERE CAST(price AS TEXT) LIKE '123%'

or use (if all your numbers have the same number of digits (a constraint would be useful then))

SELECT * FROM books WHERE price BETWEEN 123000 AND 123999;

How to add data validation to a cell using VBA

Use this one:

Dim ws As Worksheet
Dim range1 As Range, rng As Range
'change Sheet1 to suit
Set ws = ThisWorkbook.Worksheets("Sheet1")

Set range1 = ws.Range("A1:A5")
Set rng = ws.Range("B1")

With rng.Validation
    .Delete 'delete previous validation
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
        Formula1:="='" & ws.Name & "'!" & range1.Address
End With

Note that when you're using Dim range1, rng As range, only rng has type of Range, but range1 is Variant. That's why I'm using Dim range1 As Range, rng As Range.
About meaning of parameters you can read is MSDN, but in short:

  • Type:=xlValidateList means validation type, in that case you should select value from list
  • AlertStyle:=xlValidAlertStop specifies the icon used in message boxes displayed during validation. If user enters any value out of list, he/she would get error message.
  • in your original code, Operator:= xlBetween is odd. It can be used only if two formulas are provided for validation.
  • Formula1:="='" & ws.Name & "'!" & range1.Address for list data validation provides address of list with values (in format =Sheet!A1:A5)

What are Makefile.am and Makefile.in?

Simple example

Shamelessly adapted from: http://www.gnu.org/software/automake/manual/html_node/Creating-amhello.html and tested on Ubuntu 14.04 Automake 1.14.1.

Makefile.am

SUBDIRS = src
dist_doc_DATA = README.md

README.md

Some doc.

configure.ac

AC_INIT([automake_hello_world], [1.0], [[email protected]])
AM_INIT_AUTOMAKE([-Wall -Werror foreign])
AC_PROG_CC
AC_CONFIG_HEADERS([config.h])
AC_CONFIG_FILES([
 Makefile
 src/Makefile
])
AC_OUTPUT

src/Makefile.am

bin_PROGRAMS = autotools_hello_world
autotools_hello_world_SOURCES = main.c

src/main.c

#include <config.h>
#include <stdio.h>

int main (void) {
  puts ("Hello world from " PACKAGE_STRING);
  return 0;
}

Usage

autoreconf --install
mkdir build
cd build
../configure
make
sudo make install
autoconf_hello_world
sudo make uninstall

This outputs:

Hello world from automake_hello_world 1.0

Notes

  • autoreconf --install generates several template files which should be tracked by Git, including Makefile.in. It only needs to be run the first time.

  • make install installs:

    • the binary to /usr/local/bin
    • README.md to /usr/local/share/doc/automake_hello_world

On GitHub for you to try it out.

Graphical HTTP client for windows

I like rest-client a lot for the purposes you described. It's a Java application to test REST-based web services.

How does String substring work in Swift

I had the same initial reaction. I too was frustrated at how syntax and objects change so drastically in every major release.

However, I realized from experience how I always eventually suffer the consequences of trying to fight "change" like dealing with multi-byte characters which is inevitable if you're looking at a global audience.

So I decided to recognize and respect the efforts exerted by Apple engineers and do my part by understanding their mindset when they came up with this "horrific" approach.

Instead of creating extensions which is just a workaround to make your life easier (I'm not saying they're wrong or expensive), why not figure out how Strings are now designed to work.

For instance, I had this code which was working on Swift 2.2:

let rString = cString.substringToIndex(2)
let gString = (cString.substringFromIndex(2) as NSString).substringToIndex(2)
let bString = (cString.substringFromIndex(4) as NSString).substringToIndex(2)

and after giving up trying to get the same approach working e.g. using Substrings, I finally understood the concept of treating Strings as a bidirectional collection for which I ended up with this version of the same code:

let rString = String(cString.characters.prefix(2))
cString = String(cString.characters.dropFirst(2))
let gString = String(cString.characters.prefix(2))
cString = String(cString.characters.dropFirst(2))
let bString = String(cString.characters.prefix(2))

I hope this contributes...

libz.so.1: cannot open shared object file

I've downloaded these packages:

  • libc6-i386
  • lib32stdc++6
  • lib32gcc1
  • lib32ncurses5
  • zlib1g

I then unpacked them and added the directories to LD_LIBRARY_PATH in my ~/.bashrc. Just make sure to add proper dirs to the path.

How to set image name in Dockerfile?

Tagging of the image isn't supported inside the Dockerfile. This needs to be done in your build command. As a workaround, you can do the build with a docker-compose.yml that identifies the target image name and then run a docker-compose build. A sample docker-compose.yml would look like

version: '2'

services:
  man:
    build: .
    image: dude/man:v2

That said, there's a push against doing the build with compose since that doesn't work with swarm mode deploys. So you're back to running the command as you've given in your question:

docker build -t dude/man:v2 .

Personally, I tend to build with a small shell script in my folder (build.sh) which passes any args and includes the name of the image there to save typing. And for production, the build is handled by a ci/cd server that has the image name inside the pipeline script.

When should I write the keyword 'inline' for a function/method?

1) Nowadays, pretty much never. If it's a good idea to inline a function, the compiler will do it without your help.

2) Always. See #1.

(Edited to reflect that you broke your question into two questions...)