Programs & Examples On #Clr hosting

CLR hosting means enabling a native process to execute managed code by using .NET runtime library dll that actually executes the managed code. Such native process said to "host" CLR, .NET Common Language Runtime, then in the hosted runtime the native process can execute any CLR assemblies.

AngularJS - Building a dynamic table based on a json

<table class="table table-striped table-condensed table-hover">
    <thead>
    <tr>
        <th ng-repeat="header in headers | filter:headerFilter | orderBy:headerOrder" width="{{header.width}}">{{header.label}}</th>
    </tr>
    </thead>
    <tbody>
    <tr ng-repeat="user in users" ng-class-odd="'trOdd'" ng-class-even="'trEven'" ng-dblclick="rowDoubleClicked(user)">
        <td ng-repeat="(key,val) in user | orderBy:userOrder(key)">{{val}}</td>
    </tr>
    </tbody>
    <tfoot>

    </tfoot>
</table>

refer this https://gist.github.com/ebellinger/4399082

How to Add Incremental Numbers to a New Column Using Pandas

You can also simply set your pandas column as list of id values with length same as of dataframe.

df['New_ID'] = range(880, 880+len(df))

Reference docs : https://pandas.pydata.org/pandas-docs/stable/missing_data.html

Operation is not valid due to the current state of the object, when I select a dropdown list

This can happen if you call

 .SingleOrDefault() 

on an IEnumerable with 2 or more elements.

Adjust width and height of iframe to fit with content in it

This is how I would do it (tested in FF/Chrome):

<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
function autoResize(iframe) {
    $(iframe).height($(iframe).contents().find('html').height());
}
</script>

<iframe src="page.html" width="100%" height="100" marginheight="0" frameborder="0" onload="autoResize(this);"></iframe>

Remove Trailing Spaces and Update in Columns in SQL Server

Example:

SELECT TRIM('   Sample   ');

Result: 'Sample'

UPDATE TableName SET ColumnName = TRIM(ColumnName)

How to enable scrolling of content inside a modal?

Bootstrap will add or remove a css "modal-open" to the <body> tag when we open or close a modal. So if you open multiple modal and then close arbitrary one, the modal-open css will be removed from the body tag.

But the scroll effect depend on the attribute "overflow-y: auto;" defined in modal-open

JPA Query selecting only specific columns without using Criteria Query?

You can use something like this:

List<Object[]> list = em.createQuery("SELECT p.field1, p.field2 FROM Entity p").getResultList();

then you can iterate over it:

for (Object[] obj : list){
    System.out.println(obj[0]);
    System.out.println(obj[1]);
}

BUT if you have only one field in query, you get a list of the type not from Object[]

How can I get the name of an object in Python?

Based on what it looks like you're trying to do you could use this approach.

In your case, your functions would all live in the module foo. Then you could:

import foo

func_name = parse_commandline()
method_to_call = getattr(foo, func_name)
result = method_to_call()

Or more succinctly:

import foo

result = getattr(foo, parse_commandline())()

Convert seconds into days, hours, minutes and seconds

I am editing one of the code to work it well when negative value comes. floor() function is not giving the correct count when the value is negative. So we need to use abs() function before using it in the floor() function. $inputSeconds variable can be the difference between the current time stamp and the required date.

/** 
 * Convert number of seconds into hours, minutes and seconds 
 * and return an array containing those values 
 * 
 * @param integer $inputSeconds Number of seconds to parse 
 * @return array 
 */ 

function secondsToTime($inputSeconds) {

    $secondsInAMinute = 60;
    $secondsInAnHour  = 60 * $secondsInAMinute;
    $secondsInADay    = 24 * $secondsInAnHour;

    // extract days
    $days = abs($inputSeconds / $secondsInADay);
    $days = floor($days);

    // extract hours
    $hourSeconds = $inputSeconds % $secondsInADay;
    $hours = abs($hourSeconds / $secondsInAnHour);
    $hours = floor($hours);

    // extract minutes
    $minuteSeconds = $hourSeconds % $secondsInAnHour;
    $minutes = abs($minuteSeconds / $secondsInAMinute);
    $minutes = floor($minutes);

    // extract the remaining seconds
    $remainingSeconds = $minuteSeconds % $secondsInAMinute;
    $seconds = abs($remainingSeconds);
    $seconds = ceil($remainingSeconds);

    // return the final array
    $obj = array(
        'd' => (int) $days,
        'h' => (int) $hours,
        'm' => (int) $minutes,
        's' => (int) $seconds,
    );
    return $obj;
}

Selecting default item from Combobox C#

This means that your selectedindex is out of the range of the array of items in the combobox. The array of items in your combo box is zero-based, so if you have 2 items, it's item 0 and item 1.

android edittext onchange listener

In Kotlin Android EditText listener is set using,

   val searchTo : EditText = findViewById(R.id.searchTo)
   searchTo.addTextChangedListener(object : TextWatcher {
    override fun afterTextChanged(s: Editable) {

        // you can call or do what you want with your EditText here

        // yourEditText...
    }

    override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
    override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
})

Must JDBC Resultsets and Statements be closed separately although the Connection is closed afterwards?

From the javadocs:

When a Statement object is closed, its current ResultSet object, if one exists, is also closed.

However, the javadocs are not very clear on whether the Statement and ResultSet are closed when you close the underlying Connection. They simply state that closing a Connection:

Releases this Connection object's database and JDBC resources immediately instead of waiting for them to be automatically released.

In my opinion, always explicitly close ResultSets, Statements and Connections when you are finished with them as the implementation of close could vary between database drivers.

You can save yourself a lot of boiler-plate code by using methods such as closeQuietly in DBUtils from Apache.

How to restart counting from 1 after erasing table in MS Access?

I am going to Necro this topic.

Starting around , you can execute Data Definition Queries (DDQ) through Macro's

Data Definition Query


ALTER TABLE <Table> ALTER COLUMN <ID_Field> COUNTER(1,1);

  1. Save the DDQ, with your values
  2. Create a Macro with the appropriate logic either before this or after.
  3. To execute this DDQ:
    • Add an Open Query action
    • Define the name of the DDQ in the Query Name field; View and Data Mode settings are not relevant and can leave the default values

WARNINGS!!!!

  1. This will reset the AutoNumber Counter to 1
  2. Any Referential Integrity will be summarily destroyed

Advice

  • Use this for Staging tables
    • these are tables that are never intended to persist the data they temporarily contain.
    • The data contained is only there until additional cleaning actions have been performed and stored in the appropriate table(s).
    • Once cleaning operations have been performed and the data is no longer needed, these tables are summarily purged of any data contained.
  • Import Tables
    • These are very similar to Staging Tables but tend to only have two columns: ID and RowValue
    • Since these are typically used to import RAW data from a general file format (TXT, RTF, CSV, XML, etc.), the data contained does not persist past the processing lifecycle

fatal error LNK1104: cannot open file 'kernel32.lib'

enter image description here

gero's solution worked for me.
In Visual Studios 2012, take the following steps.
- Go to Solution Explorer
- Right click on your project
- Go to Properties
- Configuration Properties -> General
- Platform Toolset -> change to Windows7.1SDK

Is the sizeof(some pointer) always equal to four?

The reason the size of your pointer is 4 bytes is because you are compiling for a 32-bit architecture. As FryGuy pointed out, on a 64-bit architecture you would see 8.

Alternative to deprecated getCellType

From the documentation:

int getCellType() Deprecated. POI 3.15. Will return a CellType enum in the future.

Return the cell type. Will return CellType in version 4.0 of POI. For forwards compatibility, do not hard-code cell type literals in your code.

Resource files not found from JUnit test cases

My mistake, the resource files WERE actually copied to target/test-classes. The problem seemed to be due to spaces in my project name, e.g. Project%20Name.

I'm now loading the file as follows and it works:

org.apache.commons.io.FileUtils.toFile(myClass().getResource("resourceFile.txt")??);

Or, (taken from Java: how to get a File from an escaped URL?) this may be better (no dependency on Apache Commons):

myClass().getResource("resourceFile.txt")??.toURI();

Select 50 items from list at random to write to file

One easy way to select random items is to shuffle then slice.

import random
a = [1,2,3,4,5,6,7,8,9]
random.shuffle(a)
print a[:4] # prints 4 random variables

Update a local branch with the changes from a tracked remote branch

You have set the upstream of that branch

(see:

git branch -f --track my_local_branch origin/my_remote_branch
# OR (if my_local_branch is currently checked out):
$ git branch --set-upstream-to my_local_branch origin/my_remote_branch

(git branch -f --track won't work if the branch is checked out: use the second command git branch --set-upstream-to instead, or you would get "fatal: Cannot force update the current branch.")

That means your branch is already configured with:

branch.my_local_branch.remote origin
branch.my_local_branch.merge my_remote_branch

Git already has all the necessary information.
In that case:

# if you weren't already on my_local_branch branch:
git checkout my_local_branch 
# then:
git pull

is enough.


If you hadn't establish that upstream branch relationship when it came to push your 'my_local_branch', then a simple git push -u origin my_local_branch:my_remote_branch would have been enough to push and set the upstream branch.
After that, for the subsequent pulls/pushes, git pull or git push would, again, have been enough.

PHP, Get tomorrows date from date

<? php 

//1 Day = 24*60*60 = 86400

echo date("d-m-Y", time()+86400); 

?>

How to do while loops with multiple conditions

use an infinity loop like what you have originally done. Its cleanest and you can incorporate many conditions as you wish

while 1:
  if condition1 and condition2:
      break
  ...
  ...
  if condition3: break
  ...
  ...

Angular cookies

Use NGX Cookie Service

Inastall this package: npm install ngx-cookie-service --save

Add the cookie service to your app.module.ts as a provider:

import { CookieService } from 'ngx-cookie-service';
@NgModule({
  declarations: [ AppComponent ],
  imports: [ BrowserModule, ... ],
  providers: [ CookieService ],
  bootstrap: [ AppComponent ]
})

Then call in your component:

import { CookieService } from 'ngx-cookie-service';

constructor( private cookieService: CookieService ) { }

ngOnInit(): void {
  this.cookieService.set( 'name', 'Test Cookie' ); // To Set Cookie
  this.cookieValue = this.cookieService.get('name'); // To Get Cookie
}

That's it!

javascript: optional first argument in function

Like this:

my_function (null, options) // for options only
my_function (content) // for content only
my_function (content, options) // for both

Make .gitignore ignore everything except a few files

To ignore some files in a directory, you have to do this in the correct order:

For example, ignore everything in folder "application" except index.php and folder "config" pay attention to the order.

You must negate want you want first.

FAILS

application/*

!application/config/*

!application/index.php

WORKS

!application/config/*

!application/index.php

application/*

Struct like objects in Java

This is a question on Object Oriented Design, not Java the language. It's generally good practice to hide data types within the class and expose only the methods that are part of the class API. If you expose internal data types, you can never change them in the future. If you hide them, your only obligation to the user is the method's return and argument types.

Deserializing JSON Object Array with Json.net

You can create a new model to Deserialize your Json CustomerJson:

public class CustomerJson
{
    [JsonProperty("customer")]
    public Customer Customer { get; set; }
}

public class Customer
{
    [JsonProperty("first_name")]
    public string Firstname { get; set; }

    [JsonProperty("last_name")]
    public string Lastname { get; set; }

    ...
}

And you can deserialize your json easily :

JsonConvert.DeserializeObject<List<CustomerJson>>(json);

Hope it helps !

Documentation: Serializing and Deserializing JSON

How can I use numpy.correlate to do autocorrelation?

I think the real answer to the OP's question is succinctly contained in this excerpt from the Numpy.correlate documentation:

mode : {'valid', 'same', 'full'}, optional
    Refer to the `convolve` docstring.  Note that the default
    is `valid`, unlike `convolve`, which uses `full`.

This implies that, when used with no 'mode' definition, the Numpy.correlate function will return a scalar, when given the same vector for its two input arguments (i.e. - when used to perform autocorrelation).

How to run Nginx within a Docker container without halting?

To add Tomer and Charles answers,

Syntax to run nginx in forground in Docker container using Entrypoint:

ENTRYPOINT nginx -g 'daemon off;' 

Not directly related but to run multiple commands with Entrypoint:

ENTRYPOINT /bin/bash -x /myscripts/myscript.sh && nginx -g 'daemon off;' 

How to style the <option> with only CSS?

There is no cross-browser way of styling option elements, certainly not to the extent of your second screenshot. You might be able to make them bold, and set the font-size, but that will be about it...

Run jar file with command line arguments

For the question

How can i run a jar file in command prompt but with arguments

.

To pass arguments to the jar file at the time of execution

java -jar myjar.jar arg1 arg2

In the main() method of "Main-Class" [mentioned in the manifest.mft file]of your JAR file. you can retrieve them like this:

String arg1 = args[0];
String arg2 = args[1];

How can I initialise a static Map?

If you want unmodifiable map, finally java 9 added a cool factory method of to Map interface. Similar method is added to Set, List as well.

Map<String, String> unmodifiableMap = Map.of("key1", "value1", "key2", "value2");

Regular expression for URL validation (in JavaScript)

/(?:http[s]?\/\/)?(?:[\w\-]+(?::[\w\-]+)?@)?(?:[\w\-]+\.)+(?:[a-z]{2,4})(?::[0-9]+)?(?:\/[\w\-\.%]+)*(?:\?(?:[\w\-\.%]+=[\w\-\.%!]+&?)+)?(#\w+\-\.%!)?/

Values of disabled inputs will not be submitted

There are two attributes, namely readonly and disabled, that can make a semi-read-only input. But there is a tiny difference between them.

<input type="text" readonly />
<input type="text" disabled />
  • The readonly attribute makes your input text disabled, and users are not able to change it anymore.
  • Not only will the disabled attribute make your input-text disabled(unchangeable) but also cannot it be submitted.

jQuery approach (1):

$("#inputID").prop("readonly", true);
$("#inputID").prop("disabled", true);

jQuery approach (2):

$("#inputID").attr("readonly","readonly");
$("#inputID").attr("disabled", "disabled");

JavaScript approach:

document.getElementById("inputID").readOnly = true;
document.getElementById("inputID").disabled = true;

PS disabled and readonly are standard html attributes. prop introduced with jQuery 1.6.

How to do relative imports in Python?

def import_path(fullpath):
    """ 
    Import a file with full path specification. Allows one to
    import from anywhere, something __import__ does not do. 
    """
    path, filename = os.path.split(fullpath)
    filename, ext = os.path.splitext(filename)
    sys.path.append(path)
    module = __import__(filename)
    reload(module) # Might be out of date
    del sys.path[-1]
    return module

I'm using this snippet to import modules from paths, hope that helps

Add a auto increment primary key to existing table in oracle

Snagged from Oracle OTN forums

Use alter table to add column, for example:

alter table tableName add(columnName NUMBER);

Then create a sequence:

CREATE SEQUENCE SEQ_ID
START WITH 1
INCREMENT BY 1
MAXVALUE 99999999
MINVALUE 1
NOCYCLE;

and, the use update to insert values in column like this

UPDATE tableName SET columnName = seq_test_id.NEXTVAL

How do I connect to a SQL Server 2008 database using JDBC?

There are mainly two ways to use JDBC - using Windows authentication and SQL authentication. SQL authentication is probably the easiest. What you can do is something like:

String userName = "username";
String password = "password";

String url = "jdbc:sqlserver://MYPC\\SQLEXPRESS;databaseName=MYDB";

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(url, userName, password);

after adding sqljdbc4.jar to the build path.

For Window authentication you can do something like:

String url = "jdbc:sqlserver://MYPC\\SQLEXPRESS;databaseName=MYDB;integratedSecurity=true";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(url);

and then add the path to sqljdbc_auth.dll as a VM argument (still need sqljdbc4.jar in the build path).

Please take a look here for a short step-by-step guide showing how to connect to SQL Server from Java using jTDS and JDBC should you need more details. Hope it helps!

CSS - Overflow: Scroll; - Always show vertical scroll bar?

Try the following code to display scroll bar always on your page,

::-webkit-scrollbar {
  -webkit-appearance: none;
  width: 10px;
}

::-webkit-scrollbar-thumb {
  border-radius: 5px;
  background-color: rgba(0,0,0,.5);
  -webkit-box-shadow: 0 0 1px rgba(255,255,255,.5);
}

this will always show the vertical and horizontal scroll bar on your page. If you need only a vertical scroll bar then put overflow-x: hidden

Regular expression to validate US phone numbers?

The easiest way to match both

^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$

and

^[0-9]{3}-[0-9]{3}-[0-9]{4}$

is to use alternation ((...|...)): specify them as two mostly-separate options:

^(\([0-9]{3}\)|[0-9]{3}-)[0-9]{3}-[0-9]{4}$

By the way, when Americans put the area code in parentheses, we actually put a space after that; for example, I'd write (123) 123-1234, not (123)123-1234. So you might want to write:

^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$

(Though it's probably best to explicitly demonstrate the format that you expect phone numbers to be in.)

Why does foo = filter(...) return a <filter object>, not a list?

From the documentation

Note that filter(function, iterable) is equivalent to [item for item in iterable if function(item)]

In python3, rather than returning a list; filter, map return an iterable. Your attempt should work on python2 but not in python3

Clearly, you are getting a filter object, make it a list.

shesaid = list(filter(greetings(), ["hello", "goodbye"]))

What are bitwise shift (bit-shift) operators and how do they work?

Some useful bit operations/manipulations in Python.

I implemented Ravi Prakash's answer in Python.

# Basic bit operations
# Integer to binary
print(bin(10))

# Binary to integer
print(int('1010', 2))

# Multiplying x with 2 .... x**2 == x << 1
print(200 << 1)

# Dividing x with 2 .... x/2 == x >> 1
print(200 >> 1)

# Modulo x with 2 .... x % 2 == x & 1
if 20 & 1 == 0:
    print("20 is a even number")

# Check if n is power of 2: check !(n & (n-1))
print(not(33 & (33-1)))

# Getting xth bit of n: (n >> x) & 1
print((10 >> 2) & 1) # Bin of 10 == 1010 and second bit is 0

# Toggle nth bit of x : x^(1 << n)
# take bin(10) == 1010 and toggling second bit in bin(10) we get 1110 === bin(14)
print(10^(1 << 2))

Converting double to string

The exception probably comes from the parseDouble() calls. Check that the values given to that function really reflect a double.

Parser Error Message: Could not load type 'TestMvcApplication.MvcApplication'

I had what looked like the same error. I tried many suggestions from many pages only to find out the problem was that I had the website set to the wrong version of .Net

No matter how many re-compiles or people saying 'configuration problem', nobody made the point that the .net version needed to be checked.

Http Servlet request lose params from POST body after read it once

The above answers were very helpful, but still had some problems in my experience. On tomcat 7 servlet 3.0, the getParamter and getParamterValues also had to be overwritten. The solution here includes both get-query parameters and the post-body. It allows for getting raw-string easily.

Like the other solutions it uses Apache commons-io and Googles Guava.

In this solution the getParameter* methods do not throw IOException but they use super.getInputStream() (to get the body) which may throw IOException. I catch it and throw runtimeException. It is not so nice.

import com.google.common.collect.Iterables;
import com.google.common.collect.ObjectArrays;

import org.apache.commons.io.IOUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.ContentType;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 * Purpose of this class is to make getParameter() return post data AND also be able to get entire
 * body-string. In native implementation any of those two works, but not both together.
 */
public class MultiReadHttpServletRequest extends HttpServletRequestWrapper {
    public static final String UTF8 = "UTF-8";
    public static final Charset UTF8_CHARSET = Charset.forName(UTF8);
    private ByteArrayOutputStream cachedBytes;
    private Map<String, String[]> parameterMap;

    public MultiReadHttpServletRequest(HttpServletRequest request) {
        super(request);
    }

    public static void toMap(Iterable<NameValuePair> inputParams, Map<String, String[]> toMap) {
        for (NameValuePair e : inputParams) {
            String key = e.getName();
            String value = e.getValue();
            if (toMap.containsKey(key)) {
                String[] newValue = ObjectArrays.concat(toMap.get(key), value);
                toMap.remove(key);
                toMap.put(key, newValue);
            } else {
                toMap.put(key, new String[]{value});
            }
        }
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        if (cachedBytes == null) cacheInputStream();
        return new CachedServletInputStream();
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    private void cacheInputStream() throws IOException {
    /* Cache the inputStream in order to read it multiple times. For
     * convenience, I use apache.commons IOUtils
     */
        cachedBytes = new ByteArrayOutputStream();
        IOUtils.copy(super.getInputStream(), cachedBytes);
    }

    @Override
    public String getParameter(String key) {
        Map<String, String[]> parameterMap = getParameterMap();
        String[] values = parameterMap.get(key);
        return values != null && values.length > 0 ? values[0] : null;
    }

    @Override
    public String[] getParameterValues(String key) {
        Map<String, String[]> parameterMap = getParameterMap();
        return parameterMap.get(key);
    }

    @Override
    public Map<String, String[]> getParameterMap() {
        if (parameterMap == null) {
            Map<String, String[]> result = new LinkedHashMap<String, String[]>();
            decode(getQueryString(), result);
            decode(getPostBodyAsString(), result);
            parameterMap = Collections.unmodifiableMap(result);
        }
        return parameterMap;
    }

    private void decode(String queryString, Map<String, String[]> result) {
        if (queryString != null) toMap(decodeParams(queryString), result);
    }

    private Iterable<NameValuePair> decodeParams(String body) {
        Iterable<NameValuePair> params = URLEncodedUtils.parse(body, UTF8_CHARSET);
        try {
            String cts = getContentType();
            if (cts != null) {
                ContentType ct = ContentType.parse(cts);
                if (ct.getMimeType().equals(ContentType.APPLICATION_FORM_URLENCODED.getMimeType())) {
                    List<NameValuePair> postParams = URLEncodedUtils.parse(IOUtils.toString(getReader()), UTF8_CHARSET);
                    params = Iterables.concat(params, postParams);
                }
            }
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
        return params;
    }

    public String getPostBodyAsString() {
        try {
            if (cachedBytes == null) cacheInputStream();
            return cachedBytes.toString(UTF8);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /* An inputStream which reads the cached request body */
    public class CachedServletInputStream extends ServletInputStream {
        private ByteArrayInputStream input;

        public CachedServletInputStream() {
            /* create a new input stream from the cached request body */
            input = new ByteArrayInputStream(cachedBytes.toByteArray());
        }

        @Override
        public int read() throws IOException {
            return input.read();
        }
    }

    @Override
    public String toString() {
        String query = dk.bnr.util.StringUtil.nullToEmpty(getQueryString());
        StringBuilder sb = new StringBuilder();
        sb.append("URL='").append(getRequestURI()).append(query.isEmpty() ? "" : "?" + query).append("', body='");
        sb.append(getPostBodyAsString());
        sb.append("'");
        return sb.toString();
    }
}

jQuery changing css class to div

An HTML element like div can have more than one classes. Let say div is assigned two styles using addClass method. If style1 has 3 properties like font-size, weight and color, and style2 has 4 properties like font-size, weight, color and background-color, the resultant effective properties set (style), i think, will have 4 properties i.e. union of all style sets. Common properties, in our case, color,font-size, weight, will have one occuerance with latest values. If div is assigned style1 first and style2 second, the common prpoerties will be overwritten by style2 values.

Further, I have written a post at Using JQuery to Apply,Remove and Manage Styles, I hope it will help you

Regards Awais

Is it possible to print a variable's type in standard C++?

Don't forget to include <typeinfo>

I believe what you are referring to is runtime type identification. You can achieve the above by doing .

#include <iostream>
#include <typeinfo>

using namespace std;

int main() {
  int i;
  cout << typeid(i).name();
  return 0;
}

How to add dll in c# project

Have you added the dll into your project references list? If not right click on the project "References" folder and selecet "Add Reference" then use browse to locate your science.dll, select it and click ok.

edit

I can't see the image of your VS instance that some people are referring to and I note that you now say that it works in Net4.0 and VS2010.

VS2008 projects support NET 3.5 by default. I expect that is the problem as your DLL may be NET 4.0 compliant but not NET 3.5.

Uninitialized constant ActiveSupport::Dependencies::Mutex (NameError)

If you want to keep your version same like rails will be 2.3.8 and gem version will be latest. You can use this solution Latest gem with Rails2.x. in this some changes in boot.rb file and environment.rb file.

require 'thread' in boot.rb file at the top.

and in environment.rb file add the following code above the initializer block.

if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.3.7')
 module Rails
   class GemDependency
     def requirement
       r = super
       (r == Gem::Requirement.default) ? nil : r
     end
   end
 end
end

Using sed to split a string with a delimiter

Using simply :

$ tr ':' $'\n' <<< string1:string2:string3:string4:string5
string1
string2
string3
string4
string5

If you really need :

$ sed 's/:/\n/g' <<< string1:string2:string3:string4:string5
string1
string2
string3
string4
string5

Load RSA public key from file

This program is doing almost everything with Public and private keys. The der format can be obtained but saving raw data ( without encoding base64). I hope this helps programmers.

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import sun.security.pkcs.PKCS8Key;
import sun.security.pkcs10.PKCS10;
import sun.security.x509.X500Name;

import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;



/**
 * @author Desphilboy
 * DorOd bar shomA barobach
 *
 */
public class csrgenerator {

    private static PublicKey publickey= null;
    private static PrivateKey privateKey=null;
    //private static PKCS8Key privateKey=null;
    private static KeyPairGenerator kpg= null;
    private static ByteArrayOutputStream bs =null;
    private static csrgenerator thisinstance;
    private KeyPair keypair;
    private static PKCS10 pkcs10;
    private String signaturealgorithm= "MD5WithRSA";

    public String getSignaturealgorithm() {
        return signaturealgorithm;
    }



    public void setSignaturealgorithm(String signaturealgorithm) {
        this.signaturealgorithm = signaturealgorithm;
    }



    private csrgenerator() {
        try {
           kpg = KeyPairGenerator.getInstance("RSA");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            System.out.print("No such algorithm RSA in constructor csrgenerator\n");
        }
        kpg.initialize(2048);
        keypair = kpg.generateKeyPair();
        publickey = keypair.getPublic();
        privateKey = keypair.getPrivate();
    }



    /** Generates a new key pair 
    *
    * @param int bits 
    *   this is the number of bits in modulus must be 512, 1024, 2048  or so on 
    */
    public KeyPair generateRSAkys(int bits)
    {
          kpg.initialize(bits);
            keypair = kpg.generateKeyPair();
            publickey = keypair.getPublic();
            privateKey = keypair.getPrivate();
            KeyPair dup= keypair;
     return dup;
    }

     public static csrgenerator getInstance() {
            if (thisinstance == null)
                thisinstance = new csrgenerator();
            return thisinstance;
        }


     /**
      *  Returns a CSR as string  
      * @param cn  Common Name
      * @param OU  Organizational Unit 
      * @param Org  Organization
      * @param LocName Location name
      * @param Statename  State/Territory/Province/Region
      * @param Country    Country
      * @return     returns  csr as string.
      * @throws Exception
      */
     public String getCSR(String commonname, String organizationunit, String organization,String localname, String statename, String country ) throws Exception {
            byte[] csr = generatePKCS10(commonname, organizationunit, organization, localname, statename, country,signaturealgorithm);
            return new String(csr);
        }

     /** This function generates a new Certificate 
      * Signing Request. 
     *
     * @param CN
     *            Common Name, is X.509 speak for the name that distinguishes
     *            the Certificate best, and ties it to your Organization
     * @param OU
     *            Organizational unit
     * @param O
     *            Organization NAME
     * @param L
     *            Location
     * @param S
     *            State
     * @param C
     *            Country
     * @return    byte stream of generated request
     * @throws Exception
     */
    private static byte[] generatePKCS10(String CN, String OU, String O,String L, String S, String C,String sigAlg) throws Exception {
        // generate PKCS10 certificate request

        pkcs10 = new PKCS10(publickey);
       Signature   signature = Signature.getInstance(sigAlg);
        signature.initSign(privateKey);
        // common, orgUnit, org, locality, state, country
        //X500Name(String commonName, String organizationUnit,String organizationName,Local,State, String country)
        X500Name x500Name = new X500Name(CN, OU, O, L, S, C);
        pkcs10.encodeAndSign(x500Name,signature);
        bs = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(bs);
        pkcs10.print(ps);
        byte[] c = bs.toByteArray();
        try {
            if (ps != null)
                ps.close();
            if (bs != null)
                bs.close();
        } catch (Throwable th) {
        }
        return c;
    }

    public  PublicKey getPublicKey() {
        return publickey;
    }




    /**
     * @return
     */
    public PrivateKey getPrivateKey() {
        return privateKey;
    }

    /**
     * saves private key to a file
     * @param filename
     */
    public  void SavePrivateKey(String filename)
    {
        PKCS8EncodedKeySpec pemcontents=null;
        pemcontents= new PKCS8EncodedKeySpec( privateKey.getEncoded());
        PKCS8Key pemprivatekey= new  PKCS8Key( );
        try {
            pemprivatekey.decode(pemcontents.getEncoded());
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        File file=new File(filename);
        try {

            file.createNewFile();
            FileOutputStream fos=new FileOutputStream(file);
            fos.write(pemprivatekey.getEncoded());
            fos.flush();
            fos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }



    }



    /**
     * Saves Certificate Signing Request to a file;
     * @param filename  is a String containing full path to the file which will be created containing the CSR.
     */
    public void SaveCSR(String filename)
    {
        FileOutputStream fos=null;
        PrintStream ps=null;
        File file;
        try {

            file = new File(filename);
            file.createNewFile();
            fos = new FileOutputStream(file);
            ps= new PrintStream(fos);
        }catch (IOException e)
        {
            System.out.print("\n could not open the file "+ filename);
        }

        try {
            try {
                pkcs10.print(ps);
            } catch (SignatureException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            ps.flush();
            ps.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            System.out.print("\n cannot write to the file "+ filename);
            e.printStackTrace();

        }

        }


    /**
     * Saves both public key and private  key to file names specified
     * @param fnpub  file name of public key
     * @param fnpri  file name of private key
     * @throws IOException
     */
    public static void SaveKeyPair(String fnpub,String fnpri) throws IOException { 

// Store Public Key.
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(
publickey.getEncoded());
FileOutputStream fos = new FileOutputStream(fnpub);
fos.write(x509EncodedKeySpec.getEncoded());
fos.close();

// Store Private Key.
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
fos = new FileOutputStream(fnpri);
fos.write(pkcs8EncodedKeySpec.getEncoded());
fos.close();
}


    /**
     * Reads a Private Key from a pem base64 encoded file.
     * @param filename name of the file to read.
     * @param algorithm Algorithm is usually "RSA"
     * @return returns the privatekey which is read from the file;
     * @throws Exception
     */
    public  PrivateKey getPemPrivateKey(String filename, String algorithm) throws Exception {
          File f = new File(filename);
          FileInputStream fis = new FileInputStream(f);
          DataInputStream dis = new DataInputStream(fis);
          byte[] keyBytes = new byte[(int) f.length()];
          dis.readFully(keyBytes);
          dis.close();

          String temp = new String(keyBytes);
          String privKeyPEM = temp.replace("-----BEGIN PRIVATE KEY-----", "");
          privKeyPEM = privKeyPEM.replace("-----END PRIVATE KEY-----", "");
          //System.out.println("Private key\n"+privKeyPEM);

          BASE64Decoder b64=new BASE64Decoder();
          byte[] decoded = b64.decodeBuffer(privKeyPEM);

          PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decoded);
          KeyFactory kf = KeyFactory.getInstance(algorithm);
          return kf.generatePrivate(spec);
          }



    /**
     * Saves the private key to a pem file.
     * @param filename  name of the file to write the key into 
     * @param key the Private key to save.
     * @return  String representation of the pkcs8 object.
     * @throws Exception
     */
    public  String  SavePemPrivateKey(String filename) throws Exception {
        PrivateKey key=this.privateKey;
          File f = new File(filename);
          FileOutputStream fos = new FileOutputStream(f);
          DataOutputStream dos = new DataOutputStream(fos);


          byte[] keyBytes = key.getEncoded();
          PKCS8Key pkcs8= new PKCS8Key();
          pkcs8.decode(keyBytes);
          byte[] b=pkcs8.encode();

          BASE64Encoder b64=new BASE64Encoder();
          String  encoded = b64.encodeBuffer(b);

          encoded= "-----BEGIN PRIVATE KEY-----\r\n" + encoded + "-----END PRIVATE KEY-----";

         dos.writeBytes(encoded);
         dos.flush();
         dos.close();

          //System.out.println("Private key\n"+privKeyPEM);
        return pkcs8.toString();

          }


    /**
     * Saves a public key to a base64 encoded pem file
     * @param filename  name of the file 
     * @param key public key to be saved 
     * @return string representation of the pkcs8 object.
     * @throws Exception
     */
    public  String  SavePemPublicKey(String filename) throws Exception {
        PublicKey key=this.publickey;  
        File f = new File(filename);
          FileOutputStream fos = new FileOutputStream(f);
          DataOutputStream dos = new DataOutputStream(fos);


          byte[] keyBytes = key.getEncoded();
          BASE64Encoder b64=new BASE64Encoder();
          String  encoded = b64.encodeBuffer(keyBytes);

          encoded= "-----BEGIN PUBLIC KEY-----\r\n" + encoded + "-----END PUBLIC KEY-----";

         dos.writeBytes(encoded);
         dos.flush();
         dos.close();

          //System.out.println("Private key\n"+privKeyPEM);
      return  encoded.toString();

          }





       /**
     * reads a public key from a file
     * @param filename name of the file to read
     * @param algorithm is usually RSA
     * @return the read public key
     * @throws Exception
     */
    public  PublicKey getPemPublicKey(String filename, String algorithm) throws Exception {
          File f = new File(filename);
          FileInputStream fis = new FileInputStream(f);
          DataInputStream dis = new DataInputStream(fis);
          byte[] keyBytes = new byte[(int) f.length()];
          dis.readFully(keyBytes);
          dis.close();

          String temp = new String(keyBytes);
          String publicKeyPEM = temp.replace("-----BEGIN PUBLIC KEY-----\n", "");
          publicKeyPEM = publicKeyPEM.replace("-----END PUBLIC KEY-----", "");


          BASE64Decoder b64=new BASE64Decoder();
          byte[] decoded = b64.decodeBuffer(publicKeyPEM);

          X509EncodedKeySpec spec =
                new X509EncodedKeySpec(decoded);
          KeyFactory kf = KeyFactory.getInstance(algorithm);
          return kf.generatePublic(spec);
          }




    public static void main(String[] args) throws Exception {
        csrgenerator gcsr = csrgenerator.getInstance();
        gcsr.setSignaturealgorithm("SHA512WithRSA");
        System.out.println("Public Key:\n"+gcsr.getPublicKey().toString());

        System.out.println("Private Key:\nAlgorithm: "+gcsr.getPrivateKey().getAlgorithm().toString());
        System.out.println("Format:"+gcsr.getPrivateKey().getFormat().toString());
        System.out.println("To String :"+gcsr.getPrivateKey().toString());
        System.out.println("GetEncoded :"+gcsr.getPrivateKey().getEncoded().toString());
        BASE64Encoder encoder= new BASE64Encoder();
        String s=encoder.encodeBuffer(gcsr.getPrivateKey().getEncoded());
        System.out.println("Base64:"+s+"\n");

        String csr = gcsr.getCSR( "[email protected]","baxshi az xodam", "Xodam","PointCook","VIC" ,"AU");
        System.out.println("CSR Request Generated!!");
        System.out.println(csr);
        gcsr.SaveCSR("c:\\testdir\\javacsr.csr");
        String p=gcsr.SavePemPrivateKey("c:\\testdir\\java_private.pem");
        System.out.print(p);
        p=gcsr.SavePemPublicKey("c:\\testdir\\java_public.pem");
        privateKey= gcsr.getPemPrivateKey("c:\\testdir\\java_private.pem", "RSA");
        BASE64Encoder encoder1= new BASE64Encoder();
        String s1=encoder1.encodeBuffer(gcsr.getPrivateKey().getEncoded());
        System.out.println("Private Key in Base64:"+s1+"\n");
        System.out.print(p);


    }

    }

Make body have 100% of the browser height

I would use this

_x000D_
_x000D_
html, body{_x000D_
      background: #E73;_x000D_
      min-height: 100%;_x000D_
      min-height: 100vh;_x000D_
      overflow: auto; // <- this is needed when you resize the screen_x000D_
    }
_x000D_
<html>_x000D_
    <body>_x000D_
    </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

The browser will use min-height: 100vh and if somehow the browser is a little older the min-height: 100% will be the fallback.

The overflow: auto is necessary if you want the body and html to expand their height when you resize the screen (to a mobile size for example)

Change the background color of a row in a JTable

One way would be store the current colour for each row within the model. Here's a simple model that is fixed at 3 columns and 3 rows:

static class MyTableModel extends DefaultTableModel {

    List<Color> rowColours = Arrays.asList(
        Color.RED,
        Color.GREEN,
        Color.CYAN
    );

    public void setRowColour(int row, Color c) {
        rowColours.set(row, c);
        fireTableRowsUpdated(row, row);
    }

    public Color getRowColour(int row) {
        return rowColours.get(row);
    }

    @Override
    public int getRowCount() {
        return 3;
    }

    @Override
    public int getColumnCount() {
        return 3;
    }

    @Override
    public Object getValueAt(int row, int column) {
        return String.format("%d %d", row, column);
    }
}

Note that setRowColour calls fireTableRowsUpdated; this will cause just that row of the table to be updated.

The renderer can get the model from the table:

static class MyTableCellRenderer extends DefaultTableCellRenderer {

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        MyTableModel model = (MyTableModel) table.getModel();
        Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        c.setBackground(model.getRowColour(row));
        return c;
    }
}

Changing a row's colour would be as simple as:

model.setRowColour(1, Color.YELLOW);

How can I use pointers in Java?

Java does have pointers. Any time you create an object in Java, you're actually creating a pointer to the object; this pointer could then be set to a different object or to null, and the original object will still exist (pending garbage collection).

What you can't do in Java is pointer arithmetic. You can't dereference a specific memory address or increment a pointer.

If you really want to get low-level, the only way to do it is with the Java Native Interface; and even then, the low-level part has to be done in C or C++.

Embed HTML5 YouTube video without iframe?

Yes. Youtube API is the best resource for this.

There are 3 way to embed a video:

  • IFrame embeds using <iframe> tags
  • IFrame embeds using the IFrame Player API
  • AS3 (and AS2*) object embeds DEPRECATED

I think you are looking for the second one of them:

IFrame embeds using the IFrame Player API

The HTML and JavaScript code below shows a simple example that inserts a YouTube player into the page element that has an id value of ytplayer. The onYouTubePlayerAPIReady() function specified here is called automatically when the IFrame Player API code has loaded. This code does not define any player parameters and also does not define other event handlers.

<div id="ytplayer"></div>

<script>
  // Load the IFrame Player API code asynchronously.
  var tag = document.createElement('script');
  tag.src = "https://www.youtube.com/player_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  // Replace the 'ytplayer' element with an <iframe> and
  // YouTube player after the API code downloads.
  var player;
  function onYouTubePlayerAPIReady() {
    player = new YT.Player('ytplayer', {
      height: '390',
      width: '640',
      videoId: 'M7lc1UVf-VE'
    });
  }
</script>

Here are some instructions where you may take a look when starting using the API.


An embed example without using iframe is to use <object> tag:

<object width="640" height="360">
    <param name="movie" value="http://www.youtube.com/embed/yt-video-id?html5=1&amp;rel=0&amp;hl=en_US&amp;version=3"/
    <param name="allowFullScreen" value="true"/>
    <param name="allowscriptaccess" value="always"/>
    <embed width="640" height="360" src="http://www.youtube.com/embed/yt-video-id?html5=1&amp;rel=0&amp;hl=en_US&amp;version=3" class="youtube-player" type="text/html" allowscriptaccess="always" allowfullscreen="true"/>
</object>

(replace yt-video-id with your video id)

JSFIDDLE

How do I get to IIS Manager?

To open IIS Manager, click Start, type inetmgr in the Search Programs and Files box, and then press ENTER.

if the IIS Manager doesn't open that means you need to install it.

So, Follow the instruction at this link: https://docs.microsoft.com/en-us/iis/install/installing-iis-7/installing-iis-on-windows-vista-and-windows-7

How to convert NSNumber to NSString

You can do it with:

NSNumber *myNumber = @15;
NSString *myNumberInString = [myNumber stringValue];

How to get the selected value from drop down list in jsp?

Direct value should work just fine:

var sel = document.getElementsByName('item');
var sv = sel.value;
alert(sv);

The only reason your code might fail is when there is no item selected, then the selectedIndex returns -1 and the code breaks.

Accessing member of base class

You are incorrectly using the super and this keyword. Here is an example of how they work:

class Animal {
    public name: string;
    constructor(name: string) { 
        this.name = name;
    }
    move(meters: number) {
        console.log(this.name + " moved " + meters + "m.");
    }
}

class Horse extends Animal {
    move() {
        console.log(super.name + " is Galloping...");
        console.log(this.name + " is Galloping...");
        super.move(45);
    }
}

var tom: Animal = new Horse("Tommy the Palomino");

Animal.prototype.name = 'horseee'; 

tom.move(34);
// Outputs:

// horseee is Galloping...
// Tommy the Palomino is Galloping...
// Tommy the Palomino moved 45m.

Explanation:

  1. The first log outputs super.name, this refers to the prototype chain of the object tom, not the object tom self. Because we have added a name property on the Animal.prototype, horseee will be outputted.
  2. The second log outputs this.name, the this keyword refers to the the tom object itself.
  3. The third log is logged using the move method of the Animal base class. This method is called from Horse class move method with the syntax super.move(45);. Using the super keyword in this context will look for a move method on the prototype chain which is found on the Animal prototype.

Remember TS still uses prototypes under the hood and the class and extends keywords are just syntactic sugar over prototypical inheritance.

How to wrap text of HTML button with fixed width?

If we have some inner divisions inside <button> tag like this-

<button class="top-container">
    <div class="classA">
       <div class="classB">
           puts " some text to get print." 
       </div>
     </div>
     <div class="class1">
       <div class="class2">
           puts " some text to get print." 
       </div>
     </div>
</button>

Sometime Text of class A get overlap on class1 data because these both are in a single button tag. I try to break the tex using-

 word-wrap: break-word;         /* All browsers since IE 5.5+ */
 overflow-wrap: break-word;     /* Renamed property in CSS3 draft spec */ 

But this won't worked then I try this-

white-space: normal;

after removing above css properties and got my task done.

Hope will work for all !!!

Oracle timestamp data type

The number in parentheses specifies the precision of fractional seconds to be stored. So, (0) would mean don't store any fraction of a second, and use only whole seconds. The default value if unspecified is 6 digits after the decimal separator.

So an unspecified value would store a date like:

TIMESTAMP 24-JAN-2012 08.00.05.993847 AM

And specifying (0) stores only:

TIMESTAMP(0) 24-JAN-2012 08.00.05 AM

See Oracle documentation on data types.

How to navigate to a section of a page

Use an call thru section, it works

<div id="content">
     <section id="home">
               ...
     </section>

Call the above the thru

 <a href="#home">page1</a>

Scrolling needs jquery paste this.. on above to ending body closing tag..

<script>
  $(function() {
      $('a[href*=#]:not([href=#])').click(function() {
          if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
              var target = $(this.hash);
              target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
              if (target.length) {
                  $('html,body').animate({
                      scrollTop: target.offset().top
                  }, 1000);
                  return false;
              }
          }
      });
  });
</script>

Include headers when using SELECT INTO OUTFILE?

Here is a way to get the header titles from the column names dynamically.

/* Change table_name and database_name */
SET @table_name = 'table_name';
SET @table_schema = 'database_name';
SET @default_group_concat_max_len = (SELECT @@group_concat_max_len);

/* Sets Group Concat Max Limit larger for tables with a lot of columns */
SET SESSION group_concat_max_len = 1000000;

SET @col_names = (
  SELECT GROUP_CONCAT(QUOTE(`column_name`)) AS columns
  FROM information_schema.columns
  WHERE table_schema = @table_schema
  AND table_name = @table_name);

SET @cols = CONCAT('(SELECT ', @col_names, ')');

SET @query = CONCAT('(SELECT * FROM ', @table_schema, '.', @table_name,
  ' INTO OUTFILE \'/tmp/your_csv_file.csv\'
  FIELDS ENCLOSED BY \'\\\'\' TERMINATED BY \'\t\' ESCAPED BY \'\'
  LINES TERMINATED BY \'\n\')');

/* Concatenates column names to query */
SET @sql = CONCAT(@cols, ' UNION ALL ', @query);

/* Resets Group Contact Max Limit back to original value */
SET SESSION group_concat_max_len = @default_group_concat_max_len;

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

Remove duplicates from a List<T> in C#

A simple intuitive implementation:

public static List<PointF> RemoveDuplicates(List<PointF> listPoints)
{
    List<PointF> result = new List<PointF>();

    for (int i = 0; i < listPoints.Count; i++)
    {
        if (!result.Contains(listPoints[i]))
            result.Add(listPoints[i]);
        }

        return result;
    }

How to pass multiple parameters in a querystring

Query String: ?strID=XXXX&strName=yyyy&strDate=zzzzz

before you redirect:

string queryString = Request.QueryString.ToString();

Response.Redirect("page.aspx?"+queryString);

How to select current date in Hive SQL

According to the LanguageManual, you can use unix_timestamp() to get the "current time stamp using the default time zone." If you need to convert that to something more human-readable, you can use from_unixtime(unix_timestamp()).

Hope that helps.

Add text at the end of each line

Using a text editor, check for ^M (control-M, or carriage return) at the end of each line. You will need to remove them first, then append the additional text at the end of the line.

sed -i 's|^M||g' ips.txt
sed -i 's|$|:80|g' ips.txt

Easy interview question got harder: given numbers 1..100, find the missing number(s) given exactly k are missing

I think this can be generalized like this:

Denote S, M as the initial values for the sum of arithmetic series and multiplication.

S = 1 + 2 + 3 + 4 + ... n=(n+1)*n/2
M = 1 * 2 * 3 * 4 * .... * n 

I should think about a formula to calculate this, but that is not the point. Anyway, if one number is missing, you already provided the solution. However, if two numbers are missing then, let's denote the new sum and total multiple by S1 and M1, which will be as follows:

S1 = S - (a + b)....................(1)

Where a and b are the missing numbers.

M1 = M - (a * b)....................(2)

Since you know S1, M1, M and S, the above equation is solvable to find a and b, the missing numbers.

Now for the three numbers missing:

S2 = S - ( a + b + c)....................(1)

Where a and b are the missing numbers.

M2 = M - (a * b * c)....................(2)

Now your unknown is 3 while you just have two equations you can solve from.

How to retrieve a single file from a specific revision in Git?

Using git show

To complete your own answer, the syntax is indeed

git show object
git show $REV:$FILE
git show somebranch:from/the/root/myfile.txt
git show HEAD^^^:test/test.py

The command takes the usual style of revision, meaning you can use any of the following:

  1. branch name (as suggested by ash)
  2. HEAD + x number of ^ characters
  3. The SHA1 hash of a given revision
  4. The first few (maybe 5) characters of a given SHA1 hash

Tip It's important to remember that when using "git show", always specify a path from the root of the repository, not your current directory position.

(Although Mike Morearty mentions that, at least with git 1.7.5.4, you can specify a relative path by putting "./" at the beginning of the path. For example:

git show HEAD^^:./test.py

)

Using git restore

With Git 2.23+ (August 2019), you can also use git restore which replaces the confusing git checkout command

git restore -s <SHA1>     -- afile
git restore -s somebranch -- afile

That would restore on the working tree only the file as present in the "source" (-s) commit SHA1 or branch somebranch.
To restore also the index:

git restore -s <SHA1> -SW -- afile

(-SW: short for --staged --worktree)

Using low-level git plumbing commands

Before git1.5.x, this was done with some plumbing:

git ls-tree <rev>
show a list of one or more 'blob' objects within a commit

git cat-file blob <file-SHA1>
cat a file as it has been committed within a specific revision (similar to svn cat). use git ls-tree to retrieve the value of a given file-sha1

git cat-file -p $(git-ls-tree $REV $file | cut -d " " -f 3 | cut -f 1)::

git-ls-tree lists the object ID for $file in revision $REV, this is cut out of the output and used as an argument to git-cat-file, which should really be called git-cat-object, and simply dumps that object to stdout.


Note: since Git 2.11 (Q4 2016), you can apply a content filter to the git cat-file output.

See commit 3214594, commit 7bcf341 (09 Sep 2016), commit 7bcf341 (09 Sep 2016), and commit b9e62f6, commit 16dcc29 (24 Aug 2016) by Johannes Schindelin (dscho).
(Merged by Junio C Hamano -- gitster -- in commit 7889ed2, 21 Sep 2016)

git config diff.txt.textconv "tr A-Za-z N-ZA-Mn-za-m <"
git cat-file --textconv --batch

Note: "git cat-file --textconv" started segfaulting recently (2017), which has been corrected in Git 2.15 (Q4 2017)

See commit cc0ea7c (21 Sep 2017) by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit bfbc2fc, 28 Sep 2017)

What is RSS and VSZ in Linux memory management

RSS is the Resident Set Size and is used to show how much memory is allocated to that process and is in RAM. It does not include memory that is swapped out. It does include memory from shared libraries as long as the pages from those libraries are actually in memory. It does include all stack and heap memory.

VSZ is the Virtual Memory Size. It includes all memory that the process can access, including memory that is swapped out, memory that is allocated, but not used, and memory that is from shared libraries.

So if process A has a 500K binary and is linked to 2500K of shared libraries, has 200K of stack/heap allocations of which 100K is actually in memory (rest is swapped or unused), and it has only actually loaded 1000K of the shared libraries and 400K of its own binary then:

RSS: 400K + 1000K + 100K = 1500K
VSZ: 500K + 2500K + 200K = 3200K

Since part of the memory is shared, many processes may use it, so if you add up all of the RSS values you can easily end up with more space than your system has.

The memory that is allocated also may not be in RSS until it is actually used by the program. So if your program allocated a bunch of memory up front, then uses it over time, you could see RSS going up and VSZ staying the same.

There is also PSS (proportional set size). This is a newer measure which tracks the shared memory as a proportion used by the current process. So if there were two processes using the same shared library from before:

PSS: 400K + (1000K/2) + 100K = 400K + 500K + 100K = 1000K

Threads all share the same address space, so the RSS, VSZ and PSS for each thread is identical to all of the other threads in the process. Use ps or top to view this information in linux/unix.

There is way more to it than this, to learn more check the following references:

Also see:

How do I automatically set the $DISPLAY variable for my current session?

Here's something I've just knocked up. It inspects the environment of the last-launched "gnome-session" process (DISPLAY is set correctly when VNC launches a session/window manager). Replace "gnome-session" with the name of whatever process your VNC server launches on startup.

PID=`pgrep -n -u $USER gnome-session`
if [ -n "$PID" ]; then
    export DISPLAY=`awk 'BEGIN{FS="="; RS="\0"}  $1=="DISPLAY" {print $2; exit}' /proc/$PID/environ`
    echo "DISPLAY set to $DISPLAY"
else
    echo "Could not set DISPLAY"
fi
unset PID

You should just be able to drop that in your .bashrc file.

Clearfix with twitter bootstrap

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

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

see this demo


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

Adding timestamp to a filename with mv in BASH

The few lines you posted from your script look okay to me. It's probably something a bit deeper.

You need to find which line is giving you this error. Add set -xv to the top of your script. This will print out the line number and the command that's being executed to STDERR. This will help you identify where in your script you're getting this particular error.

BTW, do you have a shebang at the top of your script? When I see something like this, I normally expect its an issue with the Shebang. For example, if you had #! /bin/bash on top, but your bash interpreter is located in /usr/bin/bash, you'll see this error.

EDIT

New question: How can I save the file correctly in the first place, to avoid having to perform this fix every time I resend the file?

Two ways:

  1. Select the Edit->EOL Conversion->Unix Format menu item when you edit a file. Once it has the correct line endings, Notepad++ will keep them.
  2. To make sure all new files have the correct line endings, go to the Settings->Preferences menu item, and pull up the Preferences dialog box. Select the New Document/Default Directory tab. Under New Document and Format, select the Unix radio button. Click the Close button.

Time part of a DateTime Field in SQL

I know this is an old question, but since the other answers all

  • return strings (rather than datetimes),
  • rely on the internal representation of dates (conversion to float, int, and back) or
  • require SQL Server 2008 or beyond,

I thought I'd add a "pure" option which only requires datetime operations and works with SQL Server 2005+:

SELECT DATEADD(dd, -DATEDIFF(dd, 0, mydatetime), mydatetime)

This calculates the difference (in whole days) between date zero (1900-01-01) and the given date and then subtracts that number of days from the given date, thereby setting its date component to zero.

Short circuit Array.forEach like calling break

You can create a variant of forEach that allows for break, continue, return, and even async/await: (example written in TypeScript)

export type LoopControlOp = "break" | "continue" | ["return", any];
export type LoopFunc<T> = (value: T, index: number, array: T[])=>LoopControlOp;

Array.prototype.ForEach = function ForEach<T>(this: T[], func: LoopFunc<T>) {
    for (let i = 0; i < this.length; i++) {
        const controlOp = func(this[i], i, this);
        if (controlOp == "break") break;
        if (controlOp == "continue") continue;
        if (controlOp instanceof Array) return controlOp[1];
    }
};

// this variant lets you use async/await in the loop-func, with the loop "awaiting" for each entry
Array.prototype.ForEachAsync = async function ForEachAsync<T>(this: T[], func: LoopFunc<T>) {
    for (let i = 0; i < this.length; i++) {
        const controlOp = await func(this[i], i, this);
        if (controlOp == "break") break;
        if (controlOp == "continue") continue;
        if (controlOp instanceof Array) return controlOp[1];
    }
};

Usage:

function GetCoffee() {
    const cancelReason = peopleOnStreet.ForEach((person, index)=> {
        if (index == 0) return "continue";
        if (person.type == "friend") return "break";
        if (person.type == "boss") return ["return", "nevermind"];
    });
    if (cancelReason) console.log("Coffee canceled because: " + cancelReason);
}

Storing money in a decimal column - what precision and scale?

I would think that for a large part your or your client's requirements should dictate what precision and scale to use. For example, for the e-commerce website I am working on that deals with money in GBP only, I have been required to keep it to Decimal( 6, 2 ).

Get the current user, within an ApiController action, without passing the userID as a parameter

You can also access the principal using the User property on ApiController.

So the following two statements are basically the same:

string id;
id = User.Identity.GetUserId();
id = RequestContext.Principal.Identity.GetUserId();

:after and :before pseudo-element selectors in Sass

Use ampersand to specify the parent selector.

SCSS syntax:

p {
    margin: 2em auto;

    > a {
        color: red;
    }

    &:before {
        content: "";
    }

    &:after {
        content: "* * *";
    }
}

How to use template module with different set of variables?

I did it in this way.

In tasks/main.yml

- name: template test
  template: 
        src=myTemplateFile.j2
        dest={{item}}
   with_dict: some_dict

and in vars/main.yml

some_dict:
  /path/to/dest1:
    var1: 1
    var2: 2
  /path/to/dest2:
    var1: 3
    var2: 4

and in templates/myTemplateFile.j2

some_var = {{ item.value.var1 }}
some_other_var = {{ item.value.var2 }}

Hope this solves your problem.

Postgresql - select something where date = "01/01/11"

With PostgreSQL there are a number of date/time functions available, see here.

In your example, you could use:

SELECT * FROM myTable WHERE date_trunc('day', dt) = 'YYYY-MM-DD';

If you are running this query regularly, it is possible to create an index using the date_trunc function as well:

CREATE INDEX date_trunc_dt_idx ON myTable ( date_trunc('day', dt) );

One advantage of this is there is some more flexibility with timezones if required, for example:

CREATE INDEX date_trunc_dt_idx ON myTable ( date_trunc('day', dt at time zone 'Australia/Sydney') );
SELECT * FROM myTable WHERE date_trunc('day', dt at time zone 'Australia/Sydney') = 'YYYY-MM-DD';

Using sed, Insert a line above or below the pattern?

More portable to use ed; some systems don't support \n in sed

printf "/^lorem ipsum dolor sit amet/a\nconsectetur adipiscing elit\n.\nw\nq\n" |\
    /bin/ed $filename

Integer value comparison

Although you could certainly use the compareTo method on an Integer instance, it's not clear when reading the code, so you should probably avoid doing so.

Java allows you to use autoboxing (see http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html) to compare directly with an int, so you can do:

if (count > 0) { }

And the Integer instance count gets automatically converted to an int for the comparison.

If you're having trouble understanding this, check out the link above, or imagine it's doing this:

if (count.intValue() > 0) { }

compilation error: identifier expected

You must to wrap your following code into a block (Either method or static).

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("What is your name?");
String name = in.readLine(); ;
System.out.println("Hello " + name);

Without a block you can only declare variables and more than that assign them a value in single statement.

For method main() will be best choice for now:

public class details {
    public static void main(String[] args){
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("What is your name?");
        String name = in.readLine(); ;
        System.out.println("Hello " + name);
    }
}

or If you want to use static block then...

public class details {
    static {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("What is your name?");
        String name = in.readLine(); ;
        System.out.println("Hello " + name);
    }
}

or if you want to build another method then..

public class details {
    public static void main(String[] args){
        myMethod();
    }
    private static void myMethod(){
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("What is your name?");
        String name = in.readLine(); ;
        System.out.println("Hello " + name);
    }
}

Also worry about exception due to BufferedReader .

Can I use Homebrew on Ubuntu?

I just tried installing it using the ruby command but somehow the dependencies are not resolved hence brew does not completely install. But, try installing by cloning:

git clone https://github.com/Homebrew/linuxbrew.git ~/.linuxbrew

and then add the following to your .bash_profile:

export PATH="$HOME/.linuxbrew/bin:$PATH"
export MANPATH="$HOME/.linuxbrew/share/man:$MANPATH"
export INFOPATH="$HOME/.linuxbrew/share/info:$INFOPATH"

It should work..

.rar, .zip files MIME Type

In a linked question, there's some Objective-C code to get the mime type for a file URL. I've created a Swift extension based on that Objective-C code to get the mime type:

import Foundation
import MobileCoreServices

extension URL {
    var mimeType: String? {
        guard self.pathExtension.count != 0 else {
            return nil
        }

        let pathExtension = self.pathExtension as CFString
        if let preferredIdentifier = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, nil) {
            guard let mimeType = UTTypeCopyPreferredTagWithClass(preferredIdentifier.takeRetainedValue(), kUTTagClassMIMEType) else {
                return nil
            }
            return mimeType.takeRetainedValue() as String
        }

        return nil
    }
}

How to play or open *.mp3 or *.wav sound file in c++ program?

I would use FMOD to do this for your game. It has the ability to play any file mostly for sounds and is pretty simple to implement in C++. using FMOD and Dir3ect X together can be powerful and not that difficult. If you are familiar with Singleton classes I would create a Singleton class of a sound manager in your win main cpp and then have access to it whenever to load or play new music or sound effects. here's an audio manager example

    #pragma once

#ifndef H_AUDIOMANAGER
#define H_AUDIOMANAGER

#include <string>
#include <Windows.h>
#include "fmod.h"
#include "fmod.hpp"
#include "fmod_codec.h"
#include "fmod_dsp.h"
#include "fmod_errors.h"
#include "fmod_memoryinfo.h"
#include "fmod_output.h"

class AudioManager
{
public:
    // Destructor
    ~AudioManager(void);

    void Initialize(void);  // Initialize sound components
    void Shutdown(void);    // Shutdown sound components

    // Singleton instance manip methods
    static AudioManager* GetInstance(void);
    static void DestroyInstance(void);

    // Accessors
    FMOD::System* GetSystem(void)
        {return soundSystem;}

    // Sound playing
    void Play(FMOD::Sound* sound);  // Play a sound/music with default channel
    void PlaySFX(FMOD::Sound* sound);   // Play a sound effect with custom channel
    void PlayBGM(FMOD::Sound* sound);   // Play background music with custom channel

    // Volume adjustment methods
    void SetBGMVolume(float volume);
    void SetSFXVolume(float volume);

private:
    static AudioManager* instance;  // Singleton instance
    AudioManager(void);  // Constructor

    FMOD::System* soundSystem;  // Sound system object
    FMOD_RESULT result;
    FMOD::Channel* bgmChannel;  // Channel for background music
    static const int numSfxChannels = 4;
    FMOD::Channel* sfxChannels[numSfxChannels]; // Channel for sound effects
};

#endif

How to format string to money

you will need to convert it to a decimal first, then format it with money format.

EX:

decimal decimalMoneyValue = 1921.39m;
string formattedMoneyValue = String.Format("{0:C}", decimalMoneyValue);

a working example: https://dotnetfiddle.net/soxxuW

Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error

Intelephense 1.3 added undefined type, function, constant, class constant, method, and property diagnostics, where previously in 1.2 there was only undefined variable diagnostics.

Some frameworks are written in a way that provide convenient shortcuts for the user but make it difficult for static analysis engines to discover symbols that are available at runtime.

Stub generators like https://github.com/barryvdh/laravel-ide-helper help fill the gap here and using this with Laravel will take care of many of the false diagnostics by providing concrete definitions of symbols that can be easily discovered.

Still, PHP is a very flexible language and there may be other instances of false undefined symbols depending on how code is written. For this reason, since 1.3.3, intelephense has config options to enable/disable each category of undefined symbol to suit the workspace and coding style.

These options are: intelephense.diagnostics.undefinedTypes intelephense.diagnostics.undefinedFunctions intelephense.diagnostics.undefinedConstants intelephense.diagnostics.undefinedClassConstants intelephense.diagnostics.undefinedMethods intelephense.diagnostics.undefinedProperties intelephense.diagnostics.undefinedVariables

Setting all of these to false except intelephense.diagnostics.undefinedVariables will give version 1.2 behaviour. See the VSCode settings UI and search for intelephense.

How to use setArguments() and getArguments() methods in Fragments?

Instantiating the Fragment the correct way!

getArguments() setArguments() methods seem very useful when it comes to instantiating a Fragment using a static method.
ie Myfragment.createInstance(String msg)

How to do it?

Fragment code

public MyFragment extends Fragment {

    private String displayMsg;
    private TextView text;

    public static MyFragment createInstance(String displayMsg)
    {
        MyFragment fragment = new MyFragment();
        Bundle args = new Bundle();
        args.setString("KEY",displayMsg);
        fragment.setArguments(args);           //set
        return fragment;
    }

    @Override
    public void onCreate(Bundle bundle)
    {
        displayMsg = getArguments().getString("KEY"):    // get 
    }

    @Override
    public View onCreateView(LayoutInlater inflater, ViewGroup parent, Bundle bundle){
        View view = inflater.inflate(R.id.placeholder,parent,false);
        text = (TextView)view.findViewById(R.id.myTextView);
        text.setText(displayMsg)    // show msg
        returm view;
   }

}

Let's say you want to pass a String while creating an Instance. This is how you will do it.

MyFragment.createInstance("This String will be shown in textView");

Read More

1) Why Myfragment.getInstance(String msg) is preferred over new MyFragment(String msg)?
2) Sample code on Fragments

Best way to Format a Double value to 2 Decimal places

No, there is no better way.

Actually you have an error in your pattern. What you want is:

DecimalFormat df = new DecimalFormat("#.00"); 

Note the "00", meaning exactly two decimal places.

If you use "#.##" (# means "optional" digit), it will drop trailing zeroes - ie new DecimalFormat("#.##").format(3.0d); prints just "3", not "3.00".

SSH to Vagrant box in Windows?

The vagrant installation folder contains an ssh.exe that behaves like ssh(1) on linux (takes the same flags/arguments).

To see all of the arguments used, you can run vagrant ssh-config or vagrant ssh --debug for a more verbose output.

from Powershell:

C:\\HashiCorp\\Vagrant\\embedded\\usr\\bin/ssh.EXE [email protected] -p 2222 -o LogLevel=FATAL -o DSAAuthentication=yes -o Strict
HostKeyChecking=no -i "C:/Users/path/to/project/.vagrant/machines/default/virtualbox/private_key"

This is useful is situations where vagrant status says your vm is in poweroff or suspended mode when you're positive it actually is running, to force ssh connection.

If you don't want to remember/type the above command, juste write it in a vagrant.ps1 file so you can execute it from your powershell using .\vagrant_ssh.ps1

How to make a new List in Java

One example:

List somelist = new ArrayList();

You can look at the javadoc for List and find all known implementing classes of the List interface that are included with the java api.

Drop multiple columns in pandas

Try this

df.drop(df.iloc[:, 1:69], inplace=True, axis=1)

This works for me

Which version of MVC am I using?

Well just use MvcDiagnostics.aspx It shows lots information about current MVC instalations, and also helps with debuging. You can find it in MVC source or just Google for it.

How can I write an anonymous function in Java?

Yes if you are using latest java which is version 8. Java8 make it possible to define anonymous functions which was impossible in previous versions.

Lets take example from java docs to get know how we can declare anonymous functions, classes

The following example, HelloWorldAnonymousClasses, uses anonymous classes in the initialization statements of the local variables frenchGreeting and spanishGreeting, but uses a local class for the initialization of the variable englishGreeting:

public class HelloWorldAnonymousClasses {

    interface HelloWorld {
        public void greet();
        public void greetSomeone(String someone);
    }

    public void sayHello() {

        class EnglishGreeting implements HelloWorld {
            String name = "world";
            public void greet() {
                greetSomeone("world");
            }
            public void greetSomeone(String someone) {
                name = someone;
                System.out.println("Hello " + name);
            }
        }

        HelloWorld englishGreeting = new EnglishGreeting();

        HelloWorld frenchGreeting = new HelloWorld() {
            String name = "tout le monde";
            public void greet() {
                greetSomeone("tout le monde");
            }
            public void greetSomeone(String someone) {
                name = someone;
                System.out.println("Salut " + name);
            }
        };

        HelloWorld spanishGreeting = new HelloWorld() {
            String name = "mundo";
            public void greet() {
                greetSomeone("mundo");
            }
            public void greetSomeone(String someone) {
                name = someone;
                System.out.println("Hola, " + name);
            }
        };
        englishGreeting.greet();
        frenchGreeting.greetSomeone("Fred");
        spanishGreeting.greet();
    }

    public static void main(String... args) {
        HelloWorldAnonymousClasses myApp =
            new HelloWorldAnonymousClasses();
        myApp.sayHello();
    }            
}

Syntax of Anonymous Classes

Consider the instantiation of the frenchGreeting object:

    HelloWorld frenchGreeting = new HelloWorld() {
        String name = "tout le monde";
        public void greet() {
            greetSomeone("tout le monde");
        }
        public void greetSomeone(String someone) {
            name = someone;
            System.out.println("Salut " + name);
        }
    };

The anonymous class expression consists of the following:

  • The new operator
  • The name of an interface to implement or a class to extend. In this example, the anonymous class is implementing the interface HelloWorld.

  • Parentheses that contain the arguments to a constructor, just like a normal class instance creation expression. Note: When you implement an interface, there is no constructor, so you use an empty pair of parentheses, as in this example.

  • A body, which is a class declaration body. More specifically, in the body, method declarations are allowed but statements are not.

Windows batch - concatenate multiple text files into one

We can use normal CAT command to merge files..

D:> cat *.csv > outputs.csv

Calculating how many minutes there are between two times

double minutes = varTime.TotalMinutes;
int minutesRounded = (int)Math.Round(varTime.TotalMinutes);

TimeSpan.TotalMinutes: The total number of minutes represented by this instance.

Getting the minimum of two values in SQL

The solutions using CASE, IIF, and UDF are adequate, but impractical when extending the problem to the general case using more than 2 comparison values. The generalized solution in SQL Server 2008+ utilizes a strange application of the VALUES clause:

SELECT
PaidForPast=(SELECT MIN(x) FROM (VALUES (PaidThisMonth),(OwedPast)) AS value(x))

Credit due to this website: http://sqlblog.com/blogs/jamie_thomson/archive/2012/01/20/use-values-clause-to-get-the-maximum-value-from-some-columns-sql-server-t-sql.aspx

How to parse JSON Array (Not Json Object) in Android

My case Load From Server Example..

int jsonLength = Integer.parseInt(jsonObject.getString("number_of_messages"));
            if (jsonLength != 1) {
                for (int i = 0; i < jsonLength; i++) {
                    JSONArray jsonArray = new JSONArray(jsonObject.getString("messages"));
                    JSONObject resJson = (JSONObject) jsonArray.get(i);
                    //addItem(resJson.getString("message"), resJson.getString("name"), resJson.getString("created_at"));
                }

Hope it help

ReferenceError: event is not defined error in Firefox

It is because you forgot to pass in event into the click function:

$('.menuOption').on('click', function (e) { // <-- the "e" for event

    e.preventDefault(); // now it'll work

    var categories = $(this).attr('rel');
    $('.pages').hide();
    $(categories).fadeIn();
});

On a side note, e is more commonly used as opposed to the word event since Event is a global variable in most browsers.

Getting path relative to the current working directory?

There is also a way to do this with some restrictions. This is the code from the article:

public string RelativePath(string absPath, string relTo)
    {
        string[] absDirs = absPath.Split('\\');
        string[] relDirs = relTo.Split('\\');
        // Get the shortest of the two paths 
        int len = absDirs.Length < relDirs.Length ? absDirs.Length : relDirs.Length;
        // Use to determine where in the loop we exited 
        int lastCommonRoot = -1; int index;
        // Find common root 
        for (index = 0; index < len; index++)
        {
            if (absDirs[index] == relDirs[index])
                lastCommonRoot = index;
            else break;
        }
        // If we didn't find a common prefix then throw 
        if (lastCommonRoot == -1)
        {
            throw new ArgumentException("Paths do not have a common base");
        }
        // Build up the relative path 
        StringBuilder relativePath = new StringBuilder();
        // Add on the .. 
        for (index = lastCommonRoot + 1; index < absDirs.Length; index++)
        {
            if (absDirs[index].Length > 0) relativePath.Append("..\\");
        }
        // Add on the folders 
        for (index = lastCommonRoot + 1; index < relDirs.Length - 1; index++)
        {
            relativePath.Append(relDirs[index] + "\\");
        }
        relativePath.Append(relDirs[relDirs.Length - 1]);
        return relativePath.ToString();
    }

When executing this piece of code:

string path1 = @"C:\Inetpub\wwwroot\Project1\Master\Dev\SubDir1"; 
string path2 = @"C:\Inetpub\wwwroot\Project1\Master\Dev\SubDir2\SubDirIWant";

System.Console.WriteLine (RelativePath(path1, path2));
System.Console.WriteLine (RelativePath(path2, path1));

it prints out:

..\SubDir2\SubDirIWant
..\..\SubDir1

How do I create a custom Error in JavaScript?

I just had to implement something like this and found that the stack was lost in my own error implementation. What I had to do was create a dummy error and retrieve the stack from that:

My.Error = function (message, innerException) {
    var err = new Error();
    this.stack = err.stack; // IMPORTANT!
    this.name = "Error";
    this.message = message;
    this.innerException = innerException;
}
My.Error.prototype = new Error();
My.Error.prototype.constructor = My.Error;
My.Error.prototype.toString = function (includeStackTrace) {
    var msg = this.message;
    var e = this.innerException;
    while (e) {
        msg += " The details are:\n" + e.message;
        e = e.innerException;
    }
    if (includeStackTrace) {
        msg += "\n\nStack Trace:\n\n" + this.stack;
    }
    return msg;
}

Separators for Navigation

If there isn't a pressing need to use images for the separators, you could do this with pure CSS.

nav li + li:before{
    content: " | ";
    padding: 0 10px;
}

This puts a bar between each list item, just as the image in the original question described. But since we're using the adjacent selectors, it doesn't put the bar before the first element. And since we're using the :before pseudo selector, it doesn't put one at the end.

Could not establish trust relationship for SSL/TLS secure channel -- SOAP

Microsoft's SSL Diagnostics Tool may be able to help identify the issue.

UPDATE the link has been fixed now.

How do I get the current username in Windows PowerShell?

I thought it would be valuable to summarize and compare the given answers.

If you want to access the environment variable:

(easier/shorter/memorable option)

  • [Environment]::UserName -- @ThomasBratt
  • $env:username -- @Eoin
  • whoami -- @galaktor

If you want to access the Windows access token:

(more dependable option)

  • [System.Security.Principal.WindowsIdentity]::GetCurrent().Name -- @MarkSeemann

If you want the name of the logged in user

(rather than the name of the user running the PowerShell instance)

  • $(Get-WMIObject -class Win32_ComputerSystem | select username).username -- @TwonOfAn on this other forum

Comparison

@Kevin Panko's comment on @Mark Seemann's answer deals with choosing one of the categories over the other:

[The Windows access token approach] is the most secure answer, because $env:USERNAME can be altered by the user, but this will not be fooled by doing that.

In short, the environment variable option is more succinct, and the Windows access token option is more dependable.

I've had to use @Mark Seemann's Windows access token approach in a PowerShell script that I was running from a C# application with impersonation.

The C# application is run with my user account, and it runs the PowerShell script as a service account. Because of a limitation of the way I'm running the PowerShell script from C#, the PowerShell instance uses my user account's environment variables, even though it is run as the service account user.

In this setup, the environment variable options return my account name, and the Windows access token option returns the service account name (which is what I wanted), and the logged in user option returns my account name.


Testing

Also, if you want to compare the options yourself, here is a script you can use to run a script as another user. You need to use the Get-Credential cmdlet to get a credential object, and then run this script with the script to run as another user as argument 1, and the credential object as argument 2.

Usage:

$cred = Get-Credential UserTo.RunAs
Run-AsUser.ps1 "whoami; pause" $cred
Run-AsUser.ps1 "[System.Security.Principal.WindowsIdentity]::GetCurrent().Name; pause" $cred

Contents of Run-AsUser.ps1 script:

param(
  [Parameter(Mandatory=$true)]
  [string]$script,
  [Parameter(Mandatory=$true)]
  [System.Management.Automation.PsCredential]$cred
)

Start-Process -Credential $cred -FilePath 'powershell.exe' -ArgumentList 'noprofile','-Command',"$script"

SQL Server function to return minimum date (January 1, 1753)

Have you seen the SqlDateTime object? use SqlDateTime.MinValue to get your minimum date (Jan 1 1753).

How to clear cache in Yarn?

Also note that the cached directory is located in ~/.yarn-cache/:

yarn cache clean: cleans that directory

yarn cache list: shows the list of cached dependencies

yarn cache dir: prints out the path of your cached directory

Pass arguments into C program from command line

Take a look at the getopt library; it's pretty much the gold standard for this sort of thing.

Is there a good reason I see VARCHAR(255) used so often (as opposed to another length)?

In many applications, like MsOffice (until version 2000 or 2002), the maximum number of characters per cell was 255. Moving data from programs able of handling more than 255 characters per field to/from those applications was a nightmare. Currently, the limit is less and less hindering.

java.net.BindException: Address already in use: JVM_Bind <null>:80

If you have some process listening on port 8080 then you can always configure tomcat to listen on a different port. To change the listener port by editing your server.xml located under tomcat server conf directory.

Search for Connector port="8080" in server.xml and change the port number to some other port.

Difference between request.getSession() and request.getSession(true)

Method with boolean argument :

  request.getSession(true);

returns new session, if the session is not associated with the request

  request.getSession(false);

returns null, if the session is not associated with the request.

Method without boolean argument :

  request.getSession();

returns new session, if the session is not associated with the request and returns the existing session, if the session is associated with the request.It won't return null.

Detect click outside Angular component

ginalx's answer should be set as the default one imo: this method allows for many optimizations.

The problem

Say that we have a list of items and on every item we want to include a menu that needs to be toggled. We include a toggle on a button that listens for a click event on itself (click)="toggle()", but we also want to toggle the menu whenever the user clicks outside of it. If the list of items grows and we attach a @HostListener('document:click') on every menu, then every menu loaded within the item will start listening for the click on the entire document, even when the menu is toggled off. Besides the obvious performance issues, this is unnecessary.

You can, for example, subscribe whenever the popup gets toggled via a click and start listening for "outside clicks" only then.


isActive: boolean = false;

// to prevent memory leaks and improve efficiency, the menu
// gets loaded only when the toggle gets clicked
private _toggleMenuSubject$: BehaviorSubject<boolean>;
private _toggleMenu$: Observable<boolean>;

private _toggleMenuSub: Subscription;
private _clickSub: Subscription = null;


constructor(
 ...
 private _utilitiesService: UtilitiesService,
 private _elementRef: ElementRef,
){
 ...
 this._toggleMenuSubject$ = new BehaviorSubject(false);
 this._toggleMenu$ = this._toggleMenuSubject$.asObservable();

}

ngOnInit() {
 this._toggleMenuSub = this._toggleMenu$.pipe(
      tap(isActive => {
        logger.debug('Label Menu is active', isActive)
        this.isActive = isActive;

        // subscribe to the click event only if the menu is Active
        // otherwise unsubscribe and save memory
        if(isActive === true){
          this._clickSub = this._utilitiesService.documentClickedTarget
           .subscribe(target => this._documentClickListener(target));
        }else if(isActive === false && this._clickSub !== null){
          this._clickSub.unsubscribe();
        }

      }),
      // other observable logic
      ...
      ).subscribe();
}

toggle() {
    this._toggleMenuSubject$.next(!this.isActive);
}

private _documentClickListener(targetElement: HTMLElement): void {
    const clickedInside = this._elementRef.nativeElement.contains(targetElement);
    if (!clickedInside) {
      this._toggleMenuSubject$.next(false);
    }    
 }

ngOnDestroy(){
 this._toggleMenuSub.unsubscribe();
}

And, in *.component.html:


<button (click)="toggle()">Toggle the menu</button>

How to set environment variables in Python?

You should assign string value to environment variable.

os.environ["DEBUSSY"] = "1"

If you want to read or print the environment variable just use

print os.environ["DEBUSSY"]

This changes will be effective only for the current process where it was assigned, it will no change the value permanently. The child processes will automatically inherit the environment of the parent process.

enter image description here

Count number of columns in a table row

<table id="table1">
<tr>
  <td colspan=4><input type="text" value="" /></td>

</tr>
<tr>
  <td><input type="text" value="" /></td>
  <td><input type="text" value="" /></td>
  <td><input type="text" value="" /></td>
  <td><input type="text" value="" /></td>

</tr>
<table>
<script>
    var row=document.getElementById('table1').rows.length;
    for(i=0;i<row;i++){
    console.log('Row '+parseFloat(i+1)+' : '+document.getElementById('table1').rows[i].cells.length +' column');
    }
</script>

Result:

Row 1 : 1 column
Row 2 : 4 column

How to create a String with carriage returns?

It depends on what you mean by "multiple lines". Different operating systems use different line separators.

In Java, \r is always carriage return, and \n is line feed. On Unix, just \n is enough for a newline, whereas many programs on Windows require \r\n. You can get at the platform default newline use System.getProperty("line.separator") or use String.format("%n") as mentioned in other answers.

But really, you need to know whether you're trying to produce OS-specific newlines - for example, if this is text which is going to be transmitted as part of a specific protocol, then you should see what that protocol deems to be a newline. For example, RFC 2822 defines a line separator of \r\n and this should be used even if you're running on Unix. So it's all about context.

XAMPP Apache won't start

If it helps to anyone, I currently use VMWare Workstation in my computer, and it also blocks Apache from starting, because VMWare Workstation listens for requests on port 443.

You can either comment out "listen 443" inside the "httpd-ssl.config" or you can disable "Shared VMs" from VMWare Workstation General Preferences.

Get commit list between tags in git

If your team uses descriptive commit messages (eg. "Ticket #12345 - Update dependencies") on this project, then generating changelog since the latest tag can de done like this:

git log --no-merges --pretty=format:"%s" 'old-tag^'...new-tag > /path/to/changelog.md
  • --no-merges omits the merge commits from the list
  • old-tag^ refers to the previous commit earlier than the tagged one. Useful if you want to see the tagged commit at the bottom of the list by any reason. (Single quotes needed only for iTerm on mac OS).

jQuery to serialize only elements within a div

serialize all the form-elements within a div.

You could do that by targeting the div #target-div-id inside your form using :

$('#target-div-id').find('select, textarea, input').serialize();

How to set background color of view transparent in React Native

Surprisingly no one told about this, which provides some !clarity:

style={{
backgroundColor: 'white',
opacity: 0.7
}}

Import Maven dependencies in IntelliJ IDEA

In maven the dependencies got included for me when I removed the dependencyManagement xml section and just had dependencies directly under project section

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

SOLUTION for WORDPRESS PLUGINS:

I think, get_option() returns FALSE (instead of EMPTY). So, check your plugin. Instead of:

if (empty(get_option('smth')))

there should be:

if (!get_option('smth'))

What is the @Html.DisplayFor syntax for?

After looking for an answer for myself for some time, i could find something. in general if we are using it for just one property it appears same even if we do a "View Source" of generated HTML Below is generated HTML for example, when i want to display only Name property for my class

    <td>
    myClassNameProperty
    </td>
   <td>
    myClassNameProperty, This is direct from Item
    </td>

This is the generated HTML from below code

<td>
@Html.DisplayFor(modelItem=>item.Genre.Name)            
</td>

<td>
@item.Genre.Name, This is direct from Item
</td>

At the same time now if i want to display all properties in one statement for my class "Genre" in this case, i can use @Html.DisplayFor() to save on my typing, for least

i can write @Html.DisplayFor(modelItem=>item.Genre) in place of writing a separate statement for each property of Genre as below

@item.Genre.Name
@item.Genre.Id
@item.Genre.Description

and so on depending on number of properties.

Pandas/Python: Set value of one column based on value in another column

I had a big dataset and .loc[] was taking too long so I found a vectorized way to do it. Recall that you can set a column to a logical operator, so this works:

file['Flag'] = (file['Claim_Amount'] > 0)

This gives a Boolean, which I wanted, but you can multiply it by, say, 1 to make an Integer.

Remove specific rows from a data frame

 X <- data.frame(Variable1=c(11,14,12,15),Variable2=c(2,3,1,4))
> X
  Variable1 Variable2
1        11         2
2        14         3
3        12         1
4        15         4
> X[X$Variable1!=11 & X$Variable1!=12, ]
  Variable1 Variable2
2        14         3
4        15         4
> X[ ! X$Variable1 %in% c(11,12), ]
  Variable1 Variable2
2        14         3
4        15         4

You can functionalize this however you like.

How to modify existing, unpushed commit messages?

Update your last wrong commit message with the new commit message in one line:

git commit --amend -m "your new commit message"

Or, try Git reset like below:

# You can reset your head to n number of commit
# NOT a good idea for changing last commit message,
# but you can get an idea to split commit into multiple commits
git reset --soft HEAD^

# It will reset you last commit. Now, you
# can re-commit it with new commit message.

Using reset to split commits into smaller commits

git reset can help you to break one commit into multiple commits too:

# Reset your head. I am resetting to last commits:
git reset --soft HEAD^
# (You can reset multiple commit by doing HEAD~2(no. of commits)

# Now, reset your head for splitting it to multiple commits
git reset HEAD

# Add and commit your files separately to make multiple commits: e.g
git add app/
git commit -m "add all files in app directory"

git add config/
git commit -m "add all files in config directory"

Here you have successfully broken your last commit into two commits.

How can I read command line parameters from an R script?

A few points:

  1. Command-line parameters are accessible via commandArgs(), so see help(commandArgs) for an overview.

  2. You can use Rscript.exe on all platforms, including Windows. It will support commandArgs(). littler could be ported to Windows but lives right now only on OS X and Linux.

  3. There are two add-on packages on CRAN -- getopt and optparse -- which were both written for command-line parsing.

Edit in Nov 2015: New alternatives have appeared and I wholeheartedly recommend docopt.

how to find my angular version in my project?

ng --version command will show only the installed angular version in your computer instead of the actual project version.

if you really want to know the project version, Go to your project, use the below command

npm list -local

enter image description here

Installing pip packages to $HOME folder

You can specify the -t option (--target) to specify the destination directory. See pip install --help for detailed information. This is the command you need:

pip install -t path_to_your_home package-name

for example, for installing say mxnet, in my $HOME directory, I type:

pip install -t /home/foivos/ mxnet

How to get rid of underline for Link component of React Router?

Working for me, just add className="nav-link" and activeStyle{{textDecoration:'underline'}}

<NavLink className="nav-link" to="/" exact activeStyle= 
  {{textDecoration:'underline'}}>My Record</NavLink>

Mongoose, update values in array of objects

I had similar issues. Here is the cleanest way to do it.

    const personQuery = {
       _id: 1  
    }

    const itemID = 2;

    Person.findOne(personQuery).then(item => {
       const audioIndex = item.items.map(item => item.id).indexOf(itemID);
       item.items[audioIndex].name = 'Name value';
       item.save();
    });

How do I compare two strings in Perl?

And if you'd like to extract the differences between the two strings, you can use String::Diff.

Start HTML5 video at a particular position when loading?

adjust video start and end time when using the video tag in html5;

http://www.yoursite.com/yourfolder/yourfile.mp4#t=5,15

where left of comma is start time in seconds, right of comma is end time in seconds. drop the comma and end time to effect the start time only.

How to deal with the URISyntaxException

A space is encoded to %20 in URLs, and to + in forms submitted data (content type application/x-www-form-urlencoded). You need the former.

Using Guava:

dependencies {
     compile 'com.google.guava:guava:28.1-jre'
}

You can use UrlEscapers:

String encodedString = UrlEscapers.urlFragmentEscaper().escape(inputString);

Don't use String.replace, this would only encode the space. Use a library instead.

Set LIMIT with doctrine 2?

 $qb = $this->getDoctrine()->getManager()->createQueryBuilder();  
 $qb->select('p') ->from('Pandora\UserBundle\Entity\PhoneNumber', 'p');
$qb->where('p.number = :number');
$qb->OrWhere('p.validatedNumber=:number');
$qb->setMaxResults(1);
$qb->setParameter('number',$postParams['From'] );
$result = $qb->getQuery()->getResult();
 $data=$result[0];

How to save the contents of a div as a image?

Do something like this:

A <div> with ID of #imageDIV, another one with ID #download and a hidden <div> with ID #previewImage.

Include the latest version of jquery, and jspdf.debug.js from the jspdf CDN

Then add this script:

var element = $("#imageDIV"); // global variable
var getCanvas; // global variable
$('document').ready(function(){
  html2canvas(element, {
    onrendered: function (canvas) {
      $("#previewImage").append(canvas);
      getCanvas = canvas;
    }
  });
});
$("#download").on('click', function () {
  var imgageData = getCanvas.toDataURL("image/png");
  // Now browser starts downloading it instead of just showing it
  var newData = imageData.replace(/^data:image\/png/, "data:application/octet-stream");
  $("#download").attr("download", "image.png").attr("href", newData);
});

The div will be saved as a PNG on clicking the #download

Put icon inside input element in a form

You can try this:

input[type='text'] {
    background-image: url(images/comment-author.gif);
    background-position: 7px 7px;
    background-repeat: no-repeat;
}

How to configure encoding in Maven?

OK, I have found the problem.

I use some reporting plugins. In the documentation of the failsafe-maven-plugin I found, that the <encoding> configuration - of course - uses ${project.reporting.outputEncoding} by default.

So I added the property as a child element of the project element and everything is fine now:

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>

See also http://maven.apache.org/general.html#encoding-warning

Force page scroll position to top at page refresh in HTML

The answer here does not works for safari, document.ready is often fired too early.

Ought to use the beforeunload event which prevent you form doing some setTimeout

$(window).on('beforeunload', function(){
  $(window).scrollTop(0);
});

How to prevent vim from creating (and leaving) temporary files?

; For Windows Users to back to temp directory

set backup
set backupdir=C:\WINDOWS\Temp
set backupskip=C:\WINDOWS\Temp\*
set directory=C:\WINDOWS\Temp
set writebackup

Disable future dates in jQuery UI Datepicker

$('#thedate,#dateid').datepicker({
     changeMonth:true,
         changeYear:true,
         yearRange:"-100:+0",
         dateFormat:"dd/mm/yy" ,
         maxDate: '0',
     });
});

Resetting a setTimeout

You will have to remember the timeout "Timer", cancel it, then restart it:

g_timer = null;

$(document).ready(function() {
    startTimer();
});

function startTimer() {
    g_timer = window.setTimeout(function() {
        window.location.href = 'file.php';
    }, 115000);
}

function onClick() {
    clearTimeout(g_timer);
    startTimer();
}

diff to output only the file names

You can also use rsync

rsync -rv --size-only --dry-run /my/source/ /my/dest/ > diff.out

python save image from url

import urllib.request
import os

img_url = "https://betanews.com/wp-content/uploads/2017/09/firefox-logo.jpg"
img_name = os.path.basename(img_url)
urllib.request.urlretrieve(img_url,img_name)

Tools to get a pictorial function call graph of code

You can check out my bash-based C call tree generator here. It lets you specify one or more C functions for which you want caller and/or called information, or you can specify a set of functions and determine the reachability graph of function calls that connects them... I.e. tell me all the ways main(), foo(), and bar() are connected. It uses graphviz/dot for a graphing engine.

Spring can you autowire inside an abstract class?

What if you need any database operation in SuperGirl you would inject it again into SuperGirl.

I think the main idea is using the same object reference in different classes. So what about this:

//There is no annotation about Spring in the abstract part.
abstract class SuperMan {


    private final DatabaseService databaseService;

    public SuperMan(DatabaseService databaseService) {
     this.databaseService = databaseService;
    }

    abstract void Fly();

    protected void doSuperPowerAction(Thing thing) {

        //busy code

        databaseService.save(thing);

    }
}

@Component
public class SuperGirl extends SuperMan {

private final DatabaseService databaseService;

@Autowired
public SuperGirl (DatabaseService databaseService) {
     super(databaseService);
     this.databaseService = databaseService;
    }

@Override
public void Fly() {
    //busy code
}

public doSomethingSuperGirlDoes() {

    //busy code

    doSuperPowerAction(thing)

}

In my opinion, inject once run everywhere :)

[Vue warn]: Cannot find element

I've solved the problem by add attribute 'defer' to the 'script' element.

How do I display a MySQL error in PHP for a long query that depends on the user input?

One useful line of code for you would be:

$sql = "Your SQL statement here";
$result = mysqli_query($this->db_link, $sql) or trigger_error("Query Failed! SQL: $sql - Error: ".mysqli_error($this->db_link), E_USER_ERROR);

This method is better than die, because you can use it for development AND production. It's the permanent solution.

Deserialize JSON array(or list) in C#

I was having the similar issue and solved by understanding the Classes in asp.net C#

I want to read following JSON string :

[
    {
        "resultList": [
            {
                "channelType": "",
                "duration": "2:29:30",
                "episodeno": 0,
                "genre": "Drama",
                "genreList": [
                    "Drama"
                ],
                "genres": [
                    {
                        "personName": "Drama"
                    }
                ],
                "id": 1204,
                "language": "Hindi",
                "name": "The Great Target",
                "productId": 1204,
                "productMasterId": 1203,
                "productMasterName": "The Great Target",
                "productName": "The Great Target",
                "productTypeId": 1,
                "productTypeName": "Movie",
                "rating": 3,
                "releaseyear": "2005",
                "showGoodName": "Movies ",
                "views": 8333
            },
            {
                "channelType": "",
                "duration": "2:30:30",
                "episodeno": 0,
                "genre": "Romance",
                "genreList": [
                    "Romance"
                ],
                "genres": [
                    {
                        "personName": "Romance"
                    }
                ],
                "id": 1144,
                "language": "Hindi",
                "name": "Mere Sapnon Ki Rani",
                "productId": 1144,
                "productMasterId": 1143,
                "productMasterName": "Mere Sapnon Ki Rani",
                "productName": "Mere Sapnon Ki Rani",
                "productTypeId": 1,
                "productTypeName": "Movie",
                "rating": 3,
                "releaseyear": "1997",
                "showGoodName": "Movies ",
                "views": 6482
            },
            {
                "channelType": "",
                "duration": "2:34:07",
                "episodeno": 0,
                "genre": "Drama",
                "genreList": [
                    "Drama"
                ],
                "genres": [
                    {
                        "personName": "Drama"
                    }
                ],
                "id": 1520,
                "language": "Telugu",
                "name": "Satyameva Jayathe",
                "productId": 1520,
                "productMasterId": 1519,
                "productMasterName": "Satyameva Jayathe",
                "productName": "Satyameva Jayathe",
                "productTypeId": 1,
                "productTypeName": "Movie",
                "rating": 3,
                "releaseyear": "2004",
                "showGoodName": "Movies ",
                "views": 9910
            }
        ],
        "resultSize": 1171,
        "pageIndex": "1"
    }
]

My asp.net c# code looks like following

First, Class3.cs page created in APP_Code folder of Web application

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Text;
using System.IO;
using System.Web.Script.Serialization;
using System.Collections.Generic;

/// <summary>
/// Summary description for Class3
/// </summary>
public class Class3
{

    public List<ListWrapper_Main> ResultList_Main { get; set; }

    public class ListWrapper_Main
    {
        public List<ListWrapper> ResultList { get; set; }

        public string resultSize { get; set; }
        public string pageIndex { get; set; }
    }

    public class ListWrapper
    {
        public string channelType { get; set; }
        public string duration { get; set; }
        public int episodeno { get; set; }
        public string genre { get; set; }
        public string[] genreList { get; set; }
        public List<genres_cls> genres { get; set; }
        public int id { get; set; }
        public string imageUrl { get; set; }
        //public string imageurl { get; set; }
        public string language { get; set; }
        public string name { get; set; }
        public int productId { get; set; }
        public int productMasterId { get; set; }
        public string productMasterName { get; set; }
        public string productName { get; set; }
        public int productTypeId { get; set; }
        public string productTypeName { get; set; }
        public decimal rating { get; set; }
        public string releaseYear { get; set; }
        //public string releaseyear { get; set; }
        public string showGoodName { get; set; }
        public string views { get; set; }
    }
    public class genres_cls
    {
        public string personName { get; set; }
    }

}

Then, Browser page that reads the string/JSON string listed above and displays/Deserialize the JSON objects and displays the data

JavaScriptSerializer ser = new JavaScriptSerializer();


        string final_sb = sb.ToString();

        List<Class3.ListWrapper_Main> movieInfos = ser.Deserialize<List<Class3.ListWrapper_Main>>(final_sb.ToString());

        foreach (var itemdetail in movieInfos)
        {

            foreach (var itemdetail2 in itemdetail.ResultList)
            {
                Response.Write("channelType=" + itemdetail2.channelType + "<br/>");
                Response.Write("duration=" + itemdetail2.duration + "<br/>");
                Response.Write("episodeno=" + itemdetail2.episodeno + "<br/>");
                Response.Write("genre=" + itemdetail2.genre + "<br/>");

                string[] genreList_arr = itemdetail2.genreList;
                for (int i = 0; i < genreList_arr.Length; i++)
                    Response.Write("genreList1=" + genreList_arr[i].ToString() + "<br>");

                foreach (var genres1 in itemdetail2.genres)
                {
                    Response.Write("genres1=" + genres1.personName + "<br>");
                }

                Response.Write("id=" + itemdetail2.id + "<br/>");
                Response.Write("imageUrl=" + itemdetail2.imageUrl + "<br/>");
                //Response.Write("imageurl=" + itemdetail2.imageurl + "<br/>");
                Response.Write("language=" + itemdetail2.language + "<br/>");
                Response.Write("name=" + itemdetail2.name + "<br/>");
                Response.Write("productId=" + itemdetail2.productId + "<br/>");
                Response.Write("productMasterId=" + itemdetail2.productMasterId + "<br/>");
                Response.Write("productMasterName=" + itemdetail2.productMasterName + "<br/>");
                Response.Write("productName=" + itemdetail2.productName + "<br/>");
                Response.Write("productTypeId=" + itemdetail2.productTypeId + "<br/>");
                Response.Write("productTypeName=" + itemdetail2.productTypeName + "<br/>");
                Response.Write("rating=" + itemdetail2.rating + "<br/>");
                Response.Write("releaseYear=" + itemdetail2.releaseYear + "<br/>");
                //Response.Write("releaseyear=" + itemdetail2.releaseyear + "<br/>");
                Response.Write("showGoodName=" + itemdetail2.showGoodName + "<br/>");
                Response.Write("views=" + itemdetail2.views + "<br/><br>");
                //Response.Write("resultSize" + itemdetail2.resultSize + "<br/>");
                //  Response.Write("pageIndex" + itemdetail2.pageIndex + "<br/>");


            }



            Response.Write("resultSize=" + itemdetail.resultSize + "<br/><br>");
            Response.Write("pageIndex=" + itemdetail.pageIndex + "<br/><br>");

        }

'sb' is the actual string, i.e. JSON string of data mentioned very first on top of this reply

This is basically - web application asp.net c# code....

N joy...

How to NodeJS require inside TypeScript file?

Use typings to access node functions from TypeScript:

typings install env~node --global

If you don't have typings install it:

npm install typings --global

Only local connections are allowed Chrome and Selenium webdriver

I followed my frnd suggestion and it worked like a gem for me:

Working Code:

1) Downloaded chromedriver.

2) Code is

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

public class Sel {
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    System.setProperty("webdriver.chrome.driver", "C:\\Users\\Downloads\\chromedriver_win32\\chromedriver.exe"); // path of chromedriver 
    WebDriver driver = new ChromeDriver();

      driver.get("https://google.ca");
      driver.manage().window().maximize();
      driver.getTitle();

  }
}

Connect Bluestacks to Android Studio

Steps to connect Blue Stack with Android Studio

  1. Close Android Studio.
  2. Go to adb.exe location (default location: %LocalAppData%\Android\sdk\platform-tools)
  3. Run adb connect localhost:5555 from this location.
  4. Start Android Studio and you will get Blue Stack as emulator when you run your app.

SQL 'like' vs '=' performance

You are asking the wrong question. In databases is not the operator performance that matters, is always the SARGability of the expression, and the coverability of the overall query. Performance of the operator itself is largely irrelevant.

So, how do LIKE and = compare in terms of SARGability? LIKE, when used with an expression that does not start with a constant (eg. when used LIKE '%something') is by definition non-SARGabale. But does that make = or LIKE 'something%' SARGable? No. As with any question about SQL performance the answer does not lie with the query of the text, but with the schema deployed. These expression may be SARGable if an index exists to satisfy them.

So, truth be told, there are small differences between = and LIKE. But asking whether one operator or other operator is 'faster' in SQL is like asking 'What goes faster, a red car or a blue car?'. You should eb asking questions about the engine size and vechicle weight, not about the color... To approach questions about optimizing relational tables, the place to look is your indexes and your expressions in the WHERE clause (and other clauses, but it usually starts with the WHERE).

Copy files from one directory into an existing directory

cp dir1/* dir2

Or if you have directories inside dir1 that you'd want to copy as well

cp -r dir1/* dir2

Is returning out of a switch statement considered a better practice than using break?

A break will allow you continue processing in the function. Just returning out of the switch is fine if that's all you want to do in the function.

How to get a value inside an ArrayList java

import java.util.*;
import java.lang.*;
import java.io.*;

class hari
{
public static void main (String[] args) throws Exception
{  Scanner s=new Scanner(System.in);
    int i=0;
    int b=0;
    HashSet<Integer> h=new HashSet<Integer>();
    try{
        for(i=0;i<1000;i++)
    {   b=s.nextInt();
        h.add(b);
    }
    }
    catch(Exception e){
        System.out.println(h+","+h.size());
    }
}}

How do I set specific environment variables when debugging in Visual Studio?

If you can't use bat files to set up your environment, then your only likely option is to set up a system wide environment variable. You can find these by doing

  1. Right click "My Computer"
  2. Select properties
  3. Select the "advanced" tab
  4. Click the "environment variables" button
  5. In the "System variables" section, add the new environment variable that you desire
  6. "Ok" all the way out to accept your changes

I don't know if you'd have to restart visual studio, but seems unlikely. HTH

How do you test a public/private DSA keypair?

I always compare an MD5 hash of the modulus using these commands:

Certificate: openssl x509 -noout -modulus -in server.crt | openssl md5
Private Key: openssl rsa -noout -modulus -in server.key | openssl md5
CSR: openssl req -noout -modulus -in server.csr | openssl md5

If the hashes match, then those two files go together.

How to write loop in a Makefile?

THE major reason to use make IMHO is the -j flag. make -j5 will run 5 shell commands at once. This is good if you have 4 CPUs say, and a good test of any makefile.

Basically, you want make to see something like:

.PHONY: all
all: job1 job2 job3

.PHONY: job1
job1: ; ./a.out 1

.PHONY: job2
job2: ; ./a.out 2

.PHONY: job3
job3: ; ./a.out 3

This is -j friendly (a good sign). Can you spot the boiler-plate? We could write:

.PHONY: all job1 job2 job3
all: job1 job2 job3
job1 job2 job3: job%:
    ./a.out $*

for the same effect (yes, this is the same as the previous formulation as far as make is concerned, just a bit more compact).

A further bit of parameterisation so that you can specify a limit on the command-line (tedious as make does not have any good arithmetic macros, so I'll cheat here and use $(shell ...))

LAST := 1000
NUMBERS := $(shell seq 1 ${LAST})
JOBS := $(addprefix job,${NUMBERS})
.PHONY: all ${JOBS}
all: ${JOBS} ; echo "$@ success"
${JOBS}: job%: ; ./a.out $*

You run this with make -j5 LAST=550, with LAST defaulting to 1000.

How to check if a variable is set in Bash?

Declare a simple function is_set which uses declare -p to test directly if the variable exists.

$ is_set() {
    declare -p $1 >/dev/null 2>&1
}

$ is_set foo; echo $?
0

$ declare foo

$ is_set foo; echo $?
1

How to use putExtra() and getExtra() for string data

This is what i have been using, hopfully it helps someone.. simple and affective.

send data

    intent = new Intent(getActivity(), CheckinActivity.class);
    intent.putExtra("mealID", meal.Meald);
    startActivity(intent);

get data

    int mealId;

    Intent intent = getIntent();
    Bundle bundle = intent.getExtras();

    if(bundle != null){
        mealId = bundle.getInt("mealID");
    }

cheers!

Default value for field in Django model

Set editable to False and default to your default value.

http://docs.djangoproject.com/en/stable/ref/models/fields/#editable

b = models.CharField(max_length=7, default='0000000', editable=False)

Also, your id field is unnecessary. Django will add it automatically.

Differences between Microsoft .NET 4.0 full Framework and Client Profile

Cameron MacFarland nailed it.

I'd like to add that the .NET 4.0 client profile will be included in Windows Update and future Windows releases. Expect most computers to have the client profile, not the full profile. Do not underestimate that fact if you're doing business-to-consumer (B2C) sales.

Convert String to Integer in XSLT 1.0

Adding to jelovirt's answer, you can use number() to convert the value to a number, then round(), floor(), or ceiling() to get a whole integer.

Example

<xsl:variable name="MyValAsText" select="'5.14'"/>
<xsl:value-of select="number($MyValAsText) * 2"/> <!-- This outputs 10.28 -->
<xsl:value-of select="floor($MyValAsText)"/> <!-- outputs 5 -->
<xsl:value-of select="ceiling($MyValAsText)"/> <!-- outputs 6 -->
<xsl:value-of select="round($MyValAsText)"/> <!-- outputs 5 -->

java.sql.SQLException Parameter index out of range (1 > number of parameters, which is 0)

This is an issue with the jdbc Driver version. I had this issue when I was using mysql-connector-java-commercial-5.0.3-bin.jar but when I changed to a later driver version mysql-connector-java-5.1.22.jar, the issue was fixed.

How to get a float result by dividing two integer values using T-SQL?

If you came here (just like me) to find the solution for integer value, here is the answer:

CAST(9/2 AS UNSIGNED)

returns 5

How to show a running progress bar while page is loading

Take a look here,

html file

<div class='progress' id="progress_div">
   <div class='bar' id='bar1'></div>
   <div class='percent' id='percent1'></div>
</div>

<div id="wrapper">
   <div id="content">
     <h1>Display Progress Bar While Page Loads Using jQuery<p>TalkersCode.com</p></h1>
   </div>
</div>

js file

document.onreadystatechange = function(e) {
  if (document.readyState == "interactive") {
    var all = document.getElementsByTagName("*");
    for (var i = 0, max = all.length; i < max; i++) {
      set_ele(all[i]);
    }
  }
}

function check_element(ele) {
  var all = document.getElementsByTagName("*");
  var totalele = all.length;
  var per_inc = 100 / all.length;

  if ($(ele).on()) {
    var prog_width = per_inc + Number(document.getElementById("progress_width").value);
    document.getElementById("progress_width").value = prog_width;
    $("#bar1").animate({
      width: prog_width + "%"
    }, 10, function() {
      if (document.getElementById("bar1").style.width == "100%") {
        $(".progress").fadeOut("slow");
      }
    });
  } else {
    set_ele(ele);
  }
}

function set_ele(set_element) {
  check_element(set_element);
}

it definitely solve your problem for complete tutorial here is the link http://talkerscode.com/webtricks/display-progress-bar-while-page-loads-using-jquery.php

What is best way to start and stop hadoop ecosystem, with command line?

start-all.sh & stop-all.sh : Used to start and stop hadoop daemons all at once. Issuing it on the master machine will start/stop the daemons on all the nodes of a cluster. Deprecated as you have already noticed.

start-dfs.sh, stop-dfs.sh and start-yarn.sh, stop-yarn.sh : Same as above but start/stop HDFS and YARN daemons separately on all the nodes from the master machine. It is advisable to use these commands now over start-all.sh & stop-all.sh

hadoop-daemon.sh namenode/datanode and yarn-deamon.sh resourcemanager : To start individual daemons on an individual machine manually. You need to go to a particular node and issue these commands.

Use case : Suppose you have added a new DN to your cluster and you need to start the DN daemon only on this machine,

bin/hadoop-daemon.sh start datanode

Note : You should have ssh enabled if you want to start all the daemons on all the nodes from one machine.

Hope this answers your query.

JPA and Hibernate - Criteria vs. JPQL or HQL

For me the biggest win on Criteria is the Example API, where you can pass an object and hibernate will build a query based on those object properties.

Besides that, the criteria API has its quirks (I believe the hibernate team is reworking the api), like:

  • a criteria.createAlias("obj") forces a inner join instead of a possible outer join
  • you can't create the same alias two times
  • some sql clauses have no simple criteria counterpart (like a subselect)
  • etc.

I tend to use HQL when I want queries similar to sql (delete from Users where status='blocked'), and I tend to use criteria when I don't want to use string appending.

Another advantage of HQL is that you can define all your queries before hand, and even externalise them to a file or so.

How to check string length and then select substring in Sql Server

To conditionally check the length of the string, use CASE.

SELECT  CASE WHEN LEN(comments) <= 60 
             THEN comments
             ELSE LEFT(comments, 60) + '...'
        END  As Comments
FROM    myView

Git Commit Messages: 50/72 Formatting

Separation of presentation and data drives my commit messages here.

Your commit message should not be hard-wrapped at any character count and instead line breaks should be used to separate thoughts, paragraphs, etc. as part of the data, not the presentation. In this case, the "data" is the message you are trying to get across and the "presentation" is how the user sees that.

I use a single summary line at the top and I try to keep it short but I don't limit myself to an arbitrary number. It would be far better if Git actually provided a way to store summary messages as a separate entity from the message but since it doesn't I have to hack one in and I use the first line break as the delimiter (luckily, many tools support this means of breaking apart the data).

For the message itself newlines indicate something meaningful in the data. A single newline indicates a start/break in a list and a double newline indicates a new thought/idea.

This is a summary line, try to keep it short and end with a line break.
This is a thought, perhaps an explanation of what I have done in human readable format.  It may be complex and long consisting of several sentences that describe my work in essay format.  It is not up to me to decide now (at author time) how the user is going to consume this data.

Two line breaks separate these two thoughts.  The user may be reading this on a phone or a wide screen monitor.  Have you ever tried to read 72 character wrapped text on a device that only displays 60 characters across?  It is a truly painful experience.  Also, the opening sentence of this paragraph (assuming essay style format) should be an intro into the paragraph so if a tool chooses it may want to not auto-wrap and let you just see the start of each paragraph.  Again, it is up to the presentation tool not me (a random author at some point in history) to try to force my particular formatting down everyone else's throat.

Just as an example, here is a list of points:
* Point 1.
* Point 2.
* Point 3.

Here's what it looks like in a viewer that soft wraps the text.

This is a summary line, try to keep it short and end with a line break.

This is a thought, perhaps an explanation of what I have done in human readable format. It may be complex and long consisting of several sentences that describe my work in essay format. It is not up to me to decide now (at author time) how the user is going to consume this data.

Two line breaks separate these two thoughts. The user may be reading this on a phone or a wide screen monitor. Have you ever tried to read 72 character wrapped text on a device that only displays 60 characters across? It is a truly painful experience. Also, the opening sentence of this paragraph (assuming essay style format) should be an intro into the paragraph so if a tool chooses it may want to not auto-wrap and let you just see the start of each paragraph. Again, it is up to the presentation tool not me (a random author at some point in history) to try to force my particular formatting down everyone else's throat.

Just as an example, here is a list of points:
* Point 1.
* Point 2.
* Point 3.

My suspicion is that the author of Git commit message recommendation you linked has never written software that will be consumed by a wide array of end-users on different devices before (i.e., a website) since at this point in the evolution of software/computing it is well known that storing your data with hard-coded presentation information is a bad idea as far as user experience goes.

How do I show the value of a #define at compile-time?

As far as I know '#error' only will print strings, in fact you don't even need to use quotes.

Have you tried writing various purposefully incorrect code using "BOOST_VERSION"? Perhaps something like "blah[BOOST_VERSION] = foo;" will tell you something like "string literal 1.2.1 cannot be used as an array address". It won't be a pretty error message, but at least it'll show you the relevant value. You can play around until you find a compile error that does tell you the value.

Force sidebar height 100% using CSS (with a sticky bottom image)?

UPDATE: As this answer is still getting votes both up and down, and is at the time of writing eight years old: There are probably better techniques out there now. Original answer follows below.


Clearly you are looking for the Faux columns technique :-)

By how the height-property is calculated, you can't set height: 100% inside something that has auto-height.

Case-insensitive search in Rails model

Similar to Andrews which is #1:

Something that worked for me is:

name = "Blue Jeans"
Product.find_by("lower(name) = ?", name.downcase)

This eliminates the need to do a #where and #first in the same query. Hope this helps!

angular.js ng-repeat li items with html content

It goes like ng-bind-html-unsafe="opt.text":

<div ng-app ng-controller="MyCtrl">
    <ul>
    <li ng-repeat=" opt in opts" ng-bind-html-unsafe="opt.text" >
        {{ opt.text }}
    </li>
    </ul>

    <p>{{opt}}</p>
</div>

http://jsfiddle.net/gFFBa/3/

Or you can define a function in scope:

 $scope.getContent = function(obj){
     return obj.value + " " + obj.text;
 }

And use it this way:

<li ng-repeat=" opt in opts" ng-bind-html-unsafe="getContent(opt)" >
     {{ opt.value }}
</li>

http://jsfiddle.net/gFFBa/4/

Note that you can not do it with an option tag: Can I use HTML tags in the options for select elements?

How do you determine the ideal buffer size when using FileInputStream?

Yes, it's probably dependent on various things - but I doubt it will make very much difference. I tend to opt for 16K or 32K as a good balance between memory usage and performance.

Note that you should have a try/finally block in the code to make sure the stream is closed even if an exception is thrown.

How to set HTTP header to UTF-8 using PHP which is valid in W3C validator?

This is a problem with your web server sending out an HTTP header that does not match the one you define. For instructions on how to make the server send the correct headers, see this page.

Otherwise, you can also use PHP to modify the headers, but this has to be done before outputting any text using this code:

header('Content-Type: text/html; charset=utf-8');

More information on how to send out headers using PHP can be found in the documentation for the header function.

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

Is there a css cross-browser value for "width: -moz-fit-content;"?

width: intrinsic;           /* Safari/WebKit uses a non-standard name */
width: -moz-max-content;    /* Firefox/Gecko */
width: -webkit-max-content; /* Chrome */

HTML5 placeholder css padding

If you want to keep your line-height and force the placeholder to have the same, you can directly edit the placeholder CSS since the newer browser versions. That did the trick for me:

input::-webkit-input-placeholder { /* WebKit browsers */
  line-height: 1.5em;
}
input:-moz-placeholder { /* Mozilla Firefox 4 to 18 */
  line-height: 1.5em;
}
input::-moz-placeholder { /* Mozilla Firefox 19+ */
  line-height: 1.5em;
}
input:-ms-input-placeholder { /* Internet Explorer 10+ */
  line-height: 1.5em;
}

How to access full source of old commit in BitBucket?

Great answers from a couple of years ago. Now Bitbucket has made it easier.

Tag the Commit you want to download (as mentioned in answer by Rudy Matela).

Then head over to Downloads and click the "Tags" tab and you'll get multiple options for download.

Tag Downloads

Is there a destructor for Java?

The closest equivalent to a destructor in Java is the finalize() method. The big difference to a traditional destructor is that you can't be sure when it'll be called, since that's the responsibility of the garbage collector. I'd strongly recommend carefully reading up on this before using it, since your typical RAIA patterns for file handles and so on won't work reliably with finalize().

Angular, Http GET with parameter?

Having something like this:

let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('projectid', this.id);
let params = new URLSearchParams();
params.append("someParamKey", this.someParamValue)

this.http.get('http://localhost:63203/api/CallCenter/GetSupport', { headers: headers, search: params })

Of course, appending every param you need to params. It gives you a lot more flexibility than just using a URL string to pass params to the request.

EDIT(28.09.2017): As Al-Mothafar stated in a comment, search is deprecated as of Angular 4, so you should use params

EDIT(02.11.2017): If you are using the new HttpClient there are now HttpParams, which look and are used like this:

let params = new HttpParams().set("paramName",paramValue).set("paramName2", paramValue2); //Create new HttpParams

And then add the params to the request in, basically, the same way:

this.http.get(url, {headers: headers, params: params}); 
//No need to use .map(res => res.json()) anymore

More in the docs for HttpParams and HttpClient

$(...).datepicker is not a function - JQuery - Bootstrap

 <script type="text/javascript">

    var options={
            format: 'mm/dd/yyyy',
            todayHighlight: true,
            autoclose: true,
        };

    $('#datetimepicker').datepicker(options);

</script>

Jersey stopped working with InjectionManagerFactory not found

The only way I could solve it was via:

org.glassfish.jersey.core jersey-server ${jersey-2-version}

<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-servlet</artifactId>
    <version>${jersey-2-version}</version>
</dependency>

<dependency>
    <groupId>org.glassfish.jersey.inject</groupId>
    <artifactId>jersey-hk2</artifactId>
    <version>${jersey-2-version}</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.core/jersey-common -->
<dependency>
    <groupId>org.glassfish.jersey.core</groupId>
    <artifactId>jersey-common</artifactId>
    <version>${jersey-2-version}</version>
</dependency>

<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-servlet-core</artifactId>
    <version>${jersey-2-version}</version>
</dependency>

So, only if I added jersey-container-servlet and jersey-hk2 would it run without errors

How to exclude *AutoConfiguration classes in Spring Boot JUnit tests?

I have struggled with a similar issue for one day... My Scenario:

I have a SpringBoot application and I use applicationContext.xml in scr/main/resources to configure all my Spring Beans. For testing(integration testing) I use another applicationContext.xml in test/resources and things worked as I have expected: Spring/SpringBoot would override applicationContext.xml from scr/main/resources and would use the one for Testing which contained the beans configured for testing.

However, just for one UnitTest I wanted yet another customization for the applicationContext.xml used in Testing, just for this Test I wanted to used some mockito beans, so I could mock and verify, and here started my one day head-ache!

The problem is that Spring/SpringBoot doesn't not override the applicationContext.xml from scr/main/resources ONLY IF the file from test/resources HAS the SAME NAME. I tried for hours to use something like:

@RunWith(SpringJUnit4ClassRunner.class)
@OverrideAutoConfiguration(enabled=true)
@ContextConfiguration({"classpath:applicationContext-test.xml"})

it did not work, Spring was first loading the beans from applicationContext.xml in scr/main/resources

My solution based on the answers here by @myroch and @Stuart:

  1. Define the main configuration of the application:

    @Configuration @ImportResource({"classpath:applicationContext.xml"}) public class MainAppConfig { }

this is used in the application

@SpringBootApplication
@Import(MainAppConfig.class)
public class SuppressionMain implements CommandLineRunner
  1. Define a TestConfiguration for the Test where you want to exclude the main configuration

    @ComponentScan( basePackages = "com.mypackage", excludeFilters = { @ComponentScan.Filter(type = ASSIGNABLE_TYPE, value = {MainAppConfig.class}) }) @EnableAutoConfiguration public class TestConfig { }

By doing this, for this Test, Spring will not load applicationContext.xml and will load only the custom configuration specific for this Test.

Xcode 4: How do you view the console?

Here's an alternative.

  1. In XCode4 double-click your Project (Blueprint Icon).
  2. Select the Target (Gray Icon)
  3. Select the Build Phases (Top Center)
  4. Add Build Phase "Run Script" (Green Plus Button, bottom right)
  5. In the textbox below the Shell textfield replace "Type a script or drag a script file from your workspace" with "open ${TARGET_BUILD_DIR}/${TARGET_NAME}"

This will open a terminal window with your command-line app running in it.

This is not a great solution because XCode 4 still runs and debugs the app independently of what you're doing in the terminal window that pops up.

Relative path to absolute path in C#?

Assuming you know the real directory the XML file lives in use Path.Combine, e.g.

var absolute_path = Path.Combine(directoryXmlLivesIn, "..\images\image.jpg");

If you want to get back the full path with any ..'s collapsed then you can use:

Path.GetFullPath((new Uri(absolute_path)).LocalPath);

Show/hide 'div' using JavaScript

Just Simple Set the style attribute of ID:

To Show the hidden div

<div id="xyz" style="display:none">
     ...............
</div>
//In JavaScript

document.getElementById('xyz').style.display ='block';  // to hide

To hide the shown div

<div id="xyz">
     ...............
</div>
//In JavaScript

document.getElementById('xyz').style.display ='none';  // to display

Measure string size in Bytes in php

You can use mb_strlen() to get the byte length using a encoding that only have byte-characters, without worring about multibyte or singlebyte strings. For example, as drake127 saids in a comment of mb_strlen, you can use '8bit' encoding:

<?php
    $string = 'Cién cañones por banda';
    echo mb_strlen($string, '8bit');
?>

You can have problems using strlen function since php have an option to overload strlen to actually call mb_strlen. See more info about it in http://php.net/manual/en/mbstring.overload.php

For trim the string by byte length without split in middle of a multibyte character you can use:

mb_strcut(string $str, int $start [, int $length [, string $encoding ]] )

Is it not possible to stringify an Error using JSON.stringify?

You can solve this with a one-liner( errStringified ) in plain javascript:

var error = new Error('simple error message');
var errStringified = (err => JSON.stringify(Object.getOwnPropertyNames(Object.getPrototypeOf(err)).reduce(function(accumulator, currentValue) { return accumulator[currentValue] = err[currentValue], accumulator}, {})))(error);
console.log(errStringified);

It works with DOMExceptions as well.

How to add button in ActionBar(Android)?

An activity populates the ActionBar in its onCreateOptionsMenu() method.

Instead of using setcustomview(), just override onCreateOptionsMenu like this:

@Override    
public boolean onCreateOptionsMenu(Menu menu) {
  MenuInflater inflater = getMenuInflater();
  inflater.inflate(R.menu.mainmenu, menu);
  return true;
}

If an actions in the ActionBar is selected, the onOptionsItemSelected() method is called. It receives the selected action as parameter. Based on this information you code can decide what to do for example:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
  switch (item.getItemId()) {
    case R.id.menuitem1:
      Toast.makeText(this, "Menu Item 1 selected", Toast.LENGTH_SHORT).show();
      break;
    case R.id.menuitem2:
      Toast.makeText(this, "Menu item 2 selected", Toast.LENGTH_SHORT).show();
      break;
  }
  return true;
}

Choosing a file in Python with simple Dialog

Another option to consider is Zenity: http://freecode.com/projects/zenity.

I had a situation where I was developing a Python server application (no GUI component) and hence didn't want to introduce a dependency on any python GUI toolkits, but I wanted some of my debug scripts to be parameterized by input files and wanted to visually prompt the user for a file if they didn't specify one on the command line. Zenity was a perfect fit. To achieve this, invoke "zenity --file-selection" using the subprocess module and capture the stdout. Of course this solution isn't Python-specific.

Zenity supports multiple platforms and happened to already be installed on our dev servers so it facilitated our debugging/development without introducing an unwanted dependency.

Forking / Multi-Threaded Processes | Bash

With GNU Parallel you can do:

cat file | parallel 'foo {}; foo2 {}; foo3 {}'

This will run one job on each cpu core. To run 50 do:

cat file | parallel -j 50 'foo {}; foo2 {}; foo3 {}'

Watch the intro videos to learn more:

http://www.youtube.com/playlist?list=PL284C9FF2488BC6D1

How can I revert multiple Git commits (already pushed) to a published repository?

git revert HEAD -m 1

In the above code line. "Last argument represents"

  • 1 - reverts one commits. 2 - reverts last commits. n - reverts last n commits

or

git reset --hard siriwjdd

DropDownList in MVC 4 with Razor

You can use this:

@Html.DropDownListFor(x => x.Tipo, new List<SelectListItem>
    {
                        new SelectListItem() {Text = "Exemplo1", Value="Exemplo1"},
                        new SelectListItem() {Text = "Exemplo2", Value="Exemplo2"},
                        new SelectListItem() {Text = "Exemplo3", Value="Exemplo3"}
    })  

How to merge lists into a list of tuples?

One alternative without using zip:

list_c = [(p1, p2) for idx1, p1 in enumerate(list_a) for idx2, p2 in enumerate(list_b) if idx1==idx2]

In case one wants to get not only tuples 1st with 1st, 2nd with 2nd... but all possible combinations of the 2 lists, that would be done with

list_d = [(p1, p2) for p1 in list_a for p2 in list_b]

Replace single quotes in SQL Server

Besides needing to escape the quote (by using double quotes), you've also confused the names of variables: You're using @var and @strip, instead of @CleanString and @strStrip...

How to preserve insertion order in HashMap?

LinkedHashMap is precisely what you're looking for.

It is exactly like HashMap, except that when you iterate over it, it presents the items in the insertion order.

Convert integer to hex and hex to integer

Actually, the built-in function is named master.dbo.fn_varbintohexstr.

So, for example:

SELECT 100, master.dbo.fn_varbintohexstr(100)

Gives you

100 0x00000064