Programs & Examples On #Rhino dsl

Https to http redirect using htaccess

RewriteCond %{HTTP:X-Forwarded-Proto} =https

Using Java to pull data from a webpage?

Here's my solution using URL and try with resources phrase to catch the exceptions.

/**
 * Created by mona on 5/27/16.
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
public class ReadFromWeb {
    public static void readFromWeb(String webURL) throws IOException {
        URL url = new URL(webURL);
        InputStream is =  url.openStream();
        try( BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        }
        catch (MalformedURLException e) {
            e.printStackTrace();
            throw new MalformedURLException("URL is malformed!!");
        }
        catch (IOException e) {
            e.printStackTrace();
            throw new IOException();
        }

    }
    public static void main(String[] args) throws IOException {
        String url = "https://madison.craigslist.org/search/sub";
        readFromWeb(url);
    }

}

You could additionally save it to file based on your needs or parse it using XML or HTML libraries.

Iframe transparent background

Why not just load the frame off screen or hidden and then display it once it has finished loading. You could show a loading icon in its place to begin with to give the user immediate feedback that it's loading.

Why is the GETDATE() an invalid identifier

SYSDATE and GETDATE perform identically.

SYSDATE is compatible with Oracle syntax, and GETDATE is compatible with Microsoft SQL Server syntax.

Swift convert unix time to date and time

Convert timestamp into Date object.

If timestamp object is invalid then return current date.

class func toDate(_ timestamp: Any?) -> Date? {
    if let any = timestamp {
        if let str = any as? NSString {
            return Date(timeIntervalSince1970: str.doubleValue)
        } else if let str = any as? NSNumber {
            return Date(timeIntervalSince1970: str.doubleValue)
        }
    }
    return nil
}

Babel command not found

There are two problems here. First, you need a package.json file. Telling npm to install without one will throw the npm WARN enoent ENOENT: no such file or directory error. In your project directory, run npm init to generate a package.json file for the project.

Second, local binaries probably aren't found because the local ./node_modules/.bin is not in $PATH. There are some solutions in How to use package installed locally in node_modules?, but it might be easier to just wrap your babel-cli commands in npm scripts. This works because npm run adds the output of npm bin (node_modules/.bin) to the PATH provided to scripts.

Here's a stripped-down example package.json which returns the locally installed babel-cli version:

{
  "scripts": {
    "babel-version": "babel --version"
  },
  "devDependencies": {
    "babel-cli": "^6.6.5"
  }
}

Call the script with this command: npm run babel-version.

Putting scripts in package.json is quite useful but often overlooked. Much more in the docs: How npm handles the "scripts" field

Convert canvas to PDF

Please see https://github.com/joshua-gould/canvas2pdf. This library creates a PDF representation of your canvas element, unlike the other proposed solutions which embed an image in a PDF document.

//Create a new PDF canvas context.
var ctx = new canvas2pdf.Context(blobStream());

//draw your canvas like you would normally
ctx.fillStyle='yellow';
ctx.fillRect(100,100,100,100);
// more canvas drawing, etc...

//convert your PDF to a Blob and save to file
ctx.stream.on('finish', function () {
    var blob = ctx.stream.toBlob('application/pdf');
    saveAs(blob, 'example.pdf', true);
});
ctx.end();

Convert int (number) to string with leading zeros? (4 digits)

Use String.PadLeft like this:

var result = input.ToString().PadLeft(length, '0');

Class Diagrams in VS 2017

A further note on Dmitry's 2017 answer. I opened up

C:\Program Files (x86)\Microsoft Visual 
Studio\2017\Community\MSBuild\Microsoft\VisualStudio\Managed\ 
Microsoft.CSharp.DesignTime.targets 

and went to the <ProjectCapability> element. I already had this:

<ProjectCapability Include="
                          CSharp;
                          Managed;
                          ClassDesigner**;**" />

with ClassDesigner already there, and yet I was still unable to drag items to my hack-made Diagram.cd using the XML editing method Dmitry mentioned (

Manually create text file, say MyClasses.cd with following content:

<?xml version="1.0" encoding="utf-8"?> <ClassDiagram MajorVersion="1"
> MinorVersion="1">
>     <Font Name="Segoe UI" Size="9" /> </ClassDiagram>

). But when I took off the semicolon off 'ClassDesigner' in that element then reopened Visual Studio, voila, I was able to drag classes from my Solution Explorer to my Diagram.cd window.

So in conclusion, this element in Microsoft.CSharp.DesignTime.targets worked:

<ProjectCapability Include="
                              CSharp;
                              Managed;
                              ClassDesigner" />

I am using VS 2019, version 16.1.5.

Can a WSDL indicate the SOAP version (1.1 or 1.2) of the web service?

SOAP 1.1 uses namespace http://schemas.xmlsoap.org/wsdl/soap/

SOAP 1.2 uses namespace http://schemas.xmlsoap.org/wsdl/soap12/

The wsdl is able to define operations under soap 1.1 and soap 1.2 at the same time in the same wsdl. Thats useful if you need to evolve your wsdl to support new functionality that requires soap 1.2 (eg. MTOM), in this case you dont need to create a new service but just evolve the original one.

java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/JsonFactory

In my case problem was when i added com.fasterxml.jackson.dataformat i put the version 2.11.0.

While all other Jackson dependencies were 2.8.0 and one of them was 2.11.0 and changing all to be 2.8.0 fixed it.

FYI, 2.11 is the latest but due to my legacy code, i kept it as 2.8 as well.

Before Fix [ERROR]

com.fasterxml.jackson.dataformat version is 2.11.0    
com.fasterxml.jackson.dataformat jackson-dataformat-xml 2.11.0
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.8.0</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.0</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.8.0</version>
</dependency>

After Fix [WORKED] com.fasterxml.jackson.dataformat version is 2.8.0

com.fasterxml.jackson.dataformat jackson-dataformat-xml 2.8.0
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.8.0</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.0</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.8.0</version>
</dependency>

jQuery trigger event when click outside the element

I know that the question has been answered, but I hope my solution helps other people.

stopPropagation caused problems in my case, because I needed the click event for something else. Moreover, not every element should cause the div to be closed when clicked.

My solution:

$(document).click(function(e) {
    if (($(e.target).closest("#mydiv").attr("id") != "mydiv") &&
        $(e.target).closest("#div-exception").attr("id") != "div-exception") {
        alert("Clicked outside!");
    }
});

http://jsfiddle.net/NLDu3/

SMTP Connect() failed. Message was not sent.Mailer error: SMTP Connect() failed

You've got no SMTPSecure setting to define the type of authentication being used, and you're running the Host setting with the unnecessary 'ssl://' (PS -- ssl is over port 465, if you need to run it over ssl instead, see the accepted answer here. Here's the lines to add/change:

+ $mail->SMTPSecure = 'tls';

- $mail->Host = "ssl://smtp.gmail.com";
+ $mail->Host = "smtp.gmail.com";

What are the differences between a clustered and a non-clustered index?

Clustered indexes physically order the data on the disk. This means no extra data is needed for the index, but there can be only one clustered index (obviously). Accessing data using a clustered index is fastest.

All other indexes must be non-clustered. A non-clustered index has a duplicate of the data from the indexed columns kept ordered together with pointers to the actual data rows (pointers to the clustered index if there is one). This means that accessing data through a non-clustered index has to go through an extra layer of indirection. However if you select only the data that's available in the indexed columns you can get the data back directly from the duplicated index data (that's why it's a good idea to SELECT only the columns that you need and not use *)

How to print color in console using System.out.println?

If you use Kotlin (which works seamlessly with Java), you can make such an enum:

enum class AnsiColor(private val colorNumber: Byte) {
    BLACK(0), RED(1), GREEN(2), YELLOW(3), BLUE(4), MAGENTA(5), CYAN(6), WHITE(7);

    companion object {
        private const val prefix = "\u001B"
        const val RESET = "$prefix[0m"
        private val isCompatible = "win" !in System.getProperty("os.name").toLowerCase()
    }

    val regular get() = if (isCompatible) "$prefix[0;3${colorNumber}m" else ""
    val bold get() = if (isCompatible) "$prefix[1;3${colorNumber}m" else ""
    val underline get() = if (isCompatible) "$prefix[4;3${colorNumber}m" else ""
    val background get() = if (isCompatible) "$prefix[4${colorNumber}m" else ""
    val highIntensity get() = if (isCompatible) "$prefix[0;9${colorNumber}m" else ""
    val boldHighIntensity get() = if (isCompatible) "$prefix[1;9${colorNumber}m" else ""
    val backgroundHighIntensity get() = if (isCompatible) "$prefix[0;10${colorNumber}m" else ""
}

And then use is as such: (code below showcases the different styles for all colors)

val sampleText = "This is a sample text"
enumValues<AnsiColor>().forEach { ansiColor ->
    println("${ansiColor.regular}$sampleText${AnsiColor.RESET}")
    println("${ansiColor.bold}$sampleText${AnsiColor.RESET}")
    println("${ansiColor.underline}$sampleText${AnsiColor.RESET}")
    println("${ansiColor.background}$sampleText${AnsiColor.RESET}")
    println("${ansiColor.highIntensity}$sampleText${AnsiColor.RESET}")
    println("${ansiColor.boldHighIntensity}$sampleText${AnsiColor.RESET}")
    println("${ansiColor.backgroundHighIntensity}$sampleText${AnsiColor.RESET}")
}

If running on Windows where these ANSI codes are not supported, the isCompatible check avoids issues by replacing the codes with empty string.

keyword not supported data source

What you have is a valid ADO.NET connection string - but it's NOT a valid Entity Framework connection string.

The EF connection string would look something like this:

<connectionStrings> 
  <add name="NorthwindEntities" connectionString=
     "metadata=.\Northwind.csdl|.\Northwind.ssdl|.\Northwind.msl;
      provider=System.Data.SqlClient;
      provider connection string=&quot;Data Source=SERVER\SQL2000;Initial Catalog=Northwind;Integrated Security=True;MultipleActiveResultSets=False&quot;" 
      providerName="System.Data.EntityClient" /> 
</connectionStrings>

You're missing all the metadata= and providerName= elements in your EF connection string...... you basically only have what's contained in the provider connection string part.

Using the EDMX designer should create a valid EF connection string for you, in your web.config or app.config.

Marc

UPDATE: OK, I understand what you're trying to do: you need a second "ADO.NET" connection string just for ASP.NET user / membership database. Your string is OK, but the providerName is wrong - it would have to be "System.Data.SqlClient" - this connection doesn't use ENtity Framework - don't specify the "EntityClient" for it then!

<add name="ASPNETMembership" 
     connectionString="Data Source=MONTGOMERY-DEV\SQLEXPRESS;Initial Catalog=ASPNETDB;Integrated Security=True;" 
     providerName="System.Data.SqlClient" />

If you specify providerName=System.Data.EntityClient ==> Entity Framework connection string (with the metadata= and everything).

If you need and specify providerName=System.Data.SqlClient ==> straight ADO.NET SQL Server connection string without all the EF additions

How to compare arrays in C#?

You're comparing the object references, and they are not the same. You need to compare the array contents.

.NET2 solution

An option is iterating through the array elements and call Equals() for each element. Remember that you need to override the Equals() method for the array elements, if they are not the same object reference.

An alternative is using this generic method to compare two generic arrays:

static bool ArraysEqual<T>(T[] a1, T[] a2)
{
    if (ReferenceEquals(a1, a2))
        return true;

    if (a1 == null || a2 == null)
        return false;

    if (a1.Length != a2.Length)
        return false;

    var comparer = EqualityComparer<T>.Default;
    for (int i = 0; i < a1.Length; i++)
    {
        if (!comparer.Equals(a1[i], a2[i])) return false;
    }
    return true;
}

.NET 3.5 or higher solution

Or use SequenceEqual if Linq is available for you (.NET Framework >= 3.5)

.aspx vs .ashx MAIN difference

Page is a special case handler.

Generic Web handler (*.ashx, extension based processor) is the default HTTP handler for all Web handlers that do not have a UI and that include the @WebHandler directive.

ASP.NET page handler (*.aspx) is the default HTTP handler for all ASP.NET pages.

Among the built-in HTTP handlers there are also Web service handler (*.asmx) and Trace handler (trace.axd)

MSDN says:

An ASP.NET HTTP handler is the process (frequently referred to as the "endpoint") that runs in response to a request made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler.

The image below illustrates this: request pipe line

As to your second question:

Does ashx handle more connections than aspx?

Don't think so (but for sure, at least not less than).

Difference between array_map, array_walk and array_filter

From the documentation,

bool array_walk ( array &$array , callback $funcname [, mixed $userdata ] ) <-return bool

array_walk takes an array and a function F and modifies it by replacing every element x with F(x).

array array_map ( callback $callback , array $arr1 [, array $... ] )<-return array

array_map does the exact same thing except that instead of modifying in-place it will return a new array with the transformed elements.

array array_filter ( array $input [, callback $callback ] )<-return array

array_filter with function F, instead of transforming the elements, will remove any elements for which F(x) is not true

PhpMyAdmin "Wrong permissions on configuration file, should not be world writable!"

try this it will work

sudo chmod 755 /opt/lampp/phpmyadmin/config.inc.php

thanks

Filter output in logcat by tagname

Another option is setting the log levels for specific tags:

adb logcat SensorService:S PowerManagerService:S NfcService:S power:I Sensors:E

If you just want to set the log levels for some tags you can do it on a tag by tag basis.

Foreign key referring to primary keys across multiple tables?

Assuming that I have understood your scenario correctly, this is what I would call the right way to do this:

Start from a higher-level description of your database! You have employees, and employees can be "ce" employees and "sn" employees (whatever those are). In object-oriented terms, there is a class "employee", with two sub-classes called "ce employee" and "sn employee".

Then you translate this higher-level description to three tables: employees, employees_ce and employees_sn:

  • employees(id, name)
  • employees_ce(id, ce-specific stuff)
  • employees_sn(id, sn-specific stuff)

Since all employees are employees (duh!), every employee will have a row in the employees table. "ce" employees also have a row in the employees_ce table, and "sn" employees also have a row in the employees_sn table. employees_ce.id is a foreign key to employees.id, just as employees_sn.id is.

To refer to an employee of any kind (ce or sn), refer to the employees table. That is, the foreign key you had trouble with should refer to that table!

Function pointer as parameter

Replace void *disconnectFunc; with void (*disconnectFunc)(); to declare function pointer type variable. Or even better use a typedef:

typedef void (*func_t)(); // pointer to function with no args and void return
...
func_t fptr; // variable of pointer to function
...
void D::setDisconnectFunc( func_t func )
{
    fptr = func;
}

void D::disconnected()
{
    fptr();
    connected = false;
}

Get a list of all threads currently running in Java

You can get a lot of information about threads from the ThreadMXBean.

Call the static ManagementFactory.getThreadMXBean() method to get a reference to the MBean.

Best way to check for "empty or null value"

Checking for the length of the string also works and is compact:

where length(stringexpression) > 0;

C# Enum - How to Compare Value

Comparision:

if (userProfile.AccountType == AccountType.Retailer)
{
    //your code
}

In case to prevent the NullPointerException you could add the following condition before comparing the AccountType:

if(userProfile != null)
{
    if (userProfile.AccountType == AccountType.Retailer)
    {
       //your code
    }
}

or shorter version:

if (userProfile !=null && userProfile.AccountType == AccountType.Retailer)
{
    //your code
}

Is there a way to check if a file is in use?

the only way I know of is to use the Win32 exclusive lock API which isn't too speedy, but examples exist.

Most people, for a simple solution to this, simply to try/catch/sleep loops.

How do I get the last four characters from a string in C#?

Use a generic Last<T>. That will work with ANY IEnumerable, including string.

public static IEnumerable<T> Last<T>(this IEnumerable<T> enumerable, int nLastElements)
{
    int count = Math.Min(enumerable.Count(), nLastElements);
    for (int i = enumerable.Count() - count; i < enumerable.Count(); i++)
    {
        yield return enumerable.ElementAt(i);
    }
}

And a specific one for string:

public static string Right(this string str, int nLastElements)
{
    return new string(str.Last(nLastElements).ToArray());
}

How to set the width of a RaisedButton in Flutter?

Try it out

Expanded(   
  child: RaisedButton(
    onPressed: _onButtonPressed,
    child: Text('Button1')
  )  
)

C# Switch-case string starting with

Short answer: No.

The switch statement takes an expression that is only evaluated once. Based on the result, another piece of code is executed.

So what? => String.StartsWith is a function. Together with a given parameter, it is an expression. However, for your case you need to pass a different parameter for each case, so it cannot be evaluated only once.

Long answer #1 has been given by others.

Long answer #2:

Depending on what you're trying to achieve, you might be interested in the Command Pattern/Chain-of-responsibility pattern. Applied to your case, each piece of code would be represented by an implementation of a Command. In addition to the execute method, the command can provide a boolean Accept method, which checks whether the given string starts with the respective parameter.

Advantage: Instead of your hardcoded switch statement, hardcoded StartsWith evaluations and hardcoded strings, you'd have lot more flexibility.

The example you gave in your question would then look like this:

var commandList = new List<Command>() { new MyABCCommand() };

foreach (Command c in commandList)
{
    if (c.Accept(mystring))
    {
        c.Execute(mystring);
        break;
    }
}

class MyABCCommand : Command
{
    override bool Accept(string mystring)
    {
        return mystring.StartsWith("abc");
    }
}    

Adding a simple UIAlertView

As a supplementary to the two previous answers (of user "sudo rm -rf" and "Evan Mulawski"), if you don't want to do anything when your alert view is clicked, you can just allocate, show and release it. You don't have to declare the delegate protocol.

TypeScript or JavaScript type casting

This is called type assertion in TypeScript, and since TypeScript 1.6, there are two ways to express this:

// Original syntax
var markerSymbolInfo = <MarkerSymbolInfo> symbolInfo;

// Newer additional syntax
var markerSymbolInfo = symbolInfo as MarkerSymbolInfo;

Both alternatives are functionally identical. The reason for introducing the as-syntax is that the original syntax conflicted with JSX, see the design discussion here.

If you are in a position to choose, just use the syntax that you feel more comfortable with. I personally prefer the as-syntax as it feels more fluent to read and write.

How to add title to seaborn boxplot

sns.boxplot() function returns Axes(matplotlib.axes.Axes) object. please refer the documentation you can add title using 'set' method as below:

sns.boxplot('Day', 'Count', data=gg).set(title='lalala')

you can also add other parameters like xlabel, ylabel to the set method.

sns.boxplot('Day', 'Count', data=gg).set(title='lalala', xlabel='its x_label', ylabel='its y_label')

There are some other methods as mentioned in the matplotlib.axes.Axes documentaion to add tile, legend and labels.

Basic HTTP authentication with Node and Express 4

Express has removed this functionality and now recommends you use the basic-auth library.

Here's an example of how to use:

var http = require('http')
var auth = require('basic-auth')

// Create server
var server = http.createServer(function (req, res) {
  var credentials = auth(req)

  if (!credentials || credentials.name !== 'aladdin' || credentials.pass !== 'opensesame') {
    res.statusCode = 401
    res.setHeader('WWW-Authenticate', 'Basic realm="example"')
    res.end('Access denied')
  } else {
    res.end('Access granted')
  }
})

// Listen
server.listen(3000)

To send a request to this route you need to include an Authorization header formatted for basic auth.

Sending a curl request first you must take the base64 encoding of name:pass or in this case aladdin:opensesame which is equal to YWxhZGRpbjpvcGVuc2VzYW1l

Your curl request will then look like:

 curl -H "Authorization: Basic YWxhZGRpbjpvcGVuc2VzYW1l" http://localhost:3000/

How to convert std::string to LPCSTR?

str.c_str() gives you a const char *, which is an LPCSTR (Long Pointer to Constant STRing) -- means that it's a pointer to a 0 terminated string of characters. W means wide string (composed of wchar_t instead of char).

Express: How to pass app-instance to routes from a different file?

Like I said in the comments, you can use a function as module.exports. A function is also an object, so you don't have to change your syntax.

app.js

var controllers = require('./controllers')({app: app});

controllers.js

module.exports = function(params)
{
    return require('controllers/index')(params);
}

controllers/index.js

function controllers(params)
{
  var app = params.app;

  controllers.posts = require('./posts');

  controllers.index = function(req, res) {
    // code
  };
}

module.exports = controllers;

Easiest way to split a string on newlines in .NET?

I did not know about Environment.Newline, but I guess this is a very good solution.

My try would have been:

        string str = "Test Me\r\nTest Me\nTest Me";
        var splitted = str.Split('\n').Select(s => s.Trim()).ToArray();

The additional .Trim removes any \r or \n that might be still present (e. g. when on windows but splitting a string with os x newline characters). Probably not the fastest method though.

EDIT:

As the comments correctly pointed out, this also removes any whitespace at the start of the line or before the new line feed. If you need to preserve that whitespace, use one of the other options.

How to convert an int value to string in Go?

It is interesting to note that strconv.Itoa is shorthand for

func FormatInt(i int64, base int) string

with base 10

For Example:

strconv.Itoa(123)

is equivalent to

strconv.FormatInt(int64(123), 10)

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

Using <section> may be neater, help screen readers and SEO while <div> is smaller in bytes and quicker to type

Overall very little difference.

Also, would not recommend putting <section> in a <section>, instead place a <div> inside a <section>

check if a key exists in a bucket in s3 using boto3

Here is a solution that works for me. One caveat is that I know the exact format of the key ahead of time, so I am only listing the single file

import boto3

# The s3 base class to interact with S3
class S3(object):
  def __init__(self):
    self.s3_client = boto3.client('s3')

  def check_if_object_exists(self, s3_bucket, s3_key):
    response = self.s3_client.list_objects(
      Bucket = s3_bucket,
      Prefix = s3_key
      )
    if 'ETag' in str(response):
      return True
    else:
      return False

if __name__ == '__main__':
  s3  = S3()
  if s3.check_if_object_exists(bucket, key):
    print "Found S3 object."
  else:
    print "No object found."

favicon not working in IE

Run Internet Explorer as Administrator. If you open IE in normal mode then favicon will not display on IE 11 (Win 7). I am not sure about the behavior on other version of browsers.

How do I add a new column to a Spark DataFrame (using PySpark)?

from pyspark.sql.functions import udf
from pyspark.sql.types import *
func_name = udf(
    lambda val: val, # do sth to val
    StringType()
)
df.withColumn('new_col', func_name(df.old_col))

Get day of week in SQL Server 2005/2008

Even though SQLMenace's answer has been accepted, there is one important SET option you should be aware of

SET DATEFIRST

DATENAME will return correct date name but not the same DATEPART value if the first day of week has been changed as illustrated below.

declare @DefaultDateFirst int
set @DefaultDateFirst = @@datefirst
--; 7 First day of week is "Sunday" by default
select  [@DefaultDateFirst] = @DefaultDateFirst 

set datefirst @DefaultDateFirst
select datename(dw,getdate()) -- Saturday
select datepart(dw,getdate()) -- 7

--; Set the first day of week to * TUESDAY * 
--; (some people start their week on Tuesdays...)
set datefirst 2
select datename(dw,getdate()) -- Saturday
--; Returns 5 because Saturday is the 5th day since Tuesday.
--; Tue 1, Wed 2, Th 3, Fri 4, Sat 5
select datepart(dw,getdate()) -- 5 <-- It's not 7!
set datefirst @DefaultDateFirst

bootstrap 3 wrap text content within div for horizontal alignment

Your code is working fine using bootatrap v3.3.7, but you can use word-break: break-word if it's not working at your end.

which would then look like this -

snap

_x000D_
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"_x000D_
        integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
    <div class="row" style="box-shadow: 0 0 30px black;">_x000D_
        <div class="col-6 col-sm-6 col-lg-4">_x000D_
            <h3 style="word-break: break-word;">2005 Volkswagen Jetta 2.5 Sedan (worcester http://www.massmotorcars.com)_x000D_
                $6900</h3>_x000D_
            <p>_x000D_
                <small>2005 volkswagen jetta 2.5 for sale has 110,000 miles powere doors,power windows,has ,car drives_x000D_
                    excellent ,comes with warranty if you&#39;re ...</small>_x000D_
            </p>_x000D_
            <p>_x000D_
                <a class="btn btn-default" href="/search/1355/detail/" role="button">View details &raquo;</a>_x000D_
                <button type="button" class="btn bookmark" id="1355">_x000D_
                    <span class="_x000D_
                      glyphicon glyphicon-star-empty "></span>_x000D_
                </button>_x000D_
            </p>_x000D_
        </div>_x000D_
        <!--/span-->_x000D_
        <div class="col-6 col-sm-6 col-lg-4">_x000D_
            <h3 style="word-break: break-word;">2006 Honda Civic EX Sedan (Worcester www.massmotorcars.com) $7950</h3>_x000D_
            <p>_x000D_
                <small>2006 honda civic ex has 110,176 miles, has power doors ,power windows,sun roof,alloy wheels,runs_x000D_
                    great, cd player, 4 cylinder engen, ...</small>_x000D_
            </p>_x000D_
            <p>_x000D_
                <a class="btn btn-default" href="/search/1356/detail/" role="button">View details &raquo;</a>_x000D_
                <button type="button" class="btn bookmark" id="1356">_x000D_
                    <span class="_x000D_
                      glyphicon glyphicon-star-empty "></span>_x000D_
                </button>_x000D_
            </p>_x000D_
_x000D_
        </div>_x000D_
        <!--/span-->_x000D_
        <div class="col-6 col-sm-6 col-lg-4">_x000D_
            <h3 style="word-break: break-word;">2004 Honda Civic LX Sedan (worcester www.massmotorcars.com) $5900</h3>_x000D_
            <p>_x000D_
                <small>2004 honda civic lx sedan has 134,000 miles, great looking car, interior and exterior looks_x000D_
                    nice,has_x000D_
                    cd player, power windows ...</small>_x000D_
            </p>_x000D_
            <p>_x000D_
                <a class="btn btn-default" href="/search/1357/detail/" role="button">View details &raquo;</a>_x000D_
                <button type="button" class="btn bookmark" id="1357">_x000D_
                    <span class="_x000D_
                      glyphicon glyphicon-star-empty "></span>_x000D_
                </button>_x000D_
            </p>_x000D_
        </div>_x000D_
    </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Microsoft Excel ActiveX Controls Disabled?

From other forums, I have learned that it is due to the MS Update and that a good fix is to simply delete the file MSForms.exd from any Temp subfolder in the user's profile. For instance:

C:\Users\[user.name]\AppData\Local\Temp\Excel8.0\MSForms.exd

C:\Users\[user.name]\AppData\Local\Temp\VBE\MSForms.exd

C:\Users\[user.name]\AppData\Local\Temp\Word8.0\MSForms.exd

Of course the application (Excel, Word...) must be closed in order to delete this file.

java.util.NoSuchElementException: No line found

You're calling nextLine() and it's throwing an exception when there's no line, exactly as the javadoc describes. It will never return null

http://download.oracle.com/javase/1,5.0/docs/api/java/util/Scanner.html

String concatenation: concat() vs "+" operator

I ran a similar test as @marcio but with the following loop instead:

String c = a;
for (long i = 0; i < 100000L; i++) {
    c = c.concat(b); // make sure javac cannot skip the loop
    // using c += b for the alternative
}

Just for good measure, I threw in StringBuilder.append() as well. Each test was run 10 times, with 100k reps for each run. Here are the results:

  • StringBuilder wins hands down. The clock time result was 0 for most the runs, and the longest took 16ms.
  • a += b takes about 40000ms (40s) for each run.
  • concat only requires 10000ms (10s) per run.

I haven't decompiled the class to see the internals or run it through profiler yet, but I suspect a += b spends much of the time creating new objects of StringBuilder and then converting them back to String.

Doctrine query builder using inner join with conditions

You can explicitly have a join like this:

$qb->innerJoin('c.phones', 'p', Join::ON, 'c.id = p.customerId');

But you need to use the namespace of the class Join from doctrine:

use Doctrine\ORM\Query\Expr\Join;

Or if you prefere like that:

$qb->innerJoin('c.phones', 'p', Doctrine\ORM\Query\Expr\Join::ON, 'c.id = p.customerId');

Otherwise, Join class won't be detected and your script will crash...

Here the constructor of the innerJoin method:

public function innerJoin($join, $alias, $conditionType = null, $condition = null);

You can find other possibilities (not just join "ON", but also "WITH", etc...) here: http://docs.doctrine-project.org/en/2.0.x/reference/query-builder.html#the-expr-class

EDIT

Think it should be:

$qb->select('c')
    ->innerJoin('c.phones', 'p', Join::ON, 'c.id = p.customerId')
    ->where('c.username = :username')
    ->andWhere('p.phone = :phone');

    $qb->setParameters(array(
        'username' => $username,
        'phone' => $phone->getPhone(),
    ));

Otherwise I think you are performing a mix of ON and WITH, perhaps the problem.

Bash: infinite sleep (infinite blocking)

This approach will not consume any resources for keeping process alive.

while :; do sleep 1; done & kill -STOP $! && wait $!

Breakdown

  • while :; do sleep 1; done & Creates a dummy process in background
  • kill -STOP $! Stops the background process
  • wait $! Wait for the background process, this will be blocking forever, cause background process was stopped before

Bootstrap date time picker

You don't need to give local path. just give cdn link of bootstrap datetimepicker. and it works.

_x000D_
_x000D_
<html lang="en">_x000D_
<head>_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.js"></script>_x000D_
_x000D_
</head>_x000D_
_x000D_
_x000D_
<body>_x000D_
_x000D_
   <div class="container">_x000D_
      <div class="row">_x000D_
        <div class='col-sm-6'>_x000D_
            <div class="form-group">_x000D_
                <div class='input-group date' id='datetimepicker'>_x000D_
                    <input type='text' class="form-control" />_x000D_
                    <span class="input-group-addon">_x000D_
                        <span class="glyphicon glyphicon-calendar"></span>_x000D_
                    </span>_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>_x000D_
        <script type="text/javascript">_x000D_
            $(function () {_x000D_
                $('#datetimepicker').datepicker();_x000D_
            });_x000D_
        </script>_x000D_
      </div>_x000D_
   </div>_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Pass parameter from a batch file to a PowerShell script

The answer from @Emiliano is excellent. You can also pass named parameters like so:

powershell.exe -Command 'G:\Karan\PowerShell_Scripts\START_DEV.ps1' -NamedParam1 "SomeDataA" -NamedParam2 "SomeData2"

Note the parameters are outside the command call, and you'll use:

[parameter(Mandatory=$false)]
  [string]$NamedParam1,
[parameter(Mandatory=$false)]
  [string]$NamedParam2

.war vs .ear file

A WAR (Web Archive) is a module that gets loaded into a Web container of a Java Application Server. A Java Application Server has two containers (runtime environments) - one is a Web container and the other is a EJB container.

The Web container hosts Web applications based on JSP or the Servlets API - designed specifically for web request handling - so more of a request/response style of distributed computing. A Web container requires the Web module to be packaged as a WAR file - that is a special JAR file with a web.xml file in the WEB-INF folder.

An EJB container hosts Enterprise java beans based on the EJB API designed to provide extended business functionality such as declarative transactions, declarative method level security and multiprotocol support - so more of an RPC style of distributed computing. EJB containers require EJB modules to be packaged as JAR files - these have an ejb-jar.xml file in the META-INF folder.

Enterprise applications may consist of one or more modules that can either be Web modules (packaged as a WAR file), EJB modules (packaged as a JAR file), or both of them. Enterprise applications are packaged as EAR files - these are special JAR files containing an application.xml file in the META-INF folder.

Basically, EAR files are a superset containing WAR files and JAR files. Java Application Servers allow deployment of standalone web modules in a WAR file, though internally, they create EAR files as a wrapper around WAR files. Standalone web containers such as Tomcat and Jetty do not support EAR files - these are not full-fledged Application servers. Web applications in these containers are to be deployed as WAR files only.

In application servers, EAR files contain configurations such as application security role mapping, EJB reference mapping and context root URL mapping of web modules.

Apart from Web modules and EJB modules, EAR files can also contain connector modules packaged as RAR files and Client modules packaged as JAR files.

Accessing Google Account Id /username via Android

There is a sample from google, which lists the existing google accounts and generates an access token upon selection , you can send that access token to server to retrieve the related details from it to identify the user.

You can also get the email id from access token , for that you need to modify the SCOPE

Please go through My Post

Moment.js - tomorrow, today and yesterday

You can use this:


const today     = moment();

const tomorrow  = moment().add(1, 'days');

const yesterday = moment().subtract(1, 'days');

How to split a string between letters and digits (or between digits and letters)?

You could try to split on (?<=\D)(?=\d)|(?<=\d)(?=\D), like:

str.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");

It matches positions between a number and not-a-number (in any order).

  • (?<=\D)(?=\d) - matches a position between a non-digit (\D) and a digit (\d)
  • (?<=\d)(?=\D) - matches a position between a digit and a non-digit.

How to move div vertically down using CSS

I don't see any mention of flexbox in here, so I will illustrate:

HTML

 <div class="wrapper">
   <div class="main">top</div>
   <div class="footer">bottom</div>
 </div>

CSS

 .wrapper {
   display: flex;
   flex-direction: column;
   min-height: 100vh;
  }
 .main {
   flex: 1;
 }
 .footer {
  flex: 0;
 }

Run jar file in command prompt

If you dont have an entry point defined in your manifest invoking java -jar foo.jar will not work.

Use this command if you dont have a manifest or to run a different main class than the one specified in the manifest:

java -cp foo.jar full.package.name.ClassName

See also instructions on how to create a manifest with an entry point: https://docs.oracle.com/javase/tutorial/deployment/jar/appman.html

Pass multiple complex objects to a post/put Web API method

Create one complex object to combine Content and Config in it as others mentioned, use dynamic and just do a .ToObject(); as:

[HttpPost]
public void StartProcessiong([FromBody] dynamic obj)
{
   var complexObj= obj.ToObject<ComplexObj>();
   var content = complexObj.Content;
   var config = complexObj.Config;
}

Changing the default title of confirm() in JavaScript?

This is not possible, as you say, from a security stand point. The only way you could simulate it, is by creating a modeless dialog window.

There are many third-party javascript-plugins that you could use to fake this effect so you do not have to write all that code.

How to use regex in String.contains() method in Java

You can simply use matches method of String class.

boolean result = someString.matches("stores.*store.*product.*");

Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile)

Sometimes this issue comes because the java.version which you have mentioned in POM.xml is not the one installed in your machine.

<properties>
    <java.version>1.7</java.version>
</properties>

Ensure you exactly mention the same version in your pom.xml as the jdk and jre version present in your machine.

Laravel 5 How to switch from Production mode

Laravel 5 uses .env file to configure your app. .env should not be committed on your repository, like github or bitbucket. On your local environment your .env will look like the following:

# .env
APP_ENV=local

For your production server, you might have the following config:

# .env
APP_ENV=production

How can I disable an <option> in a <select> based on its value in JavaScript?

I would like to give you also the idea to disable an <option> with a given defined value (not innerhtml). I recommend to it with jQuery to get the simplest way. See my sample below.

HTML

Status:  
<div id="option">
   <select class="status">
      <option value="hand" selected>Hand</option>
      <option value="simple">Typed</option>
      <option value="printed">Printed</option>
   </select>
</div>

Javascript

The idea here is how to disable Printed option when current Status is Hand

var status = $('#option').find('.status');//to get current the selected value
var op = status.find('option');//to get the elements for disable attribute
(status.val() == 'hand')? op[2].disabled = true: op[2].disabled = false;

You may see how it works here:

https://jsfiddle.net/chetabahana/f7ejxhnk/28/

Using python's eval() vs. ast.literal_eval()?

If all you need is a user provided dictionary, possible better solution is json.loads. The main limitation is that json dicts requires string keys. Also you can only provide literal data, but that is also the case for literal_eval.

Bootstrap modal: close current, open new

By using the following code you can hide first modal and immediately open second modal, by using same strategy you can hide second modal and show the first one.

$("#buttonId").on("click", function(){
    $("#currentModalId").modal("hide");
    $("#currentModalId").on("hidden.bs.modal",function(){
    $("#newModalId").modal("show");
    });
});

How to prevent a file from direct URL Access?

Based on your comments looks like this is what you need:

RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost/ [NC] 
RewriteRule \.(jpe?g|gif|bmp|png)$ - [F,NC]

I have tested it on my localhost and it seems to be working fine.

Necessary to add link tag for favicon.ico?

Please note that both the HTML5 specification of W3C and WhatWG standardize

<link rel="icon" href="/favicon.ico">

Note the value of the "rel" attribute!

The value shortcut icon for the rel attribute is a very old Internet Explorer specific extension and deprecated.

So please consider not using it any more and updating your files so they are standards compliant and are displayed correctly in all browsers.

You might also want to take a look at this great post: rel="shortcut icon" considered harmful

Adding an img element to a div with javascript

The following solution seems to be a much shorter version for that:

<div id="imageDiv"></div>

In Javascript:

document.getElementById('imageDiv').innerHTML = '<img width="100" height="100" src="images/hydrangeas.jpg">';

A Space between Inline-Block List Items

I would add the CSS property of float left as seen below. That gets rid of the extra space.

ul li {
    float:left;
}

error: the details of the application error from being viewed remotely

In my case I got this message because there's a special char (&) in my connectionstring, remove it then everything's good.

Cheers

Drop default constraint on a column in TSQL

I would like to refer a previous question, Because I have faced same problem and solved by this solution. First of all a constraint is always built with a Hash value in it's name. So problem is this HASH is varies in different Machine or Database. For example DF__Companies__IsGlo__6AB17FE4 here 6AB17FE4 is the hash value(8 bit). So I am referring a single script which will be fruitful to all

DECLARE @Command NVARCHAR(MAX)
     declare @table_name nvarchar(256)
     declare @col_name nvarchar(256)
     set @table_name = N'ProcedureAlerts'
     set @col_name = N'EmailSent'

     select @Command ='Alter Table dbo.ProcedureAlerts Drop Constraint [' + ( select d.name
     from 
         sys.tables t
         join sys.default_constraints d on d.parent_object_id = t.object_id
         join sys.columns c on c.object_id = t.object_id
                               and c.column_id = d.parent_column_id
     where 
         t.name = @table_name
         and c.name = @col_name) + ']'

    --print @Command
    exec sp_executesql @Command

It will drop your default constraint. However if you want to create it again you can simply try this

ALTER TABLE [dbo].[ProcedureAlerts] ADD DEFAULT((0)) FOR [EmailSent]

Finally, just simply run a DROP command to drop the column.

MVC Razor @foreach

The answer will not work when using the overload to indicate the template @Html.DisplayFor(x => x.Foos, "YourTemplateName) .

Seems to be designed that way, see this case. Also the exception the framework gives (about the type not been as expected) is quite misleading and fooled me on the first try (thanks @CodeCaster)

In this case you have to use @foreach

@foreach (var item in Model.Foos)
{
    @Html.DisplayFor(x => item, "FooTemplate")
}

When you use 'badidea' or 'thisisunsafe' to bypass a Chrome certificate/HSTS error, does it only apply for the current site?

The SSL errors are often thrown by network management software such as Cyberroam.

To answer your question,

you will have to enter badidea into Chrome every time you visit a website.

You might at times have to enter it more than once, as the site may try to pull in various resources before load, hence causing multiple SSL errors

Sample database for exercise

Why not download the English Wikipedia? There are compressed SQL files of various sizes, and it should certainly be large enough for you

The main articles are XML, so inserting them into the db is a bit more of a problem, but you might find there are other files there that suit you. For example, the inter-page links SQL file is 2.3GB compressed. Have a look at https://en.wikipedia.org/wiki/Wikipedia:Database_download for more info.

Oskar

What is the syntax for an inner join in LINQ to SQL?

Use LINQ joins to perform Inner Join.

var employeeInfo = from emp in db.Employees
                   join dept in db.Departments
                   on emp.Eid equals dept.Eid 
                   select new
                   {
                    emp.Ename,
                    dept.Dname,
                    emp.Elocation
                   };

Oracle Insert via Select from multiple tables where one table may not have a row

Try:

insert into account_type_standard (account_type_Standard_id, tax_status_id, recipient_id)
select account_type_standard_seq.nextval,
       ts.tax_status_id, 
       ( select r.recipient_id
         from recipient r
         where r.recipient_code = ?
       )
from tax_status ts
where ts.tax_status_code = ?

Filter df when values matches part of a string in pyspark

When filtering a DataFrame with string values, I find that the pyspark.sql.functions lower and upper come in handy, if your data could have column entries like "foo" and "Foo":

import pyspark.sql.functions as sql_fun
result = source_df.filter(sql_fun.lower(source_df.col_name).contains("foo"))

How to put/get multiple JSONObjects to JSONArray?

From android API Level 19, when I want to instance JSONArray object I put JSONObject directly as parameter like below:

JSONArray jsonArray=new JSONArray(jsonObject);

JSONArray has constructor to accept object.

macOS on VMware doesn't recognize iOS device

I am running an Iphone 8+ and VMWare macOS High Sierra on a Windows 10 machine.

I went through dozens of troubleshooting posts, and the none of them, excluding setting your VMs USBs to 2.0, helped. Through trial and error, and a decent amount of liquor, I have figured it out.

SOLUTION:

Do these things, in this order:

  1. With the VM off, go to your settings for whichever machine you're using, and change the USBs to 2.0. You can find this in the same menu that you allocated your ram and cores

  2. Make sure your phone is plugged in, and turned off.

  3. Boot up the VM, macOS.

  4. Turn Phone on when mac is booted

  5. Open Xcode

How to store JSON object in SQLite database

Convert JSONObject into String and save as TEXT/ VARCHAR. While retrieving the same column convert the String into JSONObject.

For example

Write into DB

String stringToBeInserted = jsonObject.toString();
//and insert this string into DB

Read from DB

String json = Read_column_value_logic_here
JSONObject jsonObject = new JSONObject(json);

C# Passing Function as Argument

Using the Func as mentioned above works but there are also delegates that do the same task and also define intent within the naming:

public delegate double MyFunction(double x);

public double Diff(double x, MyFunction f)
{
    double h = 0.0000001;

    return (f(x + h) - f(x)) / h;
}

public double MyFunctionMethod(double x)
{
    // Can add more complicated logic here
    return x + 10;
}

public void Client()
{
    double result = Diff(1.234, x => x * 456.1234);
    double secondResult = Diff(2.345, MyFunctionMethod);
}

Can functions be passed as parameters?

This is the simplest way I can come with.

package main

import "fmt"

func main() {
    g := greeting
    getFunc(g)
}

func getFunc(f func()) {
    f()
}

func greeting() {
    fmt.Println("Hello")
}

Restart android machine

I think the only way to do this is to run another machine in parallel and use that machine to issue commands to your android box similar to how you would with a phone. If you have issues with the IP changing you can reserve an ip on your router and have the machine grab that one instead of asking the routers DHCP for one. This way you can ping the machine and figure out if it's done rebooting to continue the script.

Specifying width and height as percentages without skewing photo proportions in HTML

From W3Schools

The height in percent of the containing element (like "20%").

So I think they mean the element where the div is in?

How to list all AWS S3 objects in a bucket using Java

Listing Keys Using the AWS SDK for Java

http://docs.aws.amazon.com/AmazonS3/latest/dev/ListingObjectKeysUsingJava.html

import java.io.IOException;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.ListObjectsRequest;
import com.amazonaws.services.s3.model.ListObjectsV2Request;
import com.amazonaws.services.s3.model.ListObjectsV2Result;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.s3.model.S3ObjectSummary;

public class ListKeys {
    private static String bucketName = "***bucket name***";

    public static void main(String[] args) throws IOException {
        AmazonS3 s3client = new AmazonS3Client(new ProfileCredentialsProvider());
        try {
            System.out.println("Listing objects");
            final ListObjectsV2Request req = new ListObjectsV2Request().withBucketName(bucketName);
            ListObjectsV2Result result;
            do {               
               result = s3client.listObjectsV2(req);

               for (S3ObjectSummary objectSummary : 
                   result.getObjectSummaries()) {
                   System.out.println(" - " + objectSummary.getKey() + "  " +
                           "(size = " + objectSummary.getSize() + 
                           ")");
               }
               System.out.println("Next Continuation Token : " + result.getNextContinuationToken());
               req.setContinuationToken(result.getNextContinuationToken());
            } while(result.isTruncated() == true ); 

         } catch (AmazonServiceException ase) {
            System.out.println("Caught an AmazonServiceException, " +
                    "which means your request made it " +
                    "to Amazon S3, but was rejected with an error response " +
                    "for some reason.");
            System.out.println("Error Message:    " + ase.getMessage());
            System.out.println("HTTP Status Code: " + ase.getStatusCode());
            System.out.println("AWS Error Code:   " + ase.getErrorCode());
            System.out.println("Error Type:       " + ase.getErrorType());
            System.out.println("Request ID:       " + ase.getRequestId());
        } catch (AmazonClientException ace) {
            System.out.println("Caught an AmazonClientException, " +
                    "which means the client encountered " +
                    "an internal error while trying to communicate" +
                    " with S3, " +
                    "such as not being able to access the network.");
            System.out.println("Error Message: " + ace.getMessage());
        }
    }
}

Big O, how do you calculate/approximate it?

Less useful generally, I think, but for the sake of completeness there is also a Big Omega O, which defines a lower-bound on an algorithm's complexity, and a Big Theta T, which defines both an upper and lower bound.

Visual Studio 2010 - recommended extensions

  1. Plugin to quickly go to any file in solution Sonic file finder (free)

  2. Fast switching between .h and .cpp file Macro available here (free)

And that's it =)

How do I lowercase a string in Python?

With Python 2, this doesn't work for non-English words in UTF-8. In this case decode('utf-8') can help:

>>> s='????????'
>>> print s.lower()
????????
>>> print s.decode('utf-8').lower()
????????

Powershell: count members of a AD group

In Powershell, you'll need to import the active directory module, then use the get-adgroupmember, and then measure-object. For example, to get the number of users belonging to the group "domain users", do the following:

Import-Module activedirecotry
Get-ADGroupMember "domain users" | Measure-Object

When entering the group name after "Get-ADGroupMember", if the name is a single string with no spaces, then no quotes are necessary. If the group name has spaces in it, use the quotes around it.

The output will look something like:

Count    : 12345
Average  :
Sum      :
Maximum  :
Minimum  :
Property :

Note - importing the active directory module may be redundant if you're already using PowerShell for other AD admin tasks.

python time + timedelta equivalent

You can change time() to now() for it to work

from datetime import datetime, timedelta
datetime.now() + timedelta(hours=1)

How to call a function after a div is ready?

To do something after certain div load from function .load(). I think this exactly what you need:

  $('#divIDer').load(document.URL +  ' #divIDer',function() {

       // call here what you want .....


       //example
       $('#mydata').show();
  });

Usage of __slots__?

Slots are very useful for library calls to eliminate the "named method dispatch" when making function calls. This is mentioned in the SWIG documentation. For high performance libraries that want to reduce function overhead for commonly called functions using slots is much faster.

Now this may not be directly related to the OPs question. It is related more to building extensions than it does to using the slots syntax on an object. But it does help complete the picture for the usage of slots and some of the reasoning behind them.

How do I properly escape quotes inside HTML attributes?

Per HTML syntax, and even HTML5, the following are all valid options:

<option value="&quot;asd">test</option>
<option value="&#34;asd">test</option>
<option value='"asd'>test</option>
<option value='&quot;asd'>test</option>
<option value='&#34;asd'>test</option>
<option value=&quot;asd>test</option>
<option value=&#34;asd>test</option>

Note that if you are using XML syntax the quotes (single or double) are required.

Here's a jsfiddle showing all of the above working.

Can't connect to MySQL server on 'localhost' (10061) after Installation

For anyone who have the same problem of "Can't connect to MySQL server on 'localhost' (10061) " or "Can't connect to MySQL server on '127.0.0.1' (10061) ". You can install "MySQL Installer" and this is the link http://dev.mysql.com/downloads/windows/installer/5.6.html and this is a tutoriel for more help https://www.youtube.com/watch?v=AqQc3YqfelE

it works for me and i wish to work for you too.

Change Color of Fonts in DIV (CSS)

To do links, you can do

.social h2 a:link {
  color: pink;
  font-size: 14px;   
}

You can change the hover, visited, and active link styling too. Just replace "link" with what you want to style. You can learn more at the w3schools page CSS Links.

What is a unix command for deleting the first N characters of a line?

I think awk would be the best tool for this as it can both filter and perform the necessary string manipulation functions on filtered lines:

tail -f logfile | awk '/org.springframework/ {print substr($0, 6)}'

or

tail -f logfile | awk '/org.springframework/ && sub(/^.{5}/,"",$0)'

WCF Error "This could be due to the fact that the server certificate is not configured properly with HTTP.SYS in the HTTPS case"

If your WCF service is using .net framework 4.0 and someone has disabled TLS 1.0 on the server then you will see this exception. Due to .net 4.0 not supporting the higher versions of TLS.

Supported protocols: https://msdn.microsoft.com/en-us/library/system.security.authentication.sslprotocols(v=vs.100).aspx

Extract data from log file in specified range of time

I used this command to find last 5 minutes logs for particular event "DHCPACK", try below:

$ grep "DHCPACK" /var/log/messages | grep "$(date +%h\ %d) [$(date --date='5 min ago' %H)-$(date +%H)]:*:*"

Pagination using MySQL LIMIT, OFFSET

A dozen pages is not a big deal when using OFFSET. But when you have hundreds of pages, you will find that OFFSET is bad for performance. This is because all the skipped rows need to be read each time.

It is better to remember where you left off.

ASP.NET MVC passing an ID in an ActionLink to the controller

The ID will work with @ sign in front also, but we have to add one parameter after that. that is null

look like:

@Html.ActionLink("Label Name", "Name_Of_Page_To_Redirect", "Controller", new {@id="Id_Value"}, null)

.do extension in web pages?

It is whatever it is configured to be on that particular web server. A web server could be configured to run .pl files with the php module and .aspx files with perl, although that would be silly. There are no scripts involved with most web servers, instead you'd have to look in your apache configuration files (or equivalent, if using different server software). If you have permission to edit the server config file, then you could make files ending in .do run as php, if that's what you're after.

How do you set the Content-Type header for an HttpClient request?

You can use this it will be work!

HttpRequestMessage msg = new HttpRequestMessage(HttpMethod.Get,"URL");
msg.Content = new StringContent(string.Empty, Encoding.UTF8, "application/json");

HttpResponseMessage response = await _httpClient.SendAsync(msg);
response.EnsureSuccessStatusCode();

string json = await response.Content.ReadAsStringAsync();

Validate that end date is greater than start date with jQuery

$(document).ready(function(){
   $("#txtFromDate").datepicker({
        minDate: 0,
        maxDate: "+60D",
        numberOfMonths: 2,
        onSelect: function(selected) {
          $("#txtToDate").datepicker("option","minDate", selected)
        }
    });

    $("#txtToDate").datepicker({
        minDate: 0,
        maxDate:"+60D",
        numberOfMonths: 2,
        onSelect: function(selected) {
           $("#txtFromDate").datepicker("option","maxDate", selected)
        }
    });
});

Or Visit to this link

Run Command Prompt Commands

Tried @RameshVel solution but I could not pass arguments in my console application. If anyone experiences the same problem here is a solution:

using System.Diagnostics;

Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.UseShellExecute = false;
cmd.Start();

cmd.StandardInput.WriteLine("echo Oscar");
cmd.StandardInput.Flush();
cmd.StandardInput.Close();
cmd.WaitForExit();
Console.WriteLine(cmd.StandardOutput.ReadToEnd());

Android Studio Stuck at Gradle Download on create new project

Invalidate Caches and Restart

It worked for me.

no debugging symbols found when using gdb

Some Linux distributions don't use the gdb style debugging symbols. (IIRC they prefer dwarf2.)

In general, gcc and gdb will be in sync as to what kind of debugging symbols they use, and forcing a particular style will just cause problems; unless you know that you need something else, use just -g.

GET URL parameter in PHP

$Query_String  = explode("&", explode("?", $_SERVER['REQUEST_URI'])[1] );
var_dump($Query_String)

Array ( [ 0] => link=www.google.com )

How to make Java honor the DNS Caching Timeout?

To expand on Byron's answer, I believe you need to edit the file java.security in the %JRE_HOME%\lib\security directory to effect this change.

Here is the relevant section:

#
# The Java-level namelookup cache policy for successful lookups:
#
# any negative value: caching forever
# any positive value: the number of seconds to cache an address for
# zero: do not cache
#
# default value is forever (FOREVER). For security reasons, this
# caching is made forever when a security manager is set. When a security
# manager is not set, the default behavior is to cache for 30 seconds.
#
# NOTE: setting this to anything other than the default value can have
#       serious security implications. Do not set it unless 
#       you are sure you are not exposed to DNS spoofing attack.
#
#networkaddress.cache.ttl=-1 

Documentation on the java.security file here.

MySQL - SELECT all columns WHERE one column is DISTINCT

SELECT DISTINCT link,id,day,month FROM posted WHERE ad='$key' ORDER BY day, month

OR

SELECT link,id,day,month FROM posted WHERE ad='$key' ORDER BY day, month

Can I update a component's props in React.js?

Trick to update props if they are array :

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

class Counter extends Component {
  constructor(props) {
    super(props);
      this.state = {
        count: this.props.count
      }
    }
  increment(){
    console.log("this.props.count");
    console.log(this.props.count);
    let count = this.state.count
    count.push("new element");
    this.setState({ count: count})
  }
  render() {

    return (
      <View style={styles.container}>
        <Text>{ this.state.count.length }</Text>
        <Button
          onPress={this.increment.bind(this)}
          title={ "Increase" }
        />
      </View>
    );
  }
}

Counter.defaultProps = {
 count: []
}

export default Counter
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

Should I put input elements inside a label element?

I usually go with the first two options. I've seen a scenario when the third option was used, when radio choices where embedded in labels and the css contained something like

label input {
    vertical-align: bottom;
}

in order to ensure proper vertical alignment for the radios.

Rewrite URL after redirecting 404 error htaccess

In your .htaccess file , if you are using apache you can try with

Rule for Error Page - 404

ErrorDocument 404 http://www.domain.com/notFound.html

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 13: ordinal not in range(128)

You can try this also:

import sys
reload(sys)
sys.setdefaultencoding('utf8')

"java.lang.OutOfMemoryError : unable to create new native Thread"

I encountered same issue during the load test, the reason is because of JVM is unable to create a new Java thread further. Below is the JVM source code

if (native_thread->osthread() == NULL) {    
// No one should hold a reference to the 'native_thread'.    
    delete native_thread;   
if (JvmtiExport::should_post_resource_exhausted()) {      
    JvmtiExport::post_resource_exhausted(        
        JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR | 
        JVMTI_RESOURCE_EXHAUSTED_THREADS, 
        "unable to create new native thread");    
    } THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(), "unable to create new native thread");  
} Thread::start(native_thread);`

Root cause : JVM throws this exception when JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR (resources exhausted (means memory exhausted) ) or JVMTI_RESOURCE_EXHAUSTED_THREADS (Threads exhausted).

In my case Jboss is creating too many threads , to serve the request, but all the threads are blocked . Because of this, JVM is exhausted with threads as well with memory (each thread holds memory , which is not released , because each thread is blocked).

Analyzed the java thread dumps observed nearly 61K threads are blocked by one of our method, which is causing this issue . Below is the portion of Thread dump

"SimpleAsyncTaskExecutor-16562" #38070 prio=5 os_prio=0 tid=0x00007f9985440000 nid=0x2ca6 waiting for monitor entry [0x00007f9d58c2d000]
   java.lang.Thread.State: BLOCKED (on object monitor)

Command line for looking at specific port

This will help you

netstat -atn | grep <port no>          # For tcp
netstat -aun | grep <port no>           # For udp
netstat -atun | grep <port no>          # For both

How to post JSON to PHP with curl

I believe you are getting an empty array because PHP is expecting the posted data to be in a Querystring format (key=value&key1=value1).

Try changing your curl request to:

curl -i -X POST -d 'json={"screencast":{"subject":"tools"}}'  \
      http://localhost:3570/index.php/trainingServer/screencast.json

and see if that helps any.

take(1) vs first()

Tip: Only use first() if:

  • You consider zero items emitted to be an error condition (eg. completing before emitting) AND if there’s a greater than 0% chance of error you handling it gracefully
  • OR You know 100% that the source observable will emit 1+ items (so can never throw).

If there are zero emissions and you are not explicitly handling it (with catchError) then that error will get propagated up, possibly cause an unexpected problem somewhere else and can be quite tricky to track down - especially if it's coming from an end user.

You're safer off using take(1) for the most part provided that:

  • You're OK with take(1) not emitting anything if the source completes without an emission.
  • You don't need to use an inline predicate (eg. first(x => x > 10) )

Note: You can use a predicate with take(1) like this: .pipe( filter(x => x > 10), take(1) ). There is no error with this if nothing is ever greater than 10.

What about single()

If you want to be even stricter, and disallow two emissions you can use single() which errors if there are zero or 2+ emissions. Again you'd need to handle errors in that case.

Tip: Single can occasionally be useful if you want to ensure your observable chain isn't doing extra work like calling an http service twice and emitting two observables. Adding single to the end of the pipe will let you know if you made such a mistake. I'm using it in a 'task runner' where you pass in a task observable that should only emit one value, so I pass the response through single(), catchError() to guarantee good behavior.


Why not always use first() instead of take(1) ?

aka. How can first potentially cause more errors?

If you have an observable that takes something from a service and then pipes it through first() you should be fine most of the time. But if someone comes along to disable the service for whatever reason - and changes it to emit of(null) or NEVER then any downstream first() operators would start throwing errors.

Now I realize that might be exactly what you want - hence why this is just a tip. The operator first appealed to me because it sounded slightly less 'clumsy' than take(1) but you need to be careful about handling errors if there's ever a chance of the source not emitting. Will entirely depend on what you're doing though.


If you have a default value (constant):

Consider also .pipe(defaultIfEmpty(42), first()) if you have a default value that should be used if nothing is emitted. This would of course not raise an error because first would always receive a value.

Note that defaultIfEmpty is only triggered if the stream is empty, not if the value of what is emitted is null.

Return content with IHttpActionResult for non-OK response

A more detailed example with support of HTTP code not defined in C# HttpStatusCode.

public class MyController : ApiController
{
    public IHttpActionResult Get()
    {
        HttpStatusCode codeNotDefined = (HttpStatusCode)429;
        return Content(codeNotDefined, "message to be sent in response body");
    }
}

Content is a virtual method defined in abstract class ApiController, the base of the controller. See the declaration as below:

protected internal virtual NegotiatedContentResult<T> Content<T>(HttpStatusCode statusCode, T value);

INSERT SELECT statement in Oracle 11G

Your query should be:

insert into table1 (col1, col2) 
select t1.col1, t2.col2 
from oldtable1 t1, oldtable2 t2

I.e. without the VALUES part.

.append(), prepend(), .after() and .before()

The best way is going to documentation.

.append() vs .after()

  • .append(): Insert content, specified by the parameter, to the end of each element in the set of matched elements.
  • .after(): Insert content, specified by the parameter, after each element in the set of matched elements.

.prepend() vs .before()

  • prepend(): Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.
  • .before(): Insert content, specified by the parameter, before each element in the set of matched elements.

So, append and prepend refers to child of the object whereas after and before refers to sibling of the the object.

Return file in ASP.Net Core Web API

Here is a simplistic example of streaming a file:

using System.IO;
using Microsoft.AspNetCore.Mvc;
[HttpGet("{id}")]
public async Task<FileStreamResult> Download(int id)
{
    var path = "<Get the file path using the ID>";
    var stream = File.OpenRead(path);
    return new FileStreamResult(stream, "application/octet-stream");
}

Note:

Be sure to use FileStreamResult from Microsoft.AspNetCore.Mvc and not from System.Web.Mvc.

How to bundle vendor scripts separately and require them as needed with Webpack?

In case you're interested in bundling automatically your scripts separately from vendors ones:

var webpack = require('webpack'),
    pkg     = require('./package.json'),  //loads npm config file
    html    = require('html-webpack-plugin');

module.exports = {
  context : __dirname + '/app',
  entry   : {
    app     : __dirname + '/app/index.js',
    vendor  : Object.keys(pkg.dependencies) //get npm vendors deps from config
  },
  output  : {
    path      : __dirname + '/dist',
    filename  : 'app.min-[hash:6].js'
  },
  plugins: [
    //Finally add this line to bundle the vendor code separately
    new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.min-[hash:6].js'),
    new html({template : __dirname + '/app/index.html'})
  ]
};

You can read more about this feature in official documentation.

Display Parameter(Multi-value) in Report

You can use the "Join" function to create a single string out of the array of labels, like this:

=Join(Parameters!Product.Label, ",")

Authentication failed for https://xxx.visualstudio.com/DefaultCollection/_git/project

I've tried lots of options, but the one that worked for me was to:

  1. Download the Git Password Manager from its Releases section

  2. Try to do simple git fetch which will automatically bring the window(alternate to default windows one for example) and ask to enter username and password but with more elegant way than the standard one.

After correctly entering the credentials it worked, though I was getting an error before.

P.S. If you are getting "Wrong Credentials" kind of errors always check if the repository username and password are correct. If you hesitate just reset the password and try to use the same one in the Git Password manager window.

How do I convert an ANSI encoded file to UTF-8 with Notepad++?

Maybe this is not the answer you needed, but I encountered similar problem, so I decided to put it here.

I needed to convert 500 xml files to UTF8 via Notepad++. Why Notepad++? When I used the option "Encode in UTF8" (many other converters use the same logic) it messed up all special characters, so I had to use "Convert to UTF8" explicitly.


Here some simple steps to convert multiple files via Notepad++ without messing up with special characters (for ex. diacritical marks).

  1. Run Notepad++ and then open menu Plugins->Plugin Manager->Show Plugin Manager
  2. Install Python Script. When plugin is installed, restart the application.
  3. Choose menu Plugins->Python Script->New script.
  4. Choose its name, and then past the following code:

convertToUTF8.py

import os
import sys
from Npp import notepad # import it first!

filePathSrc="C:\\Users\\" # Path to the folder with files to convert
for root, dirs, files in os.walk(filePathSrc):
    for fn in files: 
        if fn[-4:] == '.xml': # Specify type of the files
            notepad.open(root + "\\" + fn)      
            notepad.runMenuCommand("Encoding", "Convert to UTF-8")
            # notepad.save()
            # if you try to save/replace the file, an annoying confirmation window would popup.
            notepad.saveAs("{}{}".format(fn[:-4], '_utf8.xml')) 
            notepad.close()

After all, run the script

How to Check if value exists in a MySQL database

For Exact Match

"SELECT * FROM yourTable WHERE city = 'c7'"

For Pattern / Wildcard Search

"SELECT * FROM yourTable WHERE city LIKE '%c7%'"

Of course you can change '%c7%' to '%c7' or 'c7%' depending on how you want to search it. For exact match, use first query example.

PHP

$result = mysql_query("SELECT * FROM yourTable WHERE city = 'c7'");
$matchFound = mysql_num_rows($result) > 0 ? 'yes' : 'no';
echo $matchFound;

You can also use if condition there.

Read the package name of an Android APK

The following bash script will display the package name and the main activity name:

apk_package.sh

package=$(aapt dump badging "$*" | awk '/package/{gsub("name=|'"'"'","");  print $2}')
activity=$(aapt dump badging "$*" | awk '/activity/{gsub("name=|'"'"'","");  print $2}')
echo
echo "   file : $1"
echo "package : $package"
echo "activity: $activity"

run it like so:

apk_package.sh /path/to/my.apk

OpenSSL Verify return code: 20 (unable to get local issuer certificate)

Create the certificate chain file with the intermediate and root ca.

cat intermediate/certs/intermediate.cert.pem certs/ca.cert.pem > intermediate/certs/ca-chain.cert.pem

chmod 444 intermediate/certs/ca-chain.cert.pem

Then verfify

openssl verify -CAfile intermediate/certs/ca-chain.cert.pem \
  intermediate/certs/www.example.com.cert.pem

www.example.com.cert.pem: OK Deploy the certific

Wireshark localhost traffic capture

For some reason, none of previous answers worked in my case, so I'll post something that did the trick. There is a little jewel called RawCap that can capture localhost traffic on Windows. Advantages:

  • only 17 kB!
  • no external libraries needed
  • extremely simple to use (just start it, choose the loopback interface and destination file and that's all)

After the traffic has been captured, you can open it and examine in Wireshark normally. The only disadvantage that I found is that you cannot set filters, i.e. you have to capture all localhost traffic which can be heavy. There is also one bug regarding Windows XP SP 3.

Few more advices:

mongodb service is not starting up

I had struggled with the similar issue and sharing the solution accordingly. We use a mongo replica set and mongo service on my secondary server was taking too long to start. (approx 10-15 minutes)

Couldn't find anything until attempted to configure the mongo with some different folder in --dbpath And that worked fine, so we got to know that the earlier path, which was a mount directory had some issues. So followed with nss team to get the network mount issue solved.

Hope this helps someone

What is the boundary in multipart/form-data?

multipart/form-data contains boundary to separate name/value pairs. The boundary acts like a marker of each chunk of name/value pairs passed when a form gets submitted. The boundary is automatically added to a content-type of a request header.

The form with enctype="multipart/form-data" attribute will have a request header Content-Type : multipart/form-data; boundary --- WebKit193844043-h (browser generated vaue).

The payload passed looks something like this:

Content-Type: multipart/form-data; boundary=---WebKitFormBoundary7MA4YWxkTrZu0gW

    -----WebKitFormBoundary7MA4YWxkTrZu0gW
    Content-Disposition: form-data; name=”file”; filename=”captcha”
    Content-Type:

    -----WebKitFormBoundary7MA4YWxkTrZu0gW
    Content-Disposition: form-data; name=”action”

    submit
    -----WebKitFormBoundary7MA4YWxkTrZu0gW--

On the webservice side, it's consumed in @Consumes("multipart/form-data") form.

Beware, when testing your webservice using chrome postman, you need to check the form data option(radio button) and File menu from the dropdown box to send attachment. Explicit provision of content-type as multipart/form-data throws an error. Because boundary is missing as it overrides the curl request of post man to server with content-type by appending the boundary which works fine.

See RFC1341 sec7.2 The Multipart Content-Type

How to find length of digits in an integer?

def length(i):
  return len(str(i))

Eclipse error "ADB server didn't ACK, failed to start daemon"

I had the same problem. But there was no process of adb on my laptop. I just log out and log in to my account, and it's resolved...

ADB could start from CMD windows after that.

Escaping ampersand in URL

You can use the % character to 'escape' characters that aren't allowed in URLs. See [RFC 1738].

A table of ASCII values on http://www.asciitable.com/.

You can see & is 26 in hexadecimal - so you need M%26M.

Can I have multiple :before pseudo-elements for the same element?

If your main element has some child elements or text, you could make use of it.

Position your main element relative (or absolute/fixed) and use both :before and :after positioned absolute (in my situation it had to be absolute, don't know about your's).

Now if you want one more pseudo-element, attach an absolute :before to one of the main element's children (if you have only text, put it in a span, now you have an element), which is not relative/absolute/fixed.

This element will start acting like his owner is your main element.

HTML

<div class="circle">
    <span>Some text</span>
</div>

CSS

.circle {
    position: relative; /* or absolute/fixed */
}

.circle:before {
    position: absolute;
    content: "";
    /* more styles: width, height, etc */
}

.circle:after {
    position: absolute;
    content: "";
    /* more styles: width, height, etc */
}

.circle span {
    /* not relative/absolute/fixed */
}

.circle span:before {
    position: absolute;
    content: "";
    /* more styles: width, height, etc */
}

jQuery find parent form

I would suggest using closest, which selects the closest matching parent element:

$('input[name="submitButton"]').closest("form");

Instead of filtering by the name, I would do this:

$('input[type=submit]').closest("form");

error: No resource identifier found for attribute 'adSize' in package 'com.google.example' main.xml

I also faced the same problem, I was using GoogleAdMobAdsSDK-4.1.0.jar then I tried with GoogleAdMobAdsSDK-4.0.4.jar now it is working fine, It is problem with jar file as per my experience.

In Java, how do I check if a string contains a substring (ignoring case)?

How about matches()?

String string = "Madam, I am Adam";

// Starts with
boolean  b = string.startsWith("Mad");  // true

// Ends with
b = string.endsWith("dam");             // true

// Anywhere
b = string.indexOf("I am") >= 0;        // true

// To ignore case, regular expressions must be used

// Starts with
b = string.matches("(?i)mad.*");

// Ends with
b = string.matches("(?i).*adam");

// Anywhere
b = string.matches("(?i).*i am.*");

How To Set A JS object property name from a variable

It does not matter where the variable comes from. Main thing we have one ... Set the variable name between square brackets "[ .. ]".

var optionName = 'nameA';
var JsonVar = {
[optionName] : 'some value'
}

Check if ADODB connection is open

ADO Recordset has .State property, you can check if its value is adStateClosed or adStateOpen

If Not (rs Is Nothing) Then
  If (rs.State And adStateOpen) = adStateOpen Then rs.Close
  Set rs = Nothing
End If

MSDN about State property

Edit; The reason not to check .State against 1 or 0 is because even if it works 99.99% of the time, it is still possible to have other flags set which will cause the If statement fail the adStateOpen check.

Edit2:

For Late binding without the ActiveX Data Objects referenced, you have few options. Use the value of adStateOpen constant from ObjectStateEnum

If Not (rs Is Nothing) Then
  If (rs.State And 1) = 1 Then rs.Close
  Set rs = Nothing
End If

Or you can define the constant yourself to make your code more readable (defining them all for a good example.)

Const adStateClosed As Long = 0 'Indicates that the object is closed.
Const adStateOpen As Long = 1 'Indicates that the object is open.
Const adStateConnecting As Long = 2 'Indicates that the object is connecting.
Const adStateExecuting As Long = 4 'Indicates that the object is executing a command.
Const adStateFetching As Long = 8 'Indicates that the rows of the object are being retrieved.    

[...]

If Not (rs Is Nothing) Then

    ' ex. If (0001 And 0001) = 0001 (only open flag) -> true
    ' ex. If (1001 And 0001) = 0001 (open and retrieve) -> true
    '    This second example means it is open, but its value is not 1
    '    and If rs.State = 1 -> false, even though it is open
    If (rs.State And adStateOpen) = adStateOpen Then 
        rs.Close
    End If

    Set rs = Nothing
End If

How can I check if a view is visible or not in Android?

Although View.getVisibility() does get the visibility, its not a simple true/false. A view can have its visibility set to one of three things.

View.VISIBLE The view is visible.

View.INVISIBLE The view is invisible, but any spacing it would normally take up will still be used. Its "invisible"

View.GONE The view is gone, you can't see it and it doesn't take up the "spot".

So to answer your question, you're looking for:

if (myImageView.getVisibility() == View.VISIBLE) {
    // Its visible
} else {
    // Either gone or invisible
}

CSS - display: none; not working

This is because the inline style display:block is overwriting your CSS. You'll need to either remove this inline style or use:

#tfl {
  display: none !important;
}

This overrides inline styles. Note that using !important is generally not recommended unless it's a last resort.

What does the shrink-to-fit viewport meta attribute do?

It is Safari specific, at least at time of writing, being introduced in Safari 9.0. From the "What's new in Safari?" documentation for Safari 9.0:

Viewport Changes

Viewport meta tags using "width=device-width" cause the page to scale down to fit content that overflows the viewport bounds. You can override this behavior by adding "shrink-to-fit=no" to your meta tag as shown below. The added value will prevent the page from scaling to fit the viewport.

<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">

In short, adding this to the viewport meta tag restores pre-Safari 9.0 behaviour.

Example

Here's a worked visual example which shows the difference upon loading the page in the two configurations.

The red section is the width of the viewport and the blue section is positioned outside the initial viewport (eg left: 100vw). Note how in the first example the page is zoomed to fit when shrink-to-fit=no is omitted (thus showing the out-of-viewport content) and the blue content remains off screen in the latter example.

The code for this example can be found at https://codepen.io/davidjb/pen/ENGqpv.

Without shrink-to-fit specified

Without shrink-to-fit=no

With shrink-to-fit=no

With shrink-to-fit=no

How to create separate AngularJS controller files?

File one:

angular.module('myApp.controllers', []);

File two:

angular.module('myApp.controllers').controller('Ctrl1', ['$scope', '$http', function($scope, $http){

}]);

File three:

angular.module('myApp.controllers').controller('Ctrl2', ['$scope', '$http', function($scope, $http){

}]);

Include in that order. I recommend 3 files so the module declaration is on its own.


As for folder structure there are many many many opinions on the subject, but these two are pretty good

https://github.com/angular/angular-seed

http://briantford.com/blog/huuuuuge-angular-apps.html

How to view log output using docker-compose run?

Update July 1st 2019

docker-compose logs <name-of-service>

From the documentation:

Usage: logs [options] [SERVICE...]

Options:

--no-color Produce monochrome output.

-f, --follow Follow log output.

-t, --timestamps Show timestamps.

--tail="all" Number of lines to show from the end of the logs for each container.

See docker logs

You can start Docker compose in detached mode and attach yourself to the logs of all container later. If you're done watching logs you can detach yourself from the logs output without shutting down your services.

  1. Use docker-compose up -d to start all services in detached mode (-d) (you won't see any logs in detached mode)
  2. Use docker-compose logs -f -t to attach yourself to the logs of all running services, whereas -f means you follow the log output and the -t option gives you timestamps (See Docker reference)
  3. Use Ctrl + z or Ctrl + c to detach yourself from the log output without shutting down your running containers

If you're interested in logs of a single container you can use the docker keyword instead:

  1. Use docker logs -t -f <name-of-service>

Save the output

To save the output to a file you add the following to your logs command:

  1. docker-compose logs -f -t >> myDockerCompose.log

Add a CSS class to <%= f.submit %>

Solution When Using form_with helper

<%= f.submit, "Submit", class: 'btn btn-primary' %>

Don't forget the comma after the f.submit method!

HTH!

Change Date Format(DD/MM/YYYY) in SQL SELECT Statement

Changed to:

SELECT FORMAT(SA.[RequestStartDate],'dd/MM/yyyy') as 'Service Start Date', SA.[RequestEndDate] as 'Service End Date', FROM (......)SA WHERE......

Have no idea which SQL engine you are using, for other SQL engine, CONVERT can be used in SELECT statement to change the format in the form you needed.

Python strip() multiple characters?

For example string s="(U+007c)"

To remove only the parentheses from s, try the below one:

import re
a=re.sub("\\(","",s)
b=re.sub("\\)","",a)
print(b)

Using jQuery To Get Size of Viewport

function showViewPortSize(display) {
    if (display) {
        var height = window.innerHeight;
        var width = window.innerWidth;
        jQuery('body')
            .prepend('<div id="viewportsize" style="z-index:9999;position:fixed;bottom:0px;left:0px;color:#fff;background:#000;padding:10px">Height: ' + height + '<br>Width: ' + width + '</div>');
        jQuery(window)
            .resize(function() {
                height = window.innerHeight;
                width = window.innerWidth;
                jQuery('#viewportsize')
                    .html('Height: ' + height + '<br>Width: ' + width);
            });
    }
}
$(document)
    .ready(function() {
        showViewPortSize(true);
    });

Java, How do I get current index/key in "for each" loop

As others pointed out, 'not possible directly'. I am guessing that you want some kind of index key for Song? Just create another field (a member variable) in Element. Increment it when you add Song to the collection.

Using LINQ to concatenate strings

This answer shows usage of LINQ (Aggregate) as requested in the question and is not intended for everyday use. Because this does not use a StringBuilder it will have horrible performance for very long sequences. For regular code use String.Join as shown in the other answer

Use aggregate queries like this:

string[] words = { "one", "two", "three" };
var res = words.Aggregate(
   "", // start with empty string to handle empty list case.
   (current, next) => current + ", " + next);
Console.WriteLine(res);

This outputs:

, one, two, three

An aggregate is a function that takes a collection of values and returns a scalar value. Examples from T-SQL include min, max, and sum. Both VB and C# have support for aggregates. Both VB and C# support aggregates as extension methods. Using the dot-notation, one simply calls a method on an IEnumerable object.

Remember that aggregate queries are executed immediately.

More information - MSDN: Aggregate Queries


If you really want to use Aggregate use variant using StringBuilder proposed in comment by CodeMonkeyKing which would be about the same code as regular String.Join including good performance for large number of objects:

 var res = words.Aggregate(
     new StringBuilder(), 
     (current, next) => current.Append(current.Length == 0? "" : ", ").Append(next))
     .ToString();

Simple http post example in Objective-C?

 NSMutableDictionary *contentDictionary = [[NSMutableDictionary alloc]init];
[contentDictionary setValue:@"name" forKey:@"email"];
[contentDictionary setValue:@"name" forKey:@"username"];
[contentDictionary setValue:@"name" forKey:@"password"];
[contentDictionary setValue:@"name" forKey:@"firstName"];
[contentDictionary setValue:@"name" forKey:@"lastName"];

NSData *data = [NSJSONSerialization dataWithJSONObject:contentDictionary options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonStr = [[NSString alloc] initWithData:data
                                          encoding:NSUTF8StringEncoding];
NSLog(@"%@",jsonStr);

NSString *urlString = [NSString stringWithFormat:@"http://testgcride.com:8081/v1/users"];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
   [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];


[request setHTTPBody:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]];

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:@"moinsam" password:@"cheese"];
manager.requestSerializer = [AFJSONRequestSerializer serializer];

AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request success:<block> failure:<block>];

Getting JavaScript object key list

For a comma-delineated string listing the keys of a JSON Object, try the following:

function listKeys(jObj){
    var keyString = '';
    for(var k in jObj){
        keyString+=(','+k);
    }
    return keyString.slice(1);
}



/* listKeys({'a' : 'foo', 'b' : 'foo', 'c' : 'foo'}) -> 'a,b,c' */

Leading zeros for Int in Swift

in Xcode 8.3.2, iOS 10.3 Thats is good to now

Sample1:

let dayMoveRaw = 5 
let dayMove = String(format: "%02d", arguments: [dayMoveRaw])
print(dayMove) // 05

Sample2:

let dayMoveRaw = 55 
let dayMove = String(format: "%02d", arguments: [dayMoveRaw])
print(dayMove) // 55

Could not find server 'server name' in sys.servers. SQL Server 2014

I figured out the issue. The linked server was created correctly. However, after the server was upgraded and switched the server name in sys.servers still had the old server name.

I had to drop the old server name and add the new server name to sys.servers on the new server

sp_dropserver 'Server_A'
GO
sp_addserver  'Server',local
GO

Create an Android GPS tracking application

The source code for the Android mobile application open-gpstracker which you appreciated is available here.

You can checkout the code using SVN client application or via Git:

Debugging the source code will surely help you.

How to test the `Mosquitto` server?

In separate terminal windows do the following:

  1. Start the broker:

    mosquitto
    
  2. Start the command line subscriber:

    mosquitto_sub -v -t 'test/topic'
    
  3. Publish test message with the command line publisher:

    mosquitto_pub -t 'test/topic' -m 'helloWorld'
    

As well as seeing both the subscriber and publisher connection messages in the broker terminal the following should be printed in the subscriber terminal:

test/topic helloWorld

css with background image without repeating the image

body {
    background: url(images/image_name.jpg) no-repeat center center fixed; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

Here is a good solution to get your image to cover the full area of the web app perfectly

Clean out Eclipse workspace metadata

There is no easy way to remove the "outdated" stuff from an existing workspace. Using the "clean" parameter will not really help, as many of the files you refer to are "free form data", only known to the plugins that are no longer available.

Your best bet is to optimize the re-import, where I would like to point out the following:

  • When creating a new workspace, you can already choose to have some settings being copied from the current to the new workspace.
  • You can export the preferences of the current workspace (using the Export menu) and re-import them in the new workspace.
  • There are lots of recommendations on the Internet to just copy the ${old_workspace}/.metadata/.plugins/org.eclipse.core.runtime/.settings folder from the old to the new workspace. This is surely the fastest way, but it may lead to weird behaviour, because some of your plugins may depend on these settings and on some of the mentioned "free form data" stored elsewhere. (There are even people symlinking these folders over multiple workspaces, but this really requires to use the same plugins on all workspaces.)
  • You may want to consider using more project specific settings than workspace preferences in the future. So for instance all the Java compiler settings can either be set on the workspace level or on the project level. If set on the project level, you can put them under version control and are independent of the workspace.

z-index not working with position absolute

Old question but this answer might help someone.

If you are trying to display the contents of the container outside of the boundaries of the container, make sure that it doesn't have overflow:hidden, otherwise anything outside of it will be cut off.

What is the difference between .*? and .* regular expressions?

Let's say you have:

<a></a>

<(.*)> would match a></a where as <(.*?)> would match a. The latter stops after the first match of >. It checks for one or 0 matches of .* followed by the next expression.

The first expression <(.*)> doesn't stop when matching the first >. It will continue until the last match of >.

Foreach value from POST from form

Use array-like fields:

<input name="name_for_the_items[]"/>

You can loop through the fields:

foreach($_POST['name_for_the_items'] as $item)
{
  //do something with $item
}

applying css to specific li class

I believe it's because #ID styles trump .class styles when computing the final style of an element. Try changing your li from class to id, or you can try adding !important to your class, like this:

li.sub-navigation-home-news
{
    color: #C1C1C1; !important

What does the "On Error Resume Next" statement do?

It basically tells the program when you encounter an error just continue at the next line.

Cloud Firestore collection count

In 2020 this is still not available in the Firebase SDK however it is available in Firebase Extensions (Beta) however it's pretty complex to setup and use...

A reasonable approach

Helpers... (create/delete seems redundant but is cheaper than onUpdate)

export const onCreateCounter = () => async (
  change,
  context
) => {
  const collectionPath = change.ref.parent.path;
  const statsDoc = db.doc("counters/" + collectionPath);
  const countDoc = {};
  countDoc["count"] = admin.firestore.FieldValue.increment(1);
  await statsDoc.set(countDoc, { merge: true });
};

export const onDeleteCounter = () => async (
  change,
  context
) => {
  const collectionPath = change.ref.parent.path;
  const statsDoc = db.doc("counters/" + collectionPath);
  const countDoc = {};
  countDoc["count"] = admin.firestore.FieldValue.increment(-1);
  await statsDoc.set(countDoc, { merge: true });
};

export interface CounterPath {
  watch: string;
  name: string;
}

Exported Firestore hooks


export const Counters: CounterPath[] = [
  {
    name: "count_buildings",
    watch: "buildings/{id2}"
  },
  {
    name: "count_buildings_subcollections",
    watch: "buildings/{id2}/{id3}/{id4}"
  }
];


Counters.forEach(item => {
  exports[item.name + '_create'] = functions.firestore
    .document(item.watch)
    .onCreate(onCreateCounter());

  exports[item.name + '_delete'] = functions.firestore
    .document(item.watch)
    .onDelete(onDeleteCounter());
});

In action

The building root collection and all sub collections will be tracked.

enter image description here

Here under the /counters/ root path

enter image description here

Now collection counts will update automatically and eventually! If you need a count, just use the collection path and prefix it with counters.

const collectionPath = 'buildings/138faicnjasjoa89/buildingContacts';
const collectionCount = await db
  .doc('counters/' + collectionPath)
  .get()
  .then(snap => snap.get('count'));

Limitations

As this approach uses a single database and document, it is limited to the Firestore constraint of 1 Update per Second for each counter. It will be eventually consistent, but in cases where large amounts of documents are added/removed the counter will lag behind the actual collection count.

running a command as a super user from a python script

I tried all the solutions, but did not work. Wanted to run long running tasks with Celery but for these I needed to run sudo chown command with subprocess.call().

This is what worked for me:

To add safe environment variables, in command line, type:

export MY_SUDO_PASS="user_password_here"

To test if it's working type:

echo $MY_SUDO_PASS
 > user_password_here

To run it at system startup add it to the end of this file:

nano ~/.bashrc  

#.bashrc
...
existing_content:

  elif [ -f /etc/bash_completion ]; then
    . /etc/bash_completion
  fi
fi
...

export MY_SUDO_PASS="user_password_here"

You can add all your environment variables passwords, usernames, host, etc here later.

If your variables are ready you can run:

To update:

echo $MY_SUDO_PASS | sudo -S apt-get update

Or to install Midnight Commander

echo $MY_SUDO_PASS | sudo -S apt-get install mc

To start Midnight Commander with sudo

echo $MY_SUDO_PASS | sudo -S mc

Or from python shell (or Django/Celery), to change directory ownership recursively:

python
>> import subprocess
>> subprocess.call('echo $MY_SUDO_PASS | sudo -S chown -R username_here /home/username_here/folder_to_change_ownership_recursivley', shell=True)

Hope it helps.

How to test my servlet using JUnit

You can do this using Mockito to have the mock return the correct params, verify they were indeed called (optionally specify number of times), write the 'result' and verify it's correct.

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import java.io.*;
import javax.servlet.http.*;
import org.apache.commons.io.FileUtils;
import org.junit.Test;

public class TestMyServlet extends Mockito{

    @Test
    public void testServlet() throws Exception {
        HttpServletRequest request = mock(HttpServletRequest.class);       
        HttpServletResponse response = mock(HttpServletResponse.class);    

        when(request.getParameter("username")).thenReturn("me");
        when(request.getParameter("password")).thenReturn("secret");

        StringWriter stringWriter = new StringWriter();
        PrintWriter writer = new PrintWriter(stringWriter);
        when(response.getWriter()).thenReturn(writer);

        new MyServlet().doPost(request, response);

        verify(request, atLeast(1)).getParameter("username"); // only if you want to verify username was called...
        writer.flush(); // it may not have been flushed yet...
        assertTrue(stringWriter.toString().contains("My expected string"));
    }
}

Google Maps API 3 - Custom marker color for default (dot) marker

Well the closest thing I've been able to get with the StyledMarker is this.

The bullet in the middle isn't quite a big as the default one though. The StyledMarker class simply builds this url and asks the google api to create the marker.

From the class use example use "%E2%80%A2" as your text, as in:

var styleMaker2 = new StyledMarker({styleIcon:new StyledIcon(StyledIconTypes.MARKER,{text:"%E2%80%A2"},styleIconClass),position:new google.maps.LatLng(37.263477473067, -121.880502070713),map:map});

You will need to modifiy StyledMarker.js to comment out the lines:

  if (text_) {
    text_ = text_.substr(0,2);
  }

as this will trim the text string to 2 characters.

Alternatively you could create custom marker images based on the default one with the colors you desire and override the default marker with code such as this:

marker = new google.maps.Marker({
  map:map,
  position: latlng,
  icon: new google.maps.MarkerImage(
    'http://www.gettyicons.com/free-icons/108/gis-gps/png/24/needle_left_yellow_2_24.png',
    new google.maps.Size(24, 24),
    new google.maps.Point(0, 0),
    new google.maps.Point(0, 24)
  )
});

Split string in Lua?

Here is my really simple solution. Use the gmatch function to capture strings which contain at least one character of anything other than the desired separator. The separator is **any* whitespace (%s in Lua) by default:

function mysplit (inputstr, sep)
        if sep == nil then
                sep = "%s"
        end
        local t={}
        for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
                table.insert(t, str)
        end
        return t
end

.

Print Pdf in C#

I wrote and released a small Nuget Package which can be used to print a PDF file to a printerdriver. It can also print to a XPS file or PDF file. Here is a link to it.

How do I get Flask to run on port 80?

If you use the following to change the port or host:

if __name__ == '__main__':
  app.run(host='0.0.0.0', port=80)

use the following code to start the server (my main entrance for flask is app.py):

python app.py

instead of using:

flask run

How to know the git username and email saved during configuration?

To view git configuration type -

git config --list

To change username globally type -

git config --global user.name "your_name"

To change email globally type -

git config --global user.email "your_email"

VBA Excel - Insert row below with same format including borders and frames

Private Sub cmdInsertRow_Click()

    Dim lRow As Long
    Dim lRsp As Long
    On Error Resume Next

    lRow = Selection.Row()
    lRsp = MsgBox("Insert New row above " & lRow & "?", _
            vbQuestion + vbYesNo)
    If lRsp <> vbYes Then Exit Sub

    Rows(lRow).Select
    Selection.Copy
    Rows(lRow + 1).Select
    Selection.Insert Shift:=xlDown
    Application.CutCopyMode = False

   'Paste formulas and conditional formatting in new row created
    Rows(lRow).PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone

End Sub

This is what I use. Tested and working,

Thanks,

What is Bit Masking?

A mask defines which bits you want to keep, and which bits you want to clear.

Masking is the act of applying a mask to a value. This is accomplished by doing:

  • Bitwise ANDing in order to extract a subset of the bits in the value
  • Bitwise ORing in order to set a subset of the bits in the value
  • Bitwise XORing in order to toggle a subset of the bits in the value

Below is an example of extracting a subset of the bits in the value:

Mask:   00001111b
Value:  01010101b

Applying the mask to the value means that we want to clear the first (higher) 4 bits, and keep the last (lower) 4 bits. Thus we have extracted the lower 4 bits. The result is:

Mask:   00001111b
Value:  01010101b
Result: 00000101b

Masking is implemented using AND, so in C we get:

uint8_t stuff(...) {
  uint8_t mask = 0x0f;   // 00001111b
  uint8_t value = 0x55;  // 01010101b
  return mask & value;
}

Here is a fairly common use-case: Extracting individual bytes from a larger word. We define the high-order bits in the word as the first byte. We use two operators for this, &, and >> (shift right). This is how we can extract the four bytes from a 32-bit integer:

void more_stuff(uint32_t value) {             // Example value: 0x01020304
    uint32_t byte1 = (value >> 24);           // 0x01020304 >> 24 is 0x01 so
                                              // no masking is necessary
    uint32_t byte2 = (value >> 16) & 0xff;    // 0x01020304 >> 16 is 0x0102 so
                                              // we must mask to get 0x02
    uint32_t byte3 = (value >> 8)  & 0xff;    // 0x01020304 >> 8 is 0x010203 so
                                              // we must mask to get 0x03
    uint32_t byte4 = value & 0xff;            // here we only mask, no shifting
                                              // is necessary
    ...
}

Notice that you could switch the order of the operators above, you could first do the mask, then the shift. The results are the same, but now you would have to use a different mask:

uint32_t byte3 = (value & 0xff00) >> 8;

Checking if my Windows application is running

The recommended way is to use a Mutex. You can check out a sample here : http://www.codeproject.com/KB/cs/singleinstance.aspx

In specific the code:


        /// 
        /// check if given exe alread running or not
        /// 
        /// returns true if already running
        private static bool IsAlreadyRunning()
        {
            string strLoc = Assembly.GetExecutingAssembly().Location;
            FileSystemInfo fileInfo = new FileInfo(strLoc);
            string sExeName = fileInfo.Name;
            bool bCreatedNew;

            Mutex mutex = new Mutex(true, "Global\\"+sExeName, out bCreatedNew);
            if (bCreatedNew)
                mutex.ReleaseMutex();

            return !bCreatedNew;
        }

Can I change the scroll speed using css or jQuery?

The scroll speed CAN be changed, adjusted, reversed, all of the above - via javascript (or a js library such as jQuery).

WHY would you want to do this? Parallax is just one of the reasons. I have no idea why anyone would argue against doing so -- the same negative arguments can be made against hiding DIVs, sliding elements up/down, etc. Websites are always a combination of technical functionality and UX design -- a good designer can use almost any technical capability to improve UX. That is what makes him/her good.

Toni Almeida of Portugal created a brilliant demo, reproduced below:

jsFiddle Demo

HTML:

<div id="myDiv">
    Use the mouse wheel (not the scroll bar) to scroll this DIV. You will see that the scroll eventually slows down, and then stops. <span class="boldit">Use the mouse wheel (not the scroll bar) to scroll this DIV. You will see that the scroll eventually slows down, and then stops. </span>
</div>

javascript/jQuery:

  function wheel(event) {
      var delta = 0;
      if (event.wheelDelta) {(delta = event.wheelDelta / 120);}
      else if (event.detail) {(delta = -event.detail / 3);}

      handle(delta);
      if (event.preventDefault) {(event.preventDefault());}
      event.returnValue = false;
  }

  function handle(delta) {
      var time = 1000;
      var distance = 300;

      $('html, body').stop().animate({
          scrollTop: $(window).scrollTop() - (distance * delta)
      }, time );
  }

  if (window.addEventListener) {window.addEventListener('DOMMouseScroll', wheel, false);}
    window.onmousewheel = document.onmousewheel = wheel;

Source:

How to change default scrollspeed,scrollamount,scrollinertia of a webpage

jQuery DataTables: control table width

jQuery('#querytableDatasets').dataTable({  
        "bAutoWidth": false
});

Use LIKE %..% with field values in MySQL

Use:

SELECT t1.Notes, 
       t2.Name
  FROM Table1 t1
  JOIN Table2 t2 ON t1.Notes LIKE CONCAT('%', t2.Name ,'%')

printf %f with only 2 numbers after the decimal point?

as described in Formatter class, you need to declare precision. %.2f in your case.

jQuery Selector: Id Ends With?

Try this:

<asp:HiddenField ID="0858674_h" Value="0" runat="server" />

var test = $(this).find('[id*="_h"').val();

phpmyadmin "no data received to import" error, how to fix?

Change your upload settings in php.ini configuration file

Change the below settings to these values:

Change to:

post_max_size = 750M
upload_max_filesize = 750M
max_execution_time = 5000
max_input_time = 5000
memory_limit = 1000M

How do I remove the last comma from a string using PHP?

Use the rtrim function:

rtrim($my_string, ',');

The Second parameter indicates the character to be deleted.

.attr("disabled", "disabled") issue

Try

$(bla).click(function(){        
  if (something) {
     console.log("A:"+$target.prev("input")) // gives out the right object
     $target.toggleClass("open").prev("input").attr("disabled", "disabled");
  }else{
     console.log("A:"+$target.prev("input")) // any thing from there for a single click?
     $target.toggleClass("open").prev("input").removeAttr("disabled"); //this works
  }
});

How to calculate the CPU usage of a process by PID in Linux from C?

You can read the manpage for proc for more detail, but in summary you can read /proc/[number]/stat to get the information about a process. This is also used by the 'ps' command.

All the fields and their scanf format specifiers are documented in the proc manpage.

Here are some of the information from the manpage copied (it is quite long):

          pid %d The process ID.

          comm %s
                 The  filename of the executable, in parentheses.  This is
                 visible whether or not the executable is swapped out.

          state %c
                 One character from the string "RSDZTW" where  R  is  runâ
                 ning,  S is sleeping in an interruptible wait, D is waitâ
                 ing in uninterruptible disk sleep,  Z  is  zombie,  T  is
                 traced or stopped (on a signal), and W is paging.

          ppid %d
                 The PID of the parent.

          pgrp %d
                 The process group ID of the process.

          session %d
                 The session ID of the process.

          tty_nr %d
                 The tty the process uses.

          tpgid %d
                 The  process group ID of the process which currently owns
                 the tty that the process is connected to.

SQL to generate a list of numbers from 1 to 100

Your question is difficult to understand, but if you want to select the numbers from 1 to 100, then this should do the trick:

Select Rownum r
From dual
Connect By Rownum <= 100

Writing binary number system in C code

Use BOOST_BINARY (Yes, you can use it in C).

#include <boost/utility/binary.hpp>
...
int bin = BOOST_BINARY(110101);

This macro is expanded to an octal literal during preprocessing.

How to set radio button selected value using jquery

  <input type="radio" name="RBLExperienceApplicable" class="radio" value="1" checked > 
 //       For Example it is checked
 <input type="radio" name="RBLExperienceApplicable" class="radio" value="0" >


<input type="radio" name="RBLExperienceApplicable2" class="radio" value="1" > 
<input type="radio" name="RBLExperienceApplicable2" class="radio" value="0" >


      $( "input[type='radio']" ).change(function() //on change radio buttons
   {


    alert('Test');
   if($('input[name=RBLExperienceApplicable]:checked').val() != '') //Testing value
 {

$('input[name=RBLExperienceApplicable]:checked').val('Your value Without Quotes');

}
    });

http://jsfiddle.net/6d6FJ/1/ Demo

enter image description here

Using Cookie in Asp.Net Mvc 4

Try using Response.SetCookie(), because Response.Cookies.Add() can cause multiple cookies to be added, whereas SetCookie will update an existing cookie.

How do I find the current executable filename?

If you want the executable:

System.Reflection.Assembly.GetEntryAssembly().Location

If you want the assembly that's consuming your library (which could be the same assembly as above, if your code is called directly from a class within your executable):

System.Reflection.Assembly.GetCallingAssembly().Location

If you'd like just the filename and not the path, use:

Path.GetFileName(System.Reflection.Assembly.GetEntryAssembly().Location)

Remove Project from Android Studio

Or if you don't want to build it just remove it from settings.gradle file

Passing base64 encoded strings in URL

Yes and no.

The basic charset of base64 may in some cases collide with traditional conventions used in URLs. But many of base64 implementations allow you to change the charset to match URLs better or even come with one (like Python's urlsafe_b64encode()).

Another issue you may be facing is the limit of URL length or rather — lack of such limit. Because standards do not specify any maximum length, browsers, servers, libraries and other software working with HTTP protocol may define its' own limits.

regex to match a single character that is anything but a space

The following should suffice:

[^ ]

If you want to expand that to anything but white-space (line breaks, tabs, spaces, hard spaces):

[^\s]

or

\S  # Note this is a CAPITAL 'S'!

Cross Domain Form POSTing

The same origin policy is applicable only for browser side programming languages. So if you try to post to a different server than the origin server using JavaScript, then the same origin policy comes into play but if you post directly from the form i.e. the action points to a different server like:

<form action="http://someotherserver.com">

and there is no javascript involved in posting the form, then the same origin policy is not applicable.

See wikipedia for more information

Truncating long strings with CSS: feasible yet?

If you're OK with a JavaScript solution, there's a jQuery plug-in to do this in a cross-browser fashion - see http://azgtech.wordpress.com/2009/07/26/text-overflow-ellipsis-for-firefox-via-jquery/

What is the difference between String.slice and String.substring?

The difference between substring and slice - is how they work with negative and overlooking lines abroad arguments:

substring (start, end)

Negative arguments are interpreted as zero. Too large values ??are truncated to the length of the string:   alert ( "testme" .substring (-2)); // "testme", -2 becomes 0

Furthermore, if start > end, the arguments are interchanged, i.e. plot line returns between the start and end:

alert ( "testme" .substring (4, -1)); // "test"
// -1 Becomes 0 -> got substring (4, 0)
// 4> 0, so that the arguments are swapped -> substring (0, 4) = "test"

slice

Negative values ??are measured from the end of the line:

alert ( "testme" .slice (-2)); // "me", from the end position 2
alert ( "testme" .slice (1, -1)); // "estm", from the first position to the one at the end.

It is much more convenient than the strange logic substring.

A negative value of the first parameter to substr supported in all browsers except IE8-.

If the choice of one of these three methods, for use in most situations - it will be slice: negative arguments and it maintains and operates most obvious.

Adding new column to existing DataFrame in Python pandas

If the column you are trying to add is a series variable then just :

df["new_columns_name"]=series_variable_name #this will do it for you

This works well even if you are replacing an existing column.just type the new_columns_name same as the column you want to replace.It will just overwrite the existing column data with the new series data.

How to call a parent method from child class in javascript?

Well in order to do this, you are not limited with the Class abstraction of ES6. Accessing the parent constructor's prototype methods is possible through the __proto__ property (I am pretty sure there will be fellow JS coders to complain that it's depreciated) which is depreciated but at the same time discovered that it is actually an essential tool for sub-classing needs (especially for the Array sub-classing needs though). So while the __proto__ property is still available in all major JS engines that i know, ES6 introduced the Object.getPrototypeOf() functionality on top of it. The super() tool in the Class abstraction is a syntactical sugar of this.

So in case you don't have access to the parent constructor's name and don't want to use the Class abstraction you may still do as follows;

function ChildObject(name) {
    // call the parent's constructor
    ParentObject.call(this, name);
    this.myMethod = function(arg) {
    //this.__proto__.__proto__.myMethod.call(this,arg);
    Object.getPrototypeOf(Object.getPrototypeOf(this)).myMethod.call(this,arg);
    }
}

How to set environment variable or system property in spring tests?

You can set the System properties as VM arguments.

If your project is a maven project then you can execute following command while running the test class:

mvn test -Dapp.url="https://stackoverflow.com"

Test class:

public class AppTest  {
@Test
public void testUrl() {
    System.out.println(System.getProperty("app.url"));
    }
}

If you want to run individual test class or method in eclipse then :

1) Go to Run -> Run Configuration

2) On left side select your Test class under the Junit section.

3) do the following :

enter image description here