Programs & Examples On #Attach to process

git with IntelliJ IDEA: Could not read from remote repository

Settings --> Version Control --> Git, and then, in the SSH executable dropdown, choose Native

Version Control: Git: SSH executable: For current project

If this doesn't help, ensure that your native ssh and git clients are of a sufficiently recent version.

How can I format a String number to have commas and round?

Once you've converted your String to a number, you can use

// format the number for the default locale
NumberFormat.getInstance().format(num)

or

// format the number for a particular locale
NumberFormat.getInstance(locale).format(num)

'ssh' is not recognized as an internal or external command

Actually you have 2 problems here: First is that you don't have ssh installed, second is that you don't know how to deploy

Install SSH

It seems that ssh is not installed on your computer.

You can install openssh from here : http://openssh.en.softonic.com/download

Generate your key

Than you will have to geneate your ssh-key. There's a good tutorial about this here:

https://help.github.com/articles/generating-ssh-keys#platform-windows

Deploy

To deploy, you just have to push your code over git. Something like this:

git push fort master

If you get permission denied, be sure that you have put your public_key in the dashboard in the git tab.

SSH

The ssh command gives you access to your remote node. You should have received a password by email and now that you have ssh installed, you should be asked for a password when trying to connect. just input that password. If you want to use your private ssh key to connect to your server rather then typing that password, you can follow this : http://fortrabbit.com/docs/how-to/ssh-sftp/enable-public-key-authentication

How to validate GUID is a GUID

Based on the accepted answer I created an Extension method as follows:

public static Guid ToGuid(this string aString)
{
    Guid newGuid;

    if (string.IsNullOrWhiteSpace(aString))
    {
        return MagicNumbers.defaultGuid;
    }

    if (Guid.TryParse(aString, out newGuid))
    {
        return newGuid;
    }

    return MagicNumbers.defaultGuid;
}

Where "MagicNumbers.defaultGuid" is just "an empty" all zero Guid "00000000-0000-0000-0000-000000000000".

In my case returning that value as the result of an invalid ToGuid conversion was not a problem.

After installing SQL Server 2014 Express can't find local db

Also, if you just installed localDB, you won't see the instance in the configuration manager. You would need to initiate it first, and then connect to it using server name (localdb)\mssqllocaldb. Source

What does 'const static' mean in C and C++?

A lot of people gave the basic answer but nobody pointed out that in C++ const defaults to static at namespace level (and some gave wrong information). See the C++98 standard section 3.5.3.

First some background:

Translation unit: A source file after the pre-processor (recursively) included all its include files.

Static linkage: A symbol is only available within its translation unit.

External linkage: A symbol is available from other translation units.

At namespace level

This includes the global namespace aka global variables.

static const int sci = 0; // sci is explicitly static
const int ci = 1;         // ci is implicitly static
extern const int eci = 2; // eci is explicitly extern
extern int ei = 3;        // ei is explicitly extern
int i = 4;                // i is implicitly extern
static int si = 5;        // si is explicitly static

At function level

static means the value is maintained between function calls.
The semantics of function static variables is similar to global variables in that they reside in the program's data-segment (and not the stack or the heap), see this question for more details about static variables' lifetime.

At class level

static means the value is shared between all instances of the class and const means it doesn't change.

Unique Key constraints for multiple columns in Entity Framework

I found three ways to solve the problem.

Unique indexes in EntityFramework Core:

First approach:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
   modelBuilder.Entity<Entity>()
   .HasIndex(p => new {p.FirstColumn , p.SecondColumn}).IsUnique();
}

The second approach to create Unique Constraints with EF Core by using Alternate Keys.

Examples

One column:

modelBuilder.Entity<Blog>().HasAlternateKey(c => c.SecondColumn).HasName("IX_SingeColumn");

Multiple columns:

modelBuilder.Entity<Entity>().HasAlternateKey(c => new [] {c.FirstColumn, c.SecondColumn}).HasName("IX_MultipleColumns");

EF 6 and below:


First approach:

dbContext.Database.ExecuteSqlCommand(string.Format(
                        @"CREATE UNIQUE INDEX LX_{0} ON {0} ({1})", 
                                 "Entitys", "FirstColumn, SecondColumn"));

This approach is very fast and useful but the main problem is that Entity Framework doesn't know anything about those changes!


Second approach:
I found it in this post but I did not tried by myself.

CreateIndex("Entitys", new string[2] { "FirstColumn", "SecondColumn" },
              true, "IX_Entitys");

The problem of this approach is the following: It needs DbMigration so what do you do if you don't have it?


Third approach:
I think this is the best one but it requires some time to do it. I will just show you the idea behind it: In this link http://code.msdn.microsoft.com/CSASPNETUniqueConstraintInE-d357224a you can find the code for unique key data annotation:

[UniqueKey] // Unique Key 
public int FirstColumn  { get; set;}
[UniqueKey] // Unique Key 
public int SecondColumn  { get; set;}

// The problem hier
1, 1  = OK 
1 ,2  = NO OK 1 IS UNIQUE

The problem for this approach; How can I combine them? I have an idea to extend this Microsoft implementation for example:

[UniqueKey, 1] // Unique Key 
public int FirstColumn  { get; set;}
[UniqueKey ,1] // Unique Key 
public int SecondColumn  { get; set;}

Later in the IDatabaseInitializer as described in the Microsoft example you can combine the keys according to the given integer. One thing has to be noted though: If the unique property is of type string then you have to set the MaxLength.

How do you install GLUT and OpenGL in Visual Studio 2012?

This is GLUT installation instruction. Not free glut

First download this 118 KB GLUT package from Here

Extract the downloaded ZIP file and make sure you find the following

glut.h

glut32.lib

glut32.dll

If you have a 32 bits operating system, place glut32.dll to C:\Windows\System32\, if your operating system is 64 bits, place it to 'C:\Windows\SysWOW64\' (to your system directory)

Place glut.h C:\Program Files\Microsoft Visual Studio 12\VC\include\GL\ (NOTE: 12 here refers to your VS version it may be 8 or 10)

If you do not find VC and following directories.. go on create it.

Place glut32.lib to C:\Program Files\Microsoft Visual Studio 12\VC\lib\

Now, open visual Studio and

  1. Under Visual C++, select Empty Project(or your already existing project)
  2. Go to Project -> Properties. Select 'All Configuration' from Configuration dropdown menu on top left corner
  3. Select Linker -> Input
  4. Now right click on "Additional Dependence" found on Right panel and click Edit

now type

opengl32.lib

glu32.lib

glut32.lib

(NOTE: Each .lib in new line)

That's it... You have successfully installed OpenGL.. Go on and run your program.

Same installation instructions aplies to freeglut files with the header files in the GL folder, lib in the lib folder, and dll in the System32 folder.

jQuery - how to write 'if not equal to' (opposite of ==)

if ("one" !== 1 )

would evaluate as true, the string "one" is not equal to the number 1

How to return value from Action()?

You can use Func<T, TResult> generic delegate. (See MSDN)

Func<MyType, ReturnType> func = (db) => { return new MyType(); }

Also there are useful generic delegates which considers a return value:

  • Converter<TInput, TOutput> (MSDN)
  • Predicate<TInput> - always return bool (MSDN)

Method:

public MyType SimpleUsing.DoUsing<MyType>(Func<TInput, MyType> myTypeFactory)

Generic delegate:

Func<InputArgumentType, MyType> createInstance = db => return new MyType();

Execute:

MyType myTypeInstance = SimpleUsing.DoUsing(
                            createInstance(new InputArgumentType()));

OR explicitly:

MyType myTypeInstance = SimpleUsing.DoUsing(db => return new MyType());

Get a list of all functions and procedures in an Oracle database

SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE IN ('FUNCTION','PROCEDURE','PACKAGE')

The column STATUS tells you whether the object is VALID or INVALID. If it is invalid, you have to try a recompile, ORACLE can't tell you if it will work before.

Large Numbers in Java

Depending on what you're doing you might like to take a look at GMP (gmplib.org) which is a high-performance multi-precision library. To use it in Java you need JNI wrappers around the binary library.

See some of the Alioth Shootout code for an example of using it instead of BigInteger to calculate Pi to an arbitrary number of digits.

https://benchmarksgame-team.pages.debian.net/benchmarksgame/program/pidigits-java-2.html

LINQ equivalent of foreach for IEnumerable<T>

Yet another ForEach Example

public static IList<AddressEntry> MapToDomain(IList<AddressModel> addresses)
{
    var workingAddresses = new List<AddressEntry>();

    addresses.Select(a => a).ToList().ForEach(a => workingAddresses.Add(AddressModelMapper.MapToDomain(a)));

    return workingAddresses;
}

Is it better to use NOT or <> when comparing values?

Because "not ... =" is two operations and "<>" is only one, it is faster to use "<>".

Here is a quick experiment to prove it:

StartTime = Timer
For x = 1 to 100000000
   If 4 <> 3 Then
   End if
Next
WScript.echo Timer-StartTime

StartTime = Timer
For x = 1 to 100000000
   If Not (4 = 3) Then
   End if
Next
WScript.echo Timer-StartTime

The results I get on my machine:

4.783203
5.552734

X-UA-Compatible is set to IE=edge, but it still doesn't stop Compatibility Mode

Note that if you are serving it from PHP, you can use the following code to fix it as well.

header("X-UA-Compatible: IE=Edge");

Encode/Decode URLs in C++

Adding a follow-up to Bill's recommendation for using libcurl: great suggestion, and to be updated:
after 3 years, the curl_escape function is deprecated, so for future use it's better to use curl_easy_escape.

When do you use POST and when do you use GET?

POST can move large data while GET cannot.

But generally it's not about a shortcomming of GET, rather a convention if you want your website/webapp to be behaving nicely.

Have a look at http://www.w3.org/2001/tag/doc/whenToUseGet.html

How to convert a DataTable to a string in C#?

Or, change the app to WinForms, use grid and bind DataTable to grid. If it is a demo/sample app.

Is there any way to do HTTP PUT in python

If you want to stay within the standard library, you can subclass urllib2.Request:

import urllib2

class RequestWithMethod(urllib2.Request):
    def __init__(self, *args, **kwargs):
        self._method = kwargs.pop('method', None)
        urllib2.Request.__init__(self, *args, **kwargs)

    def get_method(self):
        return self._method if self._method else super(RequestWithMethod, self).get_method()


def put_request(url, data):
    opener = urllib2.build_opener(urllib2.HTTPHandler)
    request = RequestWithMethod(url, method='PUT', data=data)
    return opener.open(request)

How to use Monitor (DDMS) tool to debug application

Could it be a problem with past preview versions of Android Studio ? nowadays "beta" has replaced the "preview". I try it out step by step debugging while using Memory Monitor at same time by Android Studio (Beta) 0.8.11 on OSX 10.9.5 without any problems.

The tutorial Debugging with Android Studio also helps, specially this paragraph :

To track memory allocation of objects:

  1. Start your app as described in Run Your App in Debug Mode.
  2. Click Android to open the Android DDMS tool window.
  3. On the Android DDMS tool window, select the Devices | logcat tab.
  4. Select your device from the dropdown list.
  5. Select your app by its package name from the list of running apps.
  6. Click Start Allocation Tracking Interact with your app on the device. Click Stop Allocation Tracking

Here a couple of screenshot while debugging step by step on a breakpoint a monitoring the memory on the emulator:
breakpointmemory monitor

Closing WebSocket correctly (HTML5, Javascript)

Very simple, you close it :)

var myWebSocket = new WebSocket("ws://example.org"); 
myWebSocket.send("Hello Web Sockets!"); 
myWebSocket.close();

Did you check also the following site And check the introduction article of Opera

Overriding interface property type defined in Typescript d.ts file

type ModifiedType = Modify<OriginalType, {
  a: number;
  b: number;
}>

interface ModifiedInterface extends Modify<OriginalType, {
  a: number;
  b: number;
}> {}

Inspired by ZSkycat's extends Omit solution, I came up with this:

type Modify<T, R> = Omit<T, keyof R> & R;

// before [email protected]
type Modify<T, R> = Pick<T, Exclude<keyof T, keyof R>> & R

Example:

interface OriginalInterface {
  a: string;
  b: boolean;
  c: number;
}

type ModifiedType  = Modify<OriginalInterface , {
  a: number;
  b: number;
}>

// ModifiedType = { a: number; b: number; c: number; }

Going step by step:

type R0 = Omit<OriginalType, 'a' | 'b'>        // { c: number; }
type R1 = R0 & {a: number, b: number }         // { a: number; b: number; c: number; }

type T0 = Exclude<'a' | 'b' | 'c' , 'a' | 'b'> // 'c'
type T1 = Pick<OriginalType, T0>               // { c: number; }
type T2 = T1 & {a: number, b: number }         // { a: number; b: number; c: number; }

TypeScript Utility Types

What does the colon (:) operator do?

It's used in for loops to iterate over a list of objects.

for (Object o: list)
{
    // o is an element of list here
}

Think of it as a for <item> in <list> in Python.

How to declare a variable in a template in Angular

I liked the approach of creating a directive to do this (good call @yurzui).

I ended up finding a Medium article Angular "let" Directive which explains this problem nicely and proposes a custom let directive which ended up working great for my use case with minimal code changes.

Here's the gist (at the time of posting) with my modifications:

import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core'

interface LetContext <T> {
  appLet: T | null
}

@Directive({
  selector: '[appLet]',
})
export class LetDirective <T> {
  private _context: LetContext <T> = { appLet: null }

  constructor(_viewContainer: ViewContainerRef, _templateRef: TemplateRef <LetContext <T> >) {
    _viewContainer.createEmbeddedView(_templateRef, this._context)
  }

  @Input()
  set appLet(value: T) {
    this._context.appLet = value
  }
}

My main changes were:

  • changing the prefix from 'ng' to 'app' (you should use whatever your app's custom prefix is)
  • changing appLet: T to appLet: T | null

Not sure why the Angular team hasn't just made an official ngLet directive but whatevs.

Original source code credit goes to @AustinMatherne

How to set the part of the text view is clickable

The solutions provided are pretty decent. However, I generally use a more simple solution.

Here is a linkify utility function

/**
 * Method is used to Linkify words in a TextView
 *
 * @param textView TextView who's text you want to change
 * @param textToLink The text to turn into a link
 * @param url   The url you want to send the user to
 */
fun linkify(textView: TextView, textToLink: String, url: String) {
    val pattern = Pattern.compile(textToLink)
    Linkify.addLinks(textView, pattern, url, { _, _, _ -> true })
    { _, _ -> "" }
}

Using this function is pretty simple. Here is an example

    // terms and privacy
    val tvTerms = findViewById<TextView>(R.id.tv_terms)
    val tvPrivacy = findViewById<TextView>(R.id.tv_privacy)
    Utils.linkify(tvTerms, resources.getString(R.string.terms),
            Constants.TERMS_URL)
    Utils.linkify(tvPrivacy, resources.getString(R.string.privacy),
            Constants.PRIVACY_URL)

Convert UTF-8 to base64 string

It's a little difficult to tell what you're trying to achieve, but assuming you're trying to get a Base64 string that when decoded is abcdef==, the following should work:

byte[] bytes = Encoding.UTF8.GetBytes("abcdef==");
string base64 = Convert.ToBase64String(bytes);
Console.WriteLine(base64);

This will output: YWJjZGVmPT0= which is abcdef== encoded in Base64.

Edit:

To decode a Base64 string, simply use Convert.FromBase64String(). E.g.

string base64 = "YWJjZGVmPT0=";
byte[] bytes = Convert.FromBase64String(base64);

At this point, bytes will be a byte[] (not a string). If we know that the byte array represents a string in UTF8, then it can be converted back to the string form using:

string str = Encoding.UTF8.GetString(bytes);
Console.WriteLine(str);

This will output the original input string, abcdef== in this case.

Finding first and last index of some value in a list in Python

Sequences have a method index(value) which returns index of first occurrence - in your case this would be verts.index(value).

You can run it on verts[::-1] to find out the last index. Here, this would be len(verts) - 1 - verts[::-1].index(value)

Get host domain from URL?

Try this

Console.WriteLine(GetDomain.GetDomainFromUrl("http://support.domain.com/default.aspx?id=12345"));

It will output support.domain.com

Or try

Uri.GetLeftPart( UriPartial.Authority )

SQL Server Group by Count of DateTime Per Hour?

How about this? Assuming SQL Server 2008:

SELECT CAST(StartDate as date) AS ForDate,
       DATEPART(hour,StartDate) AS OnHour,
       COUNT(*) AS Totals
FROM #Events
GROUP BY CAST(StartDate as date),
       DATEPART(hour,StartDate)

For pre-2008:

SELECT DATEADD(day,datediff(day,0,StartDate),0)   AS ForDate,
       DATEPART(hour,StartDate) AS OnHour,
       COUNT(*) AS Totals
FROM #Events
GROUP BY CAST(StartDate as date),
       DATEPART(hour,StartDate)

This results in :

ForDate                 | OnHour | Totals
-----------------------------------------
2011-08-09 00:00:00.000     12       3

Pandas DataFrame to List of Dictionaries

Edit

As John Galt mentions in his answer , you should probably instead use df.to_dict('records'). It's faster than transposing manually.

In [20]: timeit df.T.to_dict().values()
1000 loops, best of 3: 395 µs per loop

In [21]: timeit df.to_dict('records')
10000 loops, best of 3: 53 µs per loop

Original answer

Use df.T.to_dict().values(), like below:

In [1]: df
Out[1]:
   customer  item1   item2   item3
0         1  apple    milk  tomato
1         2  water  orange  potato
2         3  juice   mango   chips

In [2]: df.T.to_dict().values()
Out[2]:
[{'customer': 1.0, 'item1': 'apple', 'item2': 'milk', 'item3': 'tomato'},
 {'customer': 2.0, 'item1': 'water', 'item2': 'orange', 'item3': 'potato'},
 {'customer': 3.0, 'item1': 'juice', 'item2': 'mango', 'item3': 'chips'}]

A SQL Query to select a string between two known strings

The problem is that the second part of your substring argument is including the first index. You need to subtract the first index from your second index to make this work.

SELECT SUBSTRING(@Text, CHARINDEX('the dog', @Text)
, CHARINDEX('immediately',@text) - CHARINDEX('the dog', @Text) + Len('immediately'))

How to get elements with multiple classes

AND (both classes)

var list = document.getElementsByClassName("class1 class2");
var list = document.querySelectorAll(".class1.class2");

OR (at least one class)

var list = document.querySelectorAll(".class1,.class2");

XOR (one class but not the other)

var list = document.querySelectorAll(".class1:not(.class2),.class2:not(.class1)");

NAND (not both classes)

var list = document.querySelectorAll(":not(.class1),:not(.class2)");

NOR (not any of the two classes)

var list = document.querySelectorAll(":not(.class1):not(.class2)");

How get the base URL via context path in JSF?

JSTL 1.2 variation leveraged from BalusC answer

<c:set var="baseURL" value="${pageContext.request.requestURL.substring(0, pageContext.request.requestURL.length() - pageContext.request.requestURI.length())}${pageContext.request.contextPath}/" />

<head>
  <base href="${baseURL}" />

Variably modified array at file scope

It is also possible to use enumeration.

typedef enum {
    typeNo1 = 1,
    typeNo2,
    typeNo3,
    typeNo4,
    NumOfTypes = typeNo4
}  TypeOfSomething;

C# testing to see if a string is an integer?

It is possible to try this as well:

    var ix=Convert.ToInt32(x);
    if (x==ix) //if this condition is met, then x is integer
    {
        //your code here
    }

Connecting client to server using Socket.io

You need to make sure that you add forward slash before your link to socket.io:

<script src="/socket.io/socket.io.js"></script>

Then in the view/controller just do:

var socket = io.connect()

That should solve your problem.

VBA - Range.Row.Count

That is nice question :)

When you have situation with 1 cell (A1), it is important to identify if second declared cell is not empty (sh.Range("A1").End(xlDown)). If it is true it means your range got out of control :) Look at code below:

Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("Arkusz1")

Dim k As Long

If IsEmpty(sh.Range("A1").End(xlDown)) = True Then
    k = 1

Else
    k = sh.Range("A1", sh.Range("A1").End(xlDown)).Rows.Count

End If

Find location of a removable SD card

Its work for all external devices, But make sure only get external device folder name and then you need to get file from given location using File class.

public static List<String> getExternalMounts() {
        final List<String> out = new ArrayList<>();
        String reg = "(?i).*vold.*(vfat|ntfs|exfat|fat32|ext3|ext4).*rw.*";
        String s = "";
        try {
            final Process process = new ProcessBuilder().command("mount")
                    .redirectErrorStream(true).start();
            process.waitFor();
            final InputStream is = process.getInputStream();
            final byte[] buffer = new byte[1024];
            while (is.read(buffer) != -1) {
                s = s + new String(buffer);
            }
            is.close();
        } catch (final Exception e) {
            e.printStackTrace();
        }

        // parse output
        final String[] lines = s.split("\n");
        for (String line : lines) {
            if (!line.toLowerCase(Locale.US).contains("asec")) {
                if (line.matches(reg)) {
                    String[] parts = line.split(" ");
                    for (String part : parts) {
                        if (part.startsWith("/"))
                            if (!part.toLowerCase(Locale.US).contains("vold"))
                                out.add(part);
                    }
                }
            }
        }
        return out;
    }

Calling:

List<String> list=getExternalMounts();
        if(list.size()>0)
        {
            String[] arr=list.get(0).split("/");
            int size=0;
            if(arr!=null && arr.length>0) {
                size= arr.length - 1;
            }
            File parentDir=new File("/storage/"+arr[size]);
            if(parentDir.listFiles()!=null){
                File parent[] = parentDir.listFiles();

                for (int i = 0; i < parent.length; i++) {

                    // get file path as parent[i].getAbsolutePath());

                }
            }
        }

Getting access to external storage

In order to read or write files on the external storage, your app must acquire the READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE system permissions. For example:

<manifest ...>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    ...
</manifest>

Delete a database in phpMyAdmin

Go to operations tab for the selected database and click "Drop the database (DROP)" to delete it.

React.js: How to append a component on click?

Don't use jQuery to manipulate the DOM when you're using React. React components should render a representation of what they should look like given a certain state; what DOM that translates to is taken care of by React itself.

What you want to do is store the "state which determines what gets rendered" higher up the chain, and pass it down. If you are rendering n children, that state should be "owned" by whatever contains your component. eg:

class AppComponent extends React.Component {
  state = {
    numChildren: 0
  }

  render () {
    const children = [];

    for (var i = 0; i < this.state.numChildren; i += 1) {
      children.push(<ChildComponent key={i} number={i} />);
    };

    return (
      <ParentComponent addChild={this.onAddChild}>
        {children}
      </ParentComponent>
    );
  }

  onAddChild = () => {
    this.setState({
      numChildren: this.state.numChildren + 1
    });
  }
}

const ParentComponent = props => (
  <div className="card calculator">
    <p><a href="#" onClick={props.addChild}>Add Another Child Component</a></p>
    <div id="children-pane">
      {props.children}
    </div>
  </div>
);

const ChildComponent = props => <div>{"I am child " + props.number}</div>;

Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running?

I guess if you are using WSL with GUI, then you could just try

sudo /etc/init.d/docker start

Nested objects in javascript, best practices

var defaultsettings = {
    ajaxsettings: {
        ...
    },
    uisettings: {
        ...
    }
};

How to change value of a request parameter in laravel

If you need to customize the request

$data = $request->all();

you can pass the name of the field and the value

$data['product_ref_code'] = 1650;

and finally pass the new request

$last = Product::create($data);

How to resize array in C++?

Raw arrays aren't resizable in C++.

You should be using something like a Vector class which does allow resizing..

std::vector allows you to resize it as well as allowing dynamic resizing when you add elements (often making the manual resizing unnecessary for adding).

yum error "Cannot retrieve metalink for repository: epel. Please verify its path and try again" updating ContextBroker

Walkthrough Steps

Running the following command will update the repo to use HTTP rather than HTTPS:

sudo sed -i "s/mirrorlist=https/mirrorlist=http/" /etc/yum.repos.d/epel.repo

You should then be able to update with this command:

yum -y update

Operand type clash: int is incompatible with date + The INSERT statement conflicted with the FOREIGN KEY constraint

FYI this turned out to be an issue for me where I had two tables in a statement like the following:

SELECT * FROM table1
UNION ALL
SELECT * FROM table2

It worked, but then somewhere along the line the order of columns in one of the table definitions got changed. Changing the * to SELECT column1, column2 fixed the issue. No idea how that happened, but lesson learned!

Visual studio code terminal, how to run a command with administrator rights?

Running as admin didn't help me. (also got errors with syscall: rename)

Turns out this error can also occur if files are locked by Windows.

This can occur if :

  • You are actually running the project
  • You have files open in both Visual Studio and VSCode.

Running as admin doesn't get around windows file locking.

I created a new project in VS2017 and then switched to VSCode to try to add more packages. After stopping the project from running and closing VS2017 it was able to complete without error

Disclaimer: I'm not exactly sure if this means running as admin isn't necessary, but try to avoid it if possible to avoid the possibility of some rogue package doing stuff it isn't meant to.

Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\

mysqli_select_db() should have 2 parameters, the connection link and the database name -

mysqli_select_db($con, 'phpcadet') or die(mysqli_error($con));

Using mysqli_error in the die statement will tell you exactly what is wrong as opposed to a generic error message.

Export from pandas to_excel without row names (index)?

Example: index = False

import pandas as pd

writer = pd.ExcelWriter("dataframe.xlsx", engine='xlsxwriter')
dataframe.to_excel(writer,sheet_name = dataframe, index=False)
writer.save() 

int array to string

string result = arr.Aggregate("", (s, i) => s + i.ToString());

(Disclaimer: If you have a lot of digits (hundreds, at least) and you care about performance, I suggest eschewing this method and using a StringBuilder, as in JaredPar's answer.)

Storing a Key Value Array into a compact JSON string

To me, this is the most "natural" way to structure such data in JSON, provided that all of the keys are strings.

{
    "keyvaluelist": {
        "slide0001.html": "Looking Ahead",
        "slide0008.html": "Forecast",
        "slide0021.html": "Summary"
    },
    "otherdata": {
        "one": "1",
        "two": "2",
        "three": "3"
    },
    "anotherthing": "thing1",
    "onelastthing": "thing2"
}

I read this as

a JSON object with four elements
    element 1 is a map of key/value pairs named "keyvaluelist",
    element 2 is a map of key/value pairs named "otherdata",
    element 3 is a string named "anotherthing",
    element 4 is a string named "onelastthing"

The first element or second element could alternatively be described as objects themselves, of course, with three elements each.

How to find integer array size in java

There is no method call size() with array. you can use array.length

How to make a script wait for a pressed key?

The python manual provides the following:

import termios, fcntl, sys, os
fd = sys.stdin.fileno()

oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newattr)

oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)

try:
    while 1:
        try:
            c = sys.stdin.read(1)
            print "Got character", repr(c)
        except IOError: pass
finally:
    termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
    fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)

which can be rolled into your use case.

PHP - cannot use a scalar as an array warning

A bit late, but to anyone who is wondering why they are getting the "Warning: Cannot use a scalar value as an array" message;

the reason is because somewhere you have first declared your variable with a normal integer or string and then later you are trying to turn it into an array.

hope that helps

Adding multiple class using ng-class

Using a $scope method on the controller, you can calculate what classes to output in the view. This is especially handy if you have a complex logic for calculating class names and it will reduce the amount of logic in your view by moving it to the controller:

app.controller('myController', function($scope) {

    $scope.className = function() {

        var className = 'initClass';

        if (condition1())
            className += ' class1';

        if (condition2())
            className += ' class2';

        return className;
    };
});

and in the view, simply:

<div ng-class="className()"></div>

Static Classes In Java

Can a class be static in Java ?

The answer is YES, we can have static class in java. In java, we have static instance variables as well as static methods and also static block. Classes can also be made static in Java.

In java, we can’t make Top-level (outer) class static. Only nested classes can be static.

static nested class vs non-static nested class

1) Nested static class doesn’t need a reference of Outer class, but Non-static nested class or Inner class requires Outer class reference.

2) Inner class(or non-static nested class) can access both static and non-static members of Outer class. A static class cannot access non-static members of the Outer class. It can access only static members of Outer class.

see here: https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

Clone() vs Copy constructor- which is recommended in java

clone() was designed with several mistakes (see this question), so it's best to avoid it.

From Effective Java 2nd Edition, Item 11: Override clone judiciously

Given all of the problems associated with Cloneable, it’s safe to say that other interfaces should not extend it, and that classes designed for inheritance (Item 17) should not implement it. Because of its many shortcomings, some expert programmers simply choose never to override the clone method and never to invoke it except, perhaps, to copy arrays. If you design a class for inheritance, be aware that if you choose not to provide a well-behaved protected clone method, it will be impossible for subclasses to implement Cloneable.

This book also describes the many advantages copy constructors have over Cloneable/clone.

  • They don't rely on a risk-prone extralinguistic object creation mechanism
  • They don't demand unenforceable adherence to thinly documented conventions
  • They don't conflict with the proper use of final fields
  • They don't throw unnecessary checked exceptions
  • They don't require casts.

All standard collections have copy constructors. Use them.

List<Double> original = // some list
List<Double> copy = new ArrayList<Double>(original);

Splitting string with pipe character ("|")

Or.. Pattern#quote:

String[] value_split = rat_values.split(Pattern.quote("|"));

This is happening because String#split accepts a regex:

| has a special meaning in regex.

quote will return a String representation for the regex.

How to define and use function inside Jenkins Pipeline config?

First off, you shouldn't add $ when you're outside of strings ($class in your first function being an exception), so it should be:

def doCopyMibArtefactsHere(projectName) {
    step ([
        $class: 'CopyArtifact',
        projectName: projectName,
        filter: '**/**.mib',
        fingerprintArtifacts: true, 
        flatten: true
    ]);
}

def BuildAndCopyMibsHere(projectName, params) {
    build job: project, parameters: params
    doCopyMibArtefactsHere(projectName)
}
...

Now, as for your problem; the second function takes two arguments while you're only supplying one argument at the call. Either you have to supply two arguments at the call:

...
node { 
    stage('Prepare Mib'){
        BuildAndCopyMibsHere('project1', null)
    }
}

... or you need to add a default value to the functions' second argument:

def BuildAndCopyMibsHere(projectName, params = null) {
    build job: project, parameters: params
    doCopyMibArtefactsHere($projectName)
}

Cannot drop database because it is currently in use

First make your data base offline after that detach it e.g.

Use Master
GO
ALTER DATABASE dbname SET OFFLINE
GO
EXEC sp_detach_db 'dbname', 'true'

What does CultureInfo.InvariantCulture mean?

For things like numbers (decimal points, commas in amounts), they are usually preferred in the specific culture.

A appropriate way to do this would be set it at the culture level (for German) like this:

Thread.CurrentThread.CurrentCulture.NumberFormat = new CultureInfo("de").NumberFormat;

Setting the zoom level for a MKMapView

Based on the fact that longitude lines are spaced apart equally at any point of the map, there is a very simple implementation to set the centerCoordinate and zoomLevel:

@interface MKMapView (ZoomLevel)

@property (assign, nonatomic) NSUInteger zoomLevel;

- (void)setCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate
                  zoomLevel:(NSUInteger)zoomLevel
                   animated:(BOOL)animated;

@end


@implementation MKMapView (ZoomLevel)

- (void)setZoomLevel:(NSUInteger)zoomLevel {
    [self setCenterCoordinate:self.centerCoordinate zoomLevel:zoomLevel animated:NO];
}

- (NSUInteger)zoomLevel {
    return log2(360 * ((self.frame.size.width/256) / self.region.span.longitudeDelta)) + 1;
}

- (void)setCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate
zoomLevel:(NSUInteger)zoomLevel animated:(BOOL)animated {
    MKCoordinateSpan span = MKCoordinateSpanMake(0, 360/pow(2, zoomLevel)*self.frame.size.width/256);
    [self setRegion:MKCoordinateRegionMake(centerCoordinate, span) animated:animated];
}

@end

Comparison of C++ unit test frameworks

Wikipedia has a comprehensive list of unit testing frameworks, with tables that identify features supported or not.

Switch focus between editor and integrated terminal in Visual Studio Code

Here is my approach, which provides a consistent way of navigating between active terminals as well as jumping between the terminal and editor panes without closing the terminal view. You can try adding this to your keybindings.json directly but I would recommend you go through the keybinding UI (cmd+K cmd+S on a Mac) so you can review/manage conflicts etc.

With this I can use ctrl+x <arrow direction> to navigate to any visible editor or terminal. Once the cursor is in the terminal section you can use ctrl+x ctrl+up or ctrl+x ctrl+down to cycle through the active terminals.

cmd-J is still used to hide/show the terminal pane.

    {
        "key": "ctrl+x right",
        "command": "workbench.action.terminal.focusNextPane",
        "when": "terminalFocus"
    },
    {
        "key": "ctrl+x left",
        "command": "workbench.action.terminal.focusPreviousPane",
        "when": "terminalFocus"
    },
    {
        "key": "ctrl+x ctrl+down",
        "command": "workbench.action.terminal.focusNext",
        "when": "terminalFocus"
    },
    {
        "key": "ctrl+x ctrl+up",
        "command": "workbench.action.terminal.focusPrevious",
        "when": "terminalFocus"
    },
    {
        "key": "ctrl+x up",
        "command": "workbench.action.navigateUp"
    },
    {
        "key": "ctrl+x down",
        "command": "workbench.action.navigateDown"
    },
    {
        "key": "ctrl+x left",
        "command": "workbench.action.navigateLeft",
        "when": "!terminalFocus"
    },
    {
        "key": "ctrl+x right",
        "command": "workbench.action.navigateRight",
        "when": "!terminalFocus"
    },

VBA Check if variable is empty

How you test depends on the Property's DataType:

| Type                                 | Test                            | Test2
| Numeric (Long, Integer, Double etc.) | If obj.Property = 0 Then        | 
| Boolen (True/False)                  | If Not obj.Property Then        | If obj.Property = False Then
| Object                               | If obj.Property Is Nothing Then |
| String                               | If obj.Property = "" Then       | If LenB(obj.Property) = 0 Then
| Variant                              | If obj.Property = Empty Then    |

You can tell the DataType by pressing F2 to launch the Object Browser and looking up the Object. Another way would be to just use the TypeName function:MsgBox TypeName(obj.Property)

Pointers in C: when to use the ampersand and the asterisk?

Actually, you have it down pat, there's nothing more you need to know :-)

I would just add the following bits:

  • the two operations are opposite ends of the spectrum. & takes a variable and gives you the address, * takes an address and gives you the variable (or contents).
  • arrays "degrade" to pointers when you pass them to functions.
  • you can actually have multiple levels on indirection (char **p means that p is a pointer to a pointer to a char.

As to things working differently, not really:

  • arrays, as already mentioned, degrade to pointers (to the first element in the array) when passed to functions; they don't preserve size information.
  • there are no strings in C, just character arrays that, by convention, represent a string of characters terminated by a zero (\0) character.
  • When you pass the address of a variable to a function, you can de-reference the pointer to change the variable itself (normally variables are passed by value (except for arrays)).

Custom alert and confirm box in jquery

I made custom messagebox using jquery UI component. Here is demo http://jsfiddle.net/eraj2587/Pm5Fr/14/

You have to pass just the parameters like caption name, message, button's text. You can specify trigger function on any button click. This will helpful for you.

How do malloc() and free() work?

In theory, malloc gets memory from the operating system for this application. However, since you may only want 4 bytes, and the OS needs to work in pages (often 4k), malloc does a little more than that. It takes a page, and puts it's own information in there so it can keep track of what you have allocated and freed from that page.

When you allocate 4 bytes, for instance, malloc gives you a pointer to 4 bytes. What you may not realize is that the memory 8-12 bytes before your 4 bytes is being used by malloc to make a chain of all the memory you have allocated. When you call free, it takes your pointer, backs up to where it's data is, and operates on that.

When you free memory, malloc takes that memory block off the chain... and may or may not return that memory to the operating system. If it does, than accessing that memory will probably fail, as the OS will take away your permissions to access that location. If malloc keeps the memory ( because it has other things allocated in that page, or for some optimization ), then the access will happen to work. It's still wrong, but it might work.

DISCLAIMER: What I described is a common implementation of malloc, but by no means the only possible one.

Fatal error: Call to undefined function mysql_connect()

This error is coming only for your PHP version v7.0. you can avoid these using PHP v5.0 else

use it

mysqli_connect("localhost","root","")

i made only mysqli from mysql

How do I ignore all files in a folder with a Git repository in Sourcetree?

As far as I know, Git doesn't track folders, only files - so empty folders (or folders where all files are ignored) cannot be committed. If you e.g. need the folder to be present due to some step in your build process, perhaps you can have your build tool create it instead? Or you could put one empty, unignored file in the folder and commit it.

Is it possible to make desktop GUI application in .NET Core?

AvaloniaUI now has support for running on top of .NET Core on Windows, OS X, and Linux. XAML, bindings and control templates included.

E.g. to develop on macOS with Rider:

  1. Follow instructions to install the Avalonia dotnet new templates
  2. Open JetBrains Rider and from the Welcome screen,
  3. Choose New Solution ? (near the top of the Templates List) ? More Templates ? Button Install Template...* ? browse to the directory where you cloned the templates at step 1.
  4. Click the Reload Button
  5. Behold! Avalonia Templates now appear in the New Solution Templates List!
  6. Choose an Avalonia template
  7. Build and run. See the GUI open before your eyes.

GUI steps to install a dotnet new template into JetBrains Rider

What does an exclamation mark before a cell reference mean?

When entered as the reference of a Named range, it refers to range on the sheet the named range is used on.

For example, create a named range MyName refering to =SUM(!B1:!K1)

Place a formula on Sheet1 =MyName. This will sum Sheet1!B1:K1

Now place the same formula (=MyName) on Sheet2. That formula will sum Sheet2!B1:K1

Note: (as pnuts commented) this and the regular SheetName!B1:K1 format are relative, so reference different cells as the =MyName formula is entered into different cells.

What is base 64 encoding used for?

In the early days of computers, when telephone line inter-system communication was not particularly reliable, a quick & dirty method of verifying data integrity was used: "bit parity". In this method, every byte transmitted would have 7-bits of data, and the 8th would be 1 or 0, to force the total number of 1 bits in the byte to be even.

Hence 0x01 would be transmited as 0x81; 0x02 would be 0x82; 0x03 would remain 0x03 etc.

To further this system, when the ASCII character set was defined, only 00-7F were assigned characters. (Still today, all characters set in the range 80-FF are non-standard)

Many routers of the day put the parity check and byte translation into hardware, forcing the computers attached to them to deal strictly with 7-bit data. This force email attachments (and all other data, which is why HTTP & SMTP protocols are text-based), to be convert into a text-only format.

Few of the routers survived into the 90s. I severely doubt any of them are in use today.

gcc makefile error: "No rule to make target ..."

This error occurred for me inside Travis when I forgot to add new files to my git repository. Silly mistake, but I can see it being quite common.

Check whether a path is valid in Python without creating a file at the path's target

try os.path.exists this will check for the path and return True if exists and False if not.

TypeScript function overloading

You can declare an overloaded function by declaring the function as having a type which has multiple invocation signatures:

interface IFoo
{
    bar: {
        (s: string): number;
        (n: number): string;
    }
}

Then the following:

var foo1: IFoo = ...;

var n: number = foo1.bar('baz');     // OK
var s: string = foo1.bar(123);       // OK
var a: number[] = foo1.bar([1,2,3]); // ERROR

The actual definition of the function must be singular and perform the appropriate dispatching internally on its arguments.

For example, using a class (which could implement IFoo, but doesn't have to):

class Foo
{
    public bar(s: string): number;
    public bar(n: number): string;
    public bar(arg: any): any 
    {
        if (typeof(arg) === 'number')
            return arg.toString();
        if (typeof(arg) === 'string')
            return arg.length;
    }
}

What's interesting here is that the any form is hidden by the more specifically typed overrides.

var foo2: new Foo();

var n: number = foo2.bar('baz');     // OK
var s: string = foo2.bar(123);       // OK
var a: number[] = foo2.bar([1,2,3]); // ERROR

Angular2: child component access parent class variable/function

You can do this In the parent component declare:

get self(): ParenComponentClass {
        return this;
    }

In the child component,after include the import of ParenComponentClass, declare:

private _parent: ParenComponentClass ;
@Input() set parent(value: ParenComponentClass ) {
    this._parent = value;
}

get parent(): ParenComponentClass {
    return this._parent;
}

Then in the template of the parent you can do

<childselector [parent]="self"></childselector>

Now from the child you can access public properties and methods of parent using

this.parent

How to programmatically set style attribute in a view

At runtime, you know what style you want your button to have. So beforehand, in xml in the layout folder, you can have all ready to go buttons with the styles you need. So in the layout folder, you might have a file named: button_style_1.xml. The contents of that file might look like:

<?xml version="1.0" encoding="utf-8"?>
<Button
    android:id="@+id/styleOneButton"
    style="@style/FirstStyle" />

If you are working with fragments, then in onCreateView you inflate that button, like:

Button firstStyleBtn = (Button) inflater.inflate(R.layout.button_style_1, container, false);

where container is the ViewGroup container associated with the onCreateView method you override when creating your fragment.

Need two more such buttons? You create them like this:

Button secondFirstStyleBtn = (Button) inflater.inflate(R.layout.button_style_1, container, false);
Button thirdFirstStyleBtn = (Button) inflater.inflate(R.layout.button_style_1, container, false);

You can customize those buttons:

secondFirstStyleBtn.setText("My Second");
thirdFirstStyleBtn.setText("My Third");

Then you add your customized, stylized buttons to the layout container you also inflated in the onCreateView method:

_stylizedButtonsContainer = (LinearLayout) rootView.findViewById(R.id.stylizedButtonsContainer);

_stylizedButtonsContainer.addView(firstStyleBtn);
_stylizedButtonsContainer.addView(secondFirstStyleBtn);
_stylizedButtonsContainer.addView(thirdFirstStyleBtn);

And that's how you can dynamically work with stylized buttons.

Why avoid increment ("++") and decrement ("--") operators in JavaScript?

There is a history in C of doing things like:

while (*a++ = *b++);

to copy a string, perhaps this is the source of the excessive trickery he is referring to.

And there's always the question of what

++i = i++;

or

i = i++ + ++i;

actually do. It's defined in some languages, and in other's there's no guarantee what will happen.

Those examples aside, I don't think there's anything more idiomatic than a for loop that uses ++ to increment. In some cases you could get away with a foreach loop, or a while loop that checked a different condtion. But contorting your code to try and avoid using incrementing is ridiculous.

android - listview get item view by position

This is the Kotlin version of the function posted by VVB. I used it in the ListView Adapter to implement the "go to next row first EditText when Enter key is pressed on the last EditText of current row" feature in the getView().

In the ListViewAdapter class, fun getView(), add lastEditText.setOnKeyListner as below:

lastEditText.setOnKeyListener { v, keyCode, event ->
    var setOnKeyListener = false
    if (keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_UP) {
        try {
            val nextRow = getViewByPosition(position + 1, parent as ListView) as LinearLayout
            val nextET = nextRow.findViewById(R.id.firstEditText) as EditText
            nextET.isFocusableInTouchMode = true
            nextET.requestFocus()
        } catch (e: Exception) {
            // do nothing
        }
        setOnKeyListener = true
    }
    setOnKeyListener
}

add the fun getViewByPosition() after fun getView() as below:

private fun getViewByPosition(pos: Int, listView: ListView): View? {
    val firstListItemPosition: Int = listView.firstVisiblePosition
    val lastListItemPosition: Int = firstListItemPosition + listView.childCount - 1
    return if (pos < firstListItemPosition || pos > lastListItemPosition) {
        listView.adapter.getView(pos, null, listView)
    } else {
        val childIndex = pos + listView.headerViewsCount - firstListItemPosition
        listView.getChildAt(childIndex)
    }
}

Dockerfile copy keep subdirectory structure

Alternatively you can use a "." instead of *, as this will take all the files in the working directory, include the folders and subfolders:

FROM ubuntu
COPY . /
RUN ls -la /

Convert string to title case with JavaScript

A slightly more elegant way, adapting Greg Dean's function:

String.prototype.toProperCase = function () {
    return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
};

Call it like:

"pascal".toProperCase();

How to get a file or blob from an object URL?

If you show the file in a canvas anyway you can also convert the canvas content to a blob object.

canvas.toBlob(function(my_file){
  //.toBlob is only implemented in > FF18 but there is a polyfill 
  //for other browsers https://github.com/blueimp/JavaScript-Canvas-to-Blob
  var myBlob = (my_file);
})

How to programmatically close a JFrame

Based on the answers already provided here, this is the way I implemented it:

JFrame frame= new JFrame()
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// frame stuffs here ...

frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));

The JFrame gets the event to close and upon closing, exits.

How to change a package name in Eclipse?

create a new package, drag and drop the class into it and now you are able to rename the new package

How do I dump an object's fields to the console?

object.attribute_names

# => ["id", "name", "email", "created_at", "updated_at", "password_digest", "remember_token", "admin", "marketing_permissions", "terms_and_conditions", "disable", "black_list", "zero_cost", "password_reset_token", "password_reset_sent_at"]


object.attributes.values

# => [1, "tom", "[email protected]", Tue, 02 Jun 2015 00:16:03 UTC +00:00, Tue, 02 Jun 2015 00:22:35 UTC +00:00, "$2a$10$gUTr3lpHzXvCDhVvizo8Gu/MxiTrazOWmOQqJXMW8gFLvwDftF9Lm", "2dd1829c9fb3af2a36a970acda0efe5c1d471199", true, nil, nil, nil, nil, nil, nil, nil] 

Color different parts of a RichTextBox string

Selecting text as said from somebody, may the selection appear momentarily. In Windows Forms applications there is no other solutions for the problem, but today I found a bad, working, way to solve: you can put a PictureBox in overlapping to the RichtextBox with the screenshot of if, during the selection and the changing color or font, making it after reappear all, when the operation is complete.

Code is here...

//The PictureBox has to be invisible before this, at creation
//tb variable is your RichTextBox
//inputPreview variable is your PictureBox
using (Graphics g = inputPreview.CreateGraphics())
{
    Point loc = tb.PointToScreen(new Point(0, 0));
    g.CopyFromScreen(loc, loc, tb.Size);
    Point pt = tb.GetPositionFromCharIndex(tb.TextLength);
    g.FillRectangle(new SolidBrush(Color.Red), new Rectangle(pt.X, 0, 100, tb.Height));
}
inputPreview.Invalidate();
inputPreview.Show();
//Your code here (example: tb.Select(...); tb.SelectionColor = ...;)
inputPreview.Hide();

Better is to use WPF; this solution isn't perfect, but for Winform it works.

How can I mimic the bottom sheet from the Maps app?

I wrote my own library to achieve the intended behaviour in ios Maps app. It is a protocol oriented solution. So you don't need to inherit any base class instead create a sheet controller and configure as you wish. It also supports inner navigation/presentation with or without UINavigationController.

See below link for more details.

https://github.com/OfTheWolf/UBottomSheet

ubottom sheet

Found a swap file by the name

More info... Some times .swp files might be holded by vm that was running in backgroung. You may see permission denied message when try to delete the files.

Check and kill process vm

Parsing XML in Python using ElementTree example

So I have ElementTree 1.2.6 on my box now, and ran the following code against the XML chunk you posted:

import elementtree.ElementTree as ET

tree = ET.parse("test.xml")
doc = tree.getroot()
thingy = doc.find('timeSeries')

print thingy.attrib

and got the following back:

{'name': 'NWIS Time Series Instantaneous Values'}

It appears to have found the timeSeries element without needing to use numerical indices.

What would be useful now is knowing what you mean when you say "it doesn't work." Since it works for me given the same input, it is unlikely that ElementTree is broken in some obvious way. Update your question with any error messages, backtraces, or anything you can provide to help us help you.

Can I redirect the stdout in python into some sort of string buffer?

This method restores sys.stdout even if there's an exception. It also gets any output before the exception.

import io
import sys

real_stdout = sys.stdout
fake_stdout = io.BytesIO()   # or perhaps io.StringIO()
try:
    sys.stdout = fake_stdout
    # do what you have to do to create some output
finally:
    sys.stdout = real_stdout
    output_string = fake_stdout.getvalue()
    fake_stdout.close()
    # do what you want with the output_string

Tested in Python 2.7.10 using io.BytesIO()

Tested in Python 3.6.4 using io.StringIO()


Bob, added for a case if you feel anything from the modified / extended code experimentation might get interesting in any sense, otherwise feel free to delete it

Ad informandum ... a few remarks from extended experimentation during finding some viable mechanics to "grab" outputs, directed by numexpr.print_versions() directly to the <stdout> ( upon a need to clean GUI and collecting details into debugging-report )

# THIS WORKS AS HELL: as Bob Stein proposed years ago:
#  py2 SURPRISEDaBIT:
#
import io
import sys
#
real_stdout = sys.stdout                        #           PUSH <stdout> ( store to REAL_ )
fake_stdout = io.BytesIO()                      #           .DEF FAKE_
try:                                            # FUSED .TRY:
    sys.stdout.flush()                          #           .flush() before
    sys.stdout = fake_stdout                    #           .SET <stdout> to use FAKE_
    # ----------------------------------------- #           +    do what you gotta do to create some output
    print 123456789                             #           + 
    import  numexpr                             #           + 
    QuantFX.numexpr.__version__                 #           + [3] via fake_stdout re-assignment, as was bufferred + "late" deferred .get_value()-read into print, to finally reach -> real_stdout
    QuantFX.numexpr.print_versions()            #           + [4] via fake_stdout re-assignment, as was bufferred + "late" deferred .get_value()-read into print, to finally reach -> real_stdout
    _ = os.system( 'echo os.system() redir-ed' )#           + [1] via real_stdout                                 + "late" deferred .get_value()-read into print, to finally reach -> real_stdout, if not ( _ = )-caught from RET-d "byteswritten" / avoided from being injected int fake_stdout
    _ = os.write(  sys.stderr.fileno(),         #           + [2] via      stderr                                 + "late" deferred .get_value()-read into print, to finally reach -> real_stdout, if not ( _ = )-caught from RET-d "byteswritten" / avoided from being injected int fake_stdout
                       b'os.write()  redir-ed' )#  *OTHERWISE, if via fake_stdout, EXC <_io.BytesIO object at 0x02C0BB10> Traceback (most recent call last):
    # ----------------------------------------- #           ?                              io.UnsupportedOperation: fileno
    #'''                                                    ? YET:        <_io.BytesIO object at 0x02C0BB10> has a .fileno() method listed
    #>>> 'fileno' in dir( sys.stdout )       -> True        ? HAS IT ADVERTISED,
    #>>> pass;            sys.stdout.fileno  -> <built-in method fileno of _io.BytesIO object at 0x02C0BB10>
    #>>> pass;            sys.stdout.fileno()-> Traceback (most recent call last):
    #                                             File "<stdin>", line 1, in <module>
    #                                           io.UnsupportedOperation: fileno
    #                                                       ? BUT REFUSES TO USE IT
    #'''
finally:                                        # == FINALLY:
    sys.stdout.flush()                          #           .flush() before ret'd back REAL_
    sys.stdout = real_stdout                    #           .SET <stdout> to use POP'd REAL_
    sys.stdout.flush()                          #           .flush() after  ret'd back REAL_
    out_string = fake_stdout.getvalue()         #           .GET string           from FAKE_
    fake_stdout.close()                         #                <FD>.close()
    # +++++++++++++++++++++++++++++++++++++     # do what you want with the out_string
    #
    print "\n{0:}\n{1:}{0:}".format( 60 * "/\\",# "LATE" deferred print the out_string at the very end reached -> real_stdout
                                     out_string #                   
                                     )
'''
PASS'd:::::
...
os.system() redir-ed
os.write()  redir-ed
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
123456789
'2.5'
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Numexpr version:   2.5
NumPy version:     1.10.4
Python version:    2.7.13 |Anaconda 4.0.0 (32-bit)| (default, May 11 2017, 14:07:41) [MSC v.1500 32 bit (Intel)]
AMD/Intel CPU?     True
VML available?     True
VML/MKL version:   Intel(R) Math Kernel Library Version 11.3.1 Product Build 20151021 for 32-bit applications
Number of threads used by default: 4 (out of 4 detected cores)
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
>>>

EXC'd :::::
...
os.system() redir-ed
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
123456789
'2.5'
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Numexpr version:   2.5
NumPy version:     1.10.4
Python version:    2.7.13 |Anaconda 4.0.0 (32-bit)| (default, May 11 2017, 14:07:41) [MSC v.1500 32 bit (Intel)]
AMD/Intel CPU?     True
VML available?     True
VML/MKL version:   Intel(R) Math Kernel Library Version 11.3.1 Product Build 20151021 for 32-bit applications
Number of threads used by default: 4 (out of 4 detected cores)
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\

Traceback (most recent call last):
  File "<stdin>", line 9, in <module>
io.UnsupportedOperation: fileno
'''

How to send a POST request in Go?

I know this is old but this answer came up in search results. For the next guy - the proposed and accepted answer works, however the code initially submitted in the question is lower-level than it needs to be. Nobody got time for that.

//one-line post request/response...
response, err := http.PostForm(APIURL, url.Values{
    "ln": {c.ln},
    "ip": {c.ip},
    "ua": {c.ua}})

//okay, moving on...
if err != nil {
  //handle postform error
}

defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)

if err != nil {
  //handle read response error
}

fmt.Printf("%s\n", string(body))

https://golang.org/pkg/net/http/#pkg-overview

Calling a function within a Class method?

Try this one:

class test {
     public function newTest(){
          $this->bigTest();
          $this->smallTest();
     }

     private function bigTest(){
          //Big Test Here
     }

     private function smallTest(){
          //Small Test Here
     }

     public function scoreTest(){
          //Scoring code here;
     }
}

$testObject = new test();

$testObject->newTest();

$testObject->scoreTest();

'import' and 'export' may only appear at the top level

This is not direct answer to the original question but I hope this suggestion helps someones with similar error:

When using a newer web-api with Webpack+Babel for transpiling and you get

Module parse failed: 'import' and 'export' may only appear at the top level

then you probably forgot to import a polyfill.

For example:
when using fetch() api and targeting for es2015, you should

  1. add whatwg-fetch polyfill to package.json
  2. add import {fetch} from 'whatwg-fetch'

Return generated pdf using spring MVC

You were on the right track with response.getOutputStream(), but you're not using its output anywhere in your code. Essentially what you need to do is to stream the PDF file's bytes directly to the output stream and flush the response. In Spring you can do it like this:

@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public ResponseEntity<byte[]> getPDF(@RequestBody String json) {
    // convert JSON to Employee 
    Employee emp = convertSomehow(json);

    // generate the file
    PdfUtil.showHelp(emp);

    // retrieve contents of "C:/tmp/report.pdf" that were written in showHelp
    byte[] contents = (...);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_PDF);
    // Here you have to set the actual filename of your pdf
    String filename = "output.pdf";
    headers.setContentDispositionFormData(filename, filename);
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
    return response;
}

Notes:

  • use meaningful names for your methods: naming a method that writes a PDF document showHelp is not a good idea
  • reading a file into a byte[]: example here
  • I'd suggest adding a random string to the temporary PDF file name inside showHelp() to avoid overwriting the file if two users send a request at the same time

How to convert hex to ASCII characters in the Linux shell?

You can use this command (python script) for larger inputs:

echo 58595a | python -c "import sys; import binascii; print(binascii.unhexlify(sys.stdin.read().strip()).decode())"

The result will be:

XYZ

And for more simplicity, define an alias:

alias hexdecoder='python -c "import sys; import binascii; print(binascii.unhexlify(sys.stdin.read().strip()).decode())"'

echo 58595a | hexdecoder

Run PowerShell command from command prompt (no ps1 script)

Here is the only answer that managed to work for my problem, got it figured out with the help of this webpage (nice reference).

powershell -command "& {&'some-command' someParam}"

Also, here is a neat way to do multiple commands:

powershell -command "& {&'some-command' someParam}"; "& {&'some-command' -SpecificArg someParam}"

For example, this is how I ran my 2 commands:

powershell -command "& {&'Import-Module' AppLocker}"; "& {&'Set-AppLockerPolicy' -XmlPolicy myXmlFilePath.xml}"

textarea's rows, and cols attribute in CSS

<textarea rows="4" cols="50"></textarea>

It is equivalent to:

textarea {
    height: 4em;
    width: 50em;
}

where 1em is equivalent to the current font size, thus make the text area 50 chars wide. see here.

Unable to open debugger port in IntelliJ IDEA

While debug I got this issue: It worked with

  1. tried changing my Tomcat http port 8082 to 8083(In debug configurations on IntelliJ and in Tomcat->conf->server.xml also)
  2. tried changing JMX port from 1099 to 1009.
  3. tried changing debug port in Startup/Connection in debug configurations
  4. killed all java processes in TaskManager->Processes.

Open mvc view in new window from controller

@Html.ActionLink("linkText", "Action", new {controller="Controller"}, new {target="_blank",@class="edit"})

   script below will open the action view url in a new window

<script type="text/javascript">
    $(function (){
        $('a.edit').click(function () {
            var url = $(this).attr('href');
            window.open(url, "popupWindow", "width=600,height=800,scrollbars=yes");
            });
            return false;
        });   
</script>

SQL Server CASE .. WHEN .. IN statement

Thanks for the Answer I have modified the statements to look like below

SELECT
     AlarmEventTransactionTable.TxnID,
     CASE 
    WHEN DeviceID IN('7', '10', '62', '58', '60',
            '46', '48', '50', '137', '139',
             '141', '145', '164') THEN '01'
    WHEN DeviceID IN('8', '9', '63', '59', '61',
            '47', '49', '51', '138', '140',
            '142', '146', '165') THEN '02'
             ELSE 'NA' END AS clocking,
     AlarmEventTransactionTable.DateTimeOfTxn
FROM
     multiMAXTxn.dbo.AlarmEventTransactionTable

jQuery get the location of an element relative to window

TL;DR

headroom_by_jQuery = $('#id').offset().top - $(window).scrollTop();

headroom_by_DOM = $('#id')[0].getBoundingClientRect().top;   // if no iframe

.getBoundingClientRect() appears to be universal. .offset() and .scrollTop() have been supported since jQuery 1.2. Thanks @user372551 and @prograhammer. To use DOM in an iframe see @ImranAnsari's solution.

Passing arguments to an interactive program non-interactively

You can put the data in a file and re-direct it like this:

$ cat file.sh
#!/bin/bash

read x
read y
echo $x
echo $y

Data for the script:

$ cat data.txt
2
3

Executing the script:

$ file.sh < data.txt
2
3

How to interactively (visually) resolve conflicts in SourceTree / git

From SourceTree, click on Tools->Options. Then on the "General" tab, make sure to check the box to allow SourceTree to modify your Git config files.

Then switch to the "Diff" tab. On the lower half, use the drop down to select the external program you want to use to do the diffs and merging. I've installed KDiff3 and like it well enough. When you're done, click OK.

Now when there is a merge, you can go under Actions->Resolve Conflicts->Launch External Merge Tool.

Retrieve data from a ReadableStream object?

Little bit late to the party but had some problems with getting something useful out from a ReadableStream produced from a Odata $batch request using the Sharepoint Framework.

Had similar issues as OP, but the solution in my case was to use a different conversion method than .json(). In my case .text() worked like a charm. Some fiddling was however necessary to get some useful JSON from the textfile.

Difference between the Apache HTTP Server and Apache Tomcat?

If you are using java technology(Servlet/JSP) for making web application you will probably use Apache Tomcat. However, if you are using other technologies like Perl, PHP or ruby, its better(easier) to use Apache HTTP Server.

How to create a secure random AES key in Java?

Using KeyGenerator would be the preferred method. As Duncan indicated, I would certainly give the key size during initialization. KeyFactory is a method that should be used for pre-existing keys.

OK, so lets get to the nitty-gritty of this. In principle AES keys can have any value. There are no "weak keys" as in (3)DES. Nor are there any bits that have a specific meaning as in (3)DES parity bits. So generating a key can be as simple as generating a byte array with random values, and creating a SecretKeySpec around it.

But there are still advantages to the method you are using: the KeyGenerator is specifically created to generate keys. This means that the code may be optimized for this generation. This could have efficiency and security benefits. It might be programmed to avoid a timing side channel attacks that would expose the key, for instance. Note that it may already be a good idea to clear any byte[] that hold key information as they may be leaked into a swap file (this may be the case anyway though).

Furthermore, as said, not all algorithms are using fully random keys. So using KeyGenerator would make it easier to switch to other algorithms. More modern ciphers will only accept fully random keys though; this is seen as a major benefit over e.g. DES.

Finally, and in my case the most important reason, it that the KeyGenerator method is the only valid way of handling AES keys within a secure token (smart card, TPM, USB token or HSM). If you create the byte[] with the SecretKeySpec then the key must come from memory. That means that the key may be put in the secure token, but that the key is exposed in memory regardless. Normally, secure tokens only work with keys that are either generated in the secure token or are injected by e.g. a smart card or a key ceremony. A KeyGenerator can be supplied with a provider so that the key is directly generated within the secure token.

As indicated in Duncan's answer: always specify the key size (and any other parameters) explicitly. Do not rely on provider defaults as this will make it unclear what your application is doing, and each provider may have its own defaults.

Powershell Error "The term 'Get-SPWeb' is not recognized as the name of a cmdlet, function..."

Run this script from SharePoint 2010 Management Shell as Administrator.

Warning about `$HTTP_RAW_POST_DATA` being deprecated

Well, if there's anyone out there on a shared hosting and with no access to php.ini file, you can set this line of code at the very top of your PHP files:

ini_set('always_populate_raw_post_data', -1);

Works more of the same. I hope it saves someone some debugging time :)

Delete files in subfolder using batch script

I had to complete the same task and I used a "for" loop and a "del" command as follows:

@ECHO OFF

set dir=%cd%

FOR /d /r %dir% %%x in (archive\) do (
    if exist "%%x" del %%x\*.txt /f /q
)

You can set the dir variable with any start directory you want or used the current directory (%cd%) variable.

These are the options for "for" command:

  • /d For directories
  • /r For recursive

These are the options for "del" command:

  • /f Force deletes read-only files
  • /q Quiet mode; suppresses prompts for delete confirmations.

What is a None value?

None is just a value that commonly is used to signify 'empty', or 'no value here'. It is a signal object; it only has meaning because the Python documentation says it has that meaning.

There is only one copy of that object in a given Python interpreter session.

If you write a function, and that function doesn't use an explicit return statement, None is returned instead, for example. That way, programming with functions is much simplified; a function always returns something, even if it is only that one None object.

You can test for it explicitly:

if foo is None:
    # foo is set to None

if bar is not None:
    # bar is set to something *other* than None

Another use is to give optional parameters to functions an 'empty' default:

def spam(foo=None):
    if foo is not None:
        # foo was specified, do something clever!

The function spam() has a optional argument; if you call spam() without specifying it, the default value None is given to it, making it easy to detect if the function was called with an argument or not.

Other languages have similar concepts. SQL has NULL; JavaScript has undefined and null, etc.

Note that in Python, variables exist by virtue of being used. You don't need to declare a variable first, so there are no really empty variables in Python. Setting a variable to None is then not the same thing as setting it to a default empty value; None is a value too, albeit one that is often used to signal emptyness. The book you are reading is misleading on that point.

Security of REST authentication schemes

If you require the hash of the body as one of the parameters in the URL and that URL is signed via a private key, then a man-in-the-middle attack would only be able to replace the body with content that would generate the same hash. Easy to do with MD5 hash values now at least and when SHA-1 is broken, well, you get the picture.

To secure the body from tampering, you would need to require a signature of the body, which a man-in-the-middle attack would be less likely to be able to break since they wouldn't know the private key that generates the signature.

What is the documents directory (NSDocumentDirectory)?

Like others mentioned, your app runs in a sandboxed environment and you can use the documents directory to store images or other assets your app may use, eg. downloading offline-d files as user prefers - File System Basics - Apple Documentation - Which directory to use, for storing application specific files

Updated to swift 5, you can use one of these functions, as per requirement -

func getDocumentsDirectory() -> URL {
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    return paths[0]
}

func getCacheDirectory() -> URL {
        let paths = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)
        return paths[0]
    }

func getApplicationSupportDirectory() -> URL {
        let paths = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)
        return paths[0]
    }

Usage:

let urlPath = "https://jumpcloud.com/wp-content/uploads/2017/06/SSH-Keys.png" //Or string path to some URL of valid image, for eg.

if let url = URL(string: urlPath){
    let destination = getDocumentsDirectory().appendingPathComponent(url.lastPathComponent)
    do {
        let data = try Data(contentsOf: url) //Synchronous call, just as an example
        try data.write(to: destination)
    } catch _ {
        //Do something to handle the error
    }
}

WinForms DataGridView font size

Go to designer.cs file of the form in which you have the grid view and comment the following line: - //this.dataGridView1.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle1;

if you are using vs 2008 or .net framework 3.5 as it will be by default applied to alternating rows.

How to convert seconds to HH:mm:ss in moment.js

From this post I would try this to avoid leap issues

moment("2015-01-01").startOf('day')
    .seconds(s)
    .format('H:mm:ss');

I did not run jsPerf, but I would think this is faster than creating new date objects a million times

function pad(num) {
    return ("0"+num).slice(-2);
}
function hhmmss(secs) {
  var minutes = Math.floor(secs / 60);
  secs = secs%60;
  var hours = Math.floor(minutes/60)
  minutes = minutes%60;
  return `${pad(hours)}:${pad(minutes)}:${pad(secs)}`;
  // return pad(hours)+":"+pad(minutes)+":"+pad(secs); for old browsers
}

_x000D_
_x000D_
function pad(num) {_x000D_
    return ("0"+num).slice(-2);_x000D_
}_x000D_
function hhmmss(secs) {_x000D_
  var minutes = Math.floor(secs / 60);_x000D_
  secs = secs%60;_x000D_
  var hours = Math.floor(minutes/60)_x000D_
  minutes = minutes%60;_x000D_
  return `${pad(hours)}:${pad(minutes)}:${pad(secs)}`;_x000D_
  // return pad(hours)+":"+pad(minutes)+":"+pad(secs); for old browsers_x000D_
}_x000D_
_x000D_
for (var i=60;i<=60*60*5;i++) {_x000D_
 document.write(hhmmss(i)+'<br/>');_x000D_
}_x000D_
_x000D_
_x000D_
/* _x000D_
function show(s) {_x000D_
  var d = new Date();_x000D_
  var d1 = new Date(d.getTime()+s*1000);_x000D_
  var  hms = hhmmss(s);_x000D_
  return (s+"s = "+ hms + " - "+ Math.floor((d1-d)/1000)+"\n"+d.toString().split("GMT")[0]+"\n"+d1.toString().split("GMT")[0]);_x000D_
}    _x000D_
*/
_x000D_
_x000D_
_x000D_

WebView link click open default browser

You can use an Intent for this:

Uri uriUrl = Uri.parse("http://www.google.com/"); 
Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);  
startActivity(launchBrowser);  

How do I run all Python unit tests in a directory?

In case of a packaged library or application, you don't want to do it. setuptools will do it for you.

To use this command, your project’s tests must be wrapped in a unittest test suite by either a function, a TestCase class or method, or a module or package containing TestCase classes. If the named suite is a module, and the module has an additional_tests() function, it is called and the result (which must be a unittest.TestSuite) is added to the tests to be run. If the named suite is a package, any submodules and subpackages are recursively added to the overall test suite.

Just tell it where your root test package is, like:

setup(
    # ...
    test_suite = 'somepkg.test'
)

And run python setup.py test.

File-based discovery may be problematic in Python 3, unless you avoid relative imports in your test suite, because discover uses file import. Even though it supports optional top_level_dir, but I had some infinite recursion errors. So a simple solution for a non-packaged code is to put the following in __init__.py of your test package (see load_tests Protocol).

import unittest

from . import foo, bar


def load_tests(loader, tests, pattern):
    suite = unittest.TestSuite()
    suite.addTests(loader.loadTestsFromModule(foo))
    suite.addTests(loader.loadTestsFromModule(bar))

    return suite

Multi-Line Comments in Ruby?

Here is an example :

=begin 
print "Give me a number:"
number = gets.chomp.to_f

total = number * 10
puts  "The total value is : #{total}"

=end

Everything you place in between =begin and =end will be treated as a comment regardless of how many lines of code it contains between.

Note: Make sure there is no space between = and begin:

  • Correct: =begin
  • Wrong: = begin

TypeScript and React - children type?

From the TypeScript site: https://github.com/Microsoft/TypeScript/issues/6471

The recommended practice is to write the props type as {children?: any}

That worked for me. The child node can be many different things, so explicit typing can miss cases.

There's a longer discussion on the followup issue here: https://github.com/Microsoft/TypeScript/issues/13618, but the any approach still works.

Excel- compare two cell from different sheet, if true copy value from other cell

In your destination field you want to use VLOOKUP like so:

=VLOOKUP(Sheet1!A1:A100,Sheet2!A1:F100,6,FALSE)

VLOOKUP Arguments:

  1. The set fields you want to lookup.
  2. The table range you want to lookup up your value against. The first column of your defined table should be the column you want compared against your lookup field. The table range should also contain the value you want to display (Column F).
  3. This defines what field you want to display upon a match.
  4. FALSE tells VLOOKUP to do an exact match.

server error:405 - HTTP verb used to access this page is not allowed

I fixed mine by adding these lines on my IIS webconfig.

<httpErrors>
    <remove statusCode="405" subStatusCode="-1" />
    <error statusCode="405" prefixLanguageFilePath="" path="/my-page.htm" responseMode="ExecuteURL" />
</httpErrors>

How to "fadeOut" & "remove" a div in jQuery?

Have you tried this?

$("#notification").fadeOut(300, function(){ 
    $(this).remove();
});

That is, using the current this context to target the element in the inner function and not the id. I use this pattern all the time - it should work.

C/C++ switch case with string

Ruslik's suggestion to use source generation seems like a good thing to me. However, I wouldn't go with the concept of "main" and "generated" source files. I'd rather have one file with code almost identical to yours:

h=_myhash (mystring);
switch (h)
{
case 66452: // = hash("Vasia")
   .......
case 1342537: // = hash("Petya")
   ........
}

The next thing I'd do, I'd write a simple script. Perl is good for such kind of things, but nothing stops you even from writing a simple program in C/C++ if you don't want to use any other languages. This script, or program, would take the source file, read it line-by-line, find all those case NUMBERS: // = hash("SOMESTRING") lines (use regular expressions here), replace NUMBERS with the actual hash value and write the modified source into a temporary file. Finally, it would back up the source file and replace it with the temporary file. If you don't want your source file to have a new time stamp each time, the program could check if something was actually changed and if not, skip the file replacement.

The last thing to do is to integrate this script into the build system used, so you won't accidentally forget to launch it before building the project.

How to make a simple rounded button in Storyboard?

You can connect IBOutlet of yur button from storyboard.

Then you can set corner radius of your button to make it's corner round.

for example, your outlet is myButton then,

Obj - C

 self.myButton.layer.cornerRadius = 5.0 ;

Swift

  myButton.layer.cornerRadius = 5.0

If you want exact round button then your button's width and height must be equal and cornerRadius must be equal to height or width / 2 (half of the width or height).

Why is textarea filled with mysterious white spaces?

I got the same problem, and the solution is very simple: don't start a new line! Although some of the previous answers can solve the problem, the idea is not stated clearly. The important understanding is, to get rid of the unintended spaces, never start a new line just after your start tag.

The following way is WRONG and will leave a lot of unwanted spaces before your text content:

 <textarea>
    text content // start with a new line will leave a lot of unwanted spaces
 </textarea>

The RIGHT WAY to do it is:

 <textarea>text content //put text content right after your start tag, no new line
 </textarea>

How to change the text of a button in jQuery?

Have you gave your button a class instead of an id? try the following code

$(".btnSave").attr('value', 'Save');

Setting up maven dependency for SQL Server

It looks like Microsoft has published some their drivers to maven central:

<dependency>
    <groupId>com.microsoft.sqlserver</groupId>
    <artifactId>mssql-jdbc</artifactId>
    <version>6.1.0.jre8</version>
</dependency>

How to localise a string inside the iOS info.plist file?

All the above did not work for me (XCode 7.3) so I read Apple reference on how to do, and it is much simpler than described above. According to Apple:

Localized values are not stored in the Info.plist file itself. Instead, you store the values for a particular localization in a strings file with the name InfoPlist.strings. You place this file in the same language-specific project directory that you use to store other resources for the same localization.

Accordingly, I created a string file named InfoPlist.strings and placed it in the xx.lproj folder of the "xx" language (and added it to the project using File->Add Files to ...). That's it. No need for the key "Localized resources can be mixed" = YES, and no need for InfoPlist.strings in base.lproj or en.lproj.

The application uses the Info.plist key-value as the default value if it can not find a key in the language specific file. Thus, I put my English value in the Info.plist file and the translated one in the language specific file, tested and everything works.

In particular, there is no need to localize the InfoPlist.strings (which creates a version of the file in the base.lproj, en.lroj, and xx.lproj), and in my case going that way did not work.

Is it possible to use a batch file to establish a telnet session, send a command and have the output written to a file?

I figured out a way to telnet to a server and change a file permission. Then FTP the file back to your computer and open it. Hopefully this will answer your questions and also help FTP.

The filepath variable is setup so you always login and cd to the same directory. You can change it to a prompt so the user can enter it manually.

:: This will telnet to the server, change the permissions, 
:: download the file, and then open it from your PC. 

:: Add your username, password, servername, and file path to the file.
:: I have not tested the server name with an IP address.

:: Note - telnetcmd.dat and ftpcmd.dat are temp files used to hold commands

@echo off
SET username=
SET password=
SET servername=
SET filepath=

set /p id="Enter the file name: " %=%

echo user %username%> telnetcmd.dat
echo %password%>> telnetcmd.dat
echo cd %filepath%>> telnetcmd.dat
echo SITE chmod 777 %id%>> telnetcmd.dat
echo exit>> telnetcmd.dat
telnet %servername% < telnetcmd.dat


echo user %username%> ftpcmd.dat
echo %password%>> ftpcmd.dat
echo cd %filepath%>> ftpcmd.dat
echo get %id%>> ftpcmd.dat
echo quit>> ftpcmd.dat

ftp -n -s:ftpcmd.dat %servername%
del ftpcmd.dat
del telnetcmd.dat

callback to handle completion of pipe

Streams are EventEmitters so you can listen to certain events. As you said there is a finish event for request (previously end).

 var stream = request(...).pipe(...);
 stream.on('finish', function () { ... });

For more information about which events are available you can check the stream documentation page.

How to completely uninstall Android Studio on Mac?

You may also delete gradle file, if you don't use gradle any where else:

rm -Rfv ~/.gradle/

because .gradle folder contains cached artifacts that are no longer needed.

Plotting multiple lines, in different colors, with pandas dataframe

You can use this code to get your desire output

import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'color': ['red','red','red','blue','blue','blue'], 'x': [0,1,2,3,4,5],'y': [0,1,2,9,16,25]})
print df

  color  x   y
0   red  0   0
1   red  1   1
2   red  2   2
3  blue  3   9
4  blue  4  16
5  blue  5  25

To plot graph

a = df.iloc[[i for i in xrange(0,len(df)) if df['x'][i]==df['y'][i]]].plot(x='x',y='y',color = 'red')
df.iloc[[i for i in xrange(0,len(df)) if df['y'][i]== df['x'][i]**2]].plot(x='x',y='y',color = 'blue',ax=a)

plt.show()

Output The output result will look like this

Onclick on bootstrap button

Just like any other click event, you can use jQuery to register an element, set an id to the element and listen to events like so:

$('#myButton').on('click', function(event) {
  event.preventDefault(); // To prevent following the link (optional)
  ...
});

You can also use inline javascript in the onclick attribute:

<a ... onclick="myFunc();">..</a>

estimating of testing effort as a percentage of development time

Gartner in Oct 2006 states that testing typically consumes between 10% and 35% of work on a system integration project. I assume that it applies to the waterfall method. This is quite a wide range - but there are many dependencies on the amount of customisations to a standard product and the number of systems to be integrated.

Arduino COM port doesn't work

Installing Drivers for Arduino in Windows 8 / 7.

( I tried it for Uno r3, but i believe it will work for all Arduino Boards )

Plugin your Arduino Board

Go to Control Panel ---> System and Security ---> System ---> On the left pane Device Manger

Expand Other Devices.

Under Other Devices you will notice a icon with a small yellow error graphic. (Unplug all your other devices attached to any Serial Port)

Right Click on that device ---> Update Driver Software

Select Browse my computer for Driver Software

Click on Browse ---> Browse for the folder of Arduino Environment which you have downloaded from Arduino website. If not downloaded then http://arduino.cc/en/Main/Software

After Browsing mark include subfolder.

Click next ---> Your driver will be installed.

Collapse Other Devices ---> Expand Port ( its in device manager only under other devices )

You will see Arduino Written ---> Look for its COM PORT (close device manager)

Go to Arduino Environment ---> Tools ---> Serial Port ---> Select the COM PORT as mentioned in PORT in device manager. (If you are using any other Arduino Board instead of UNO then select the same in boards )

Upload your killer programmes and see them work . . .

I hope this helps. . .

Welcome

Add Foreign Key relationship between two Databases

As the error message says, this is not supported on sql server. The only way to ensure refrerential integrity is to work with triggers.

Sending data through POST request from a node.js server to a node.js server

Posting data is a matter of sending a query string (just like the way you would send it with an URL after the ?) as the request body.

This requires Content-Type and Content-Length headers, so the receiving server knows how to interpret the incoming data. (*)

var querystring = require('querystring');
var http = require('http');

var data = querystring.stringify({
      username: yourUsernameValue,
      password: yourPasswordValue
    });

var options = {
    host: 'my.url',
    port: 80,
    path: '/login',
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': Buffer.byteLength(data)
    }
};

var req = http.request(options, function(res) {
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
        console.log("body: " + chunk);
    });
});

req.write(data);
req.end();

(*) Sending data requires the Content-Type header to be set correctly, i.e. application/x-www-form-urlencoded for the traditional format that a standard HTML form would use.

It's easy to send JSON (application/json) in exactly the same manner; just JSON.stringify() the data beforehand.

URL-encoded data supports one level of structure (i.e. key and value). JSON is useful when it comes to exchanging data that has a nested structure.

The bottom line is: The server must be able to interpret the content type in question. It could be text/plain or anything else; there is no need to convert data if the receiving server understands it as it is.

Add a charset parameter (e.g. application/json; charset=Windows-1252) if your data is in an unusual character set, i.e. not UTF-8. This can be necessary if you read it from a file, for example.

How to check if type of a variable is string?

You can simply use the isinstance function to make sure that the input data is of format string or unicode. Below examples will help you to understand easily.

>>> isinstance('my string', str)
True
>>> isinstance(12, str)
False
>>> isinstance('my string', unicode)
False
>>> isinstance(u'my string',  unicode)
True

What's the difference between a Future and a Promise?

According to this discussion, Promise has finally been called CompletableFuture for inclusion in Java 8, and its javadoc explains:

A Future that may be explicitly completed (setting its value and status), and may be used as a CompletionStage, supporting dependent functions and actions that trigger upon its completion.

An example is also given on the list:

f.then((s -> aStringFunction(s)).thenAsync(s -> ...);

Note that the final API is slightly different but allows similar asynchronous execution:

CompletableFuture<String> f = ...;
f.thenApply(this::modifyString).thenAccept(System.out::println);

Full width layout with twitter bootstrap

Here is an example of a 100% width, 100% height layout with Bootstrap 3.

http://bootply.com/tofficer/77686

How to send data in request body with a GET when using jQuery $.ajax()

we all know generally that for sending the data according to the http standards we generally use POST request. But if you really want to use Get for sending the data in your scenario I would suggest you to use the query-string or query-parameters.

1.GET use of Query string as. {{url}}admin/recordings/some_id

here the some_id is mendatory parameter to send and can be used and req.params.some_id at server side.

2.GET use of query string as{{url}}admin/recordings?durationExact=34&isFavourite=true

here the durationExact ,isFavourite is optional strings to send and can be used and req.query.durationExact and req.query.isFavourite at server side.

3.GET Sending arrays {{url}}admin/recordings/sessions/?os["Windows","Linux","Macintosh"]

and you can access those array values at server side like this

let osValues = JSON.parse(req.query.os);
        if(osValues.length > 0)
        {
            for (let i=0; i<osValues.length; i++)
            {
                console.log(osValues[i])
                //do whatever you want to do here
            }
        }

Change grid interval and specify tick labels in Matplotlib

There are several problems in your code.

First the big ones:

  1. You are creating a new figure and a new axes in every iteration of your loop ? put fig = plt.figure and ax = fig.add_subplot(1,1,1) outside of the loop.

  2. Don't use the Locators. Call the functions ax.set_xticks() and ax.grid() with the correct keywords.

  3. With plt.axes() you are creating a new axes again. Use ax.set_aspect('equal').

The minor things: You should not mix the MATLAB-like syntax like plt.axis() with the objective syntax. Use ax.set_xlim(a,b) and ax.set_ylim(a,b)

This should be a working minimal example:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

# Major ticks every 20, minor ticks every 5
major_ticks = np.arange(0, 101, 20)
minor_ticks = np.arange(0, 101, 5)

ax.set_xticks(major_ticks)
ax.set_xticks(minor_ticks, minor=True)
ax.set_yticks(major_ticks)
ax.set_yticks(minor_ticks, minor=True)

# And a corresponding grid
ax.grid(which='both')

# Or if you want different settings for the grids:
ax.grid(which='minor', alpha=0.2)
ax.grid(which='major', alpha=0.5)

plt.show()

Output is this:

result

Get type name without full namespace

best way to use:

typeof(T).Name

What are valid values for the id attribute in HTML?

alphabets-> caps & small
digits-> 0-9
special chars-> ':', '-', '_', '.'

the format should be either starting from '.' or an alphabet, followed by either of the special chars of more alphabets or numbers. the value of the id field must not end at an '_'.
Also, spaces are not allowed, if provided, they are treated as different values, which is not valid in case of the id attributes.

Retain precision with double in Java

Observe that you'd have the same problem if you used limited-precision decimal arithmetic, and wanted to deal with 1/3: 0.333333333 * 3 is 0.999999999, not 1.00000000.

Unfortunately, 5.6, 5.8 and 11.4 just aren't round numbers in binary, because they involve fifths. So the float representation of them isn't exact, just as 0.3333 isn't exactly 1/3.

If all the numbers you use are non-recurring decimals, and you want exact results, use BigDecimal. Or as others have said, if your values are like money in the sense that they're all a multiple of 0.01, or 0.001, or something, then multiply everything by a fixed power of 10 and use int or long (addition and subtraction are trivial: watch out for multiplication).

However, if you are happy with binary for the calculation, but you just want to print things out in a slightly friendlier format, try java.util.Formatter or String.format. In the format string specify a precision less than the full precision of a double. To 10 significant figures, say, 11.399999999999 is 11.4, so the result will be almost as accurate and more human-readable in cases where the binary result is very close to a value requiring only a few decimal places.

The precision to specify depends a bit on how much maths you've done with your numbers - in general the more you do, the more error will accumulate, but some algorithms accumulate it much faster than others (they're called "unstable" as opposed to "stable" with respect to rounding errors). If all you're doing is adding a few values, then I'd guess that dropping just one decimal place of precision will sort things out. Experiment.

Swap x and y axis without manually swapping values

Microsoft Excel for Mac 2011 v 14.5.9

  • Click on the chart
  • Press the "Switch Plot" button under the "Charts" tab

What is the 'override' keyword in C++ used for?

And as an addendum to all answers, FYI: override is not a keyword, but a special kind of identifier! It has meaning only in the context of declaring/defining virtual functions, in other contexts it's just an ordinary identifier. For details read 2.11.2 of The Standard.

#include <iostream>

struct base
{
    virtual void foo() = 0;
};

struct derived : base
{
    virtual void foo() override
    {
        std::cout << __PRETTY_FUNCTION__ << std::endl;
    }
};

int main()
{
    base* override = new derived();
    override->foo();
    return 0;
}

Output:

zaufi@gentop /work/tests $ g++ -std=c++11 -o override-test override-test.cc
zaufi@gentop /work/tests $ ./override-test
virtual void derived::foo()

How do I download a file using VBA (without Internet Explorer)

This solution is based from this website: http://social.msdn.microsoft.com/Forums/en-US/bd0ee306-7bb5-4ce4-8341-edd9475f84ad/excel-2007-use-vba-to-download-save-csv-from-url

It is slightly modified to overwrite existing file and to pass along login credentials.

Sub DownloadFile()

Dim myURL As String
myURL = "https://YourWebSite.com/?your_query_parameters"

Dim WinHttpReq As Object
Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
WinHttpReq.Open "GET", myURL, False, "username", "password"
WinHttpReq.send

If WinHttpReq.Status = 200 Then
    Set oStream = CreateObject("ADODB.Stream")
    oStream.Open
    oStream.Type = 1
    oStream.Write WinHttpReq.responseBody
    oStream.SaveToFile "C:\file.csv", 2 ' 1 = no overwrite, 2 = overwrite
    oStream.Close
End If

End Sub

What is the difference between a deep copy and a shallow copy?

I haven't seen a short, easy to understand answer here--so I'll give it a try.

With a shallow copy, any object pointed to by the source is also pointed to by the destination (so that no referenced objects are copied).

With a deep copy, any object pointed to by the source is copied and the copy is pointed to by the destination (so there will now be 2 of each referenced object). This recurses down the object tree.

Why am I getting 'Assembly '*.dll' must be strong signed in order to be marked as a prerequisite.'?

This is caused when you change the version of the .dll that is referenced. You need to delete all items, or the .dll in the target build folder.

Difference between Relative path and absolute path in javascript

Relative Paths

A relative path assumes that the file is on the current server. Using relative paths allows you to construct your site offline and fully test it before uploading it.

For example:

php/webct/itr/index.php

.

Absolute Paths

An absolute path refers to a file on the Internet using its full URL. Absolute paths tell the browser precisely where to go.

For example:

http://www.uvsc.edu/disted/php/webct/itr/index.php

Absolute paths are easier to use and understand. However, it is not good practice on your own website. For one thing, using relative paths allows you to construct your site offline and fully test it before uploading it. If you were to use absolute paths you would have to change your code before uploading it in order to get it to work. This would also be the case if you ever had to move your site or if you changed domain names.

Reference: http://openhighschoolcourses.org/mod/book/tool/print/index.php?id=12503

String delimiter in string.split method

Pipe (|) is a special character in regex. to escape it, you need to prefix it with backslash (\). But in java, backslash is also an escape character. so again you need to escape it with another backslash. So your regex should be \\|\\| e.g, String[] tokens = myString.split("\\|\\|");

JSON to TypeScript class instance?

You can now use Object.assign(target, ...sources). Following your example, you could use it like this:

class Foo {
  name: string;
  getName(): string { return this.name };
}

let fooJson: string = '{"name": "John Doe"}';
let foo: Foo = Object.assign(new Foo(), JSON.parse(fooJson));

console.log(foo.getName()); //returns John Doe

Object.assign is part of ECMAScript 2015 and is currently available in most modern browsers.

Create or write/append in text file

Try something like this:

 $txt = "user id date";
 $myfile = file_put_contents('logs.txt', $txt.PHP_EOL , FILE_APPEND | LOCK_EX);

SQL query to group by day

if you're using SQL Server,

dateadd(DAY,0, datediff(day,0, created)) will return the day created

for example, if the sale created on '2009-11-02 06:12:55.000', dateadd(DAY,0, datediff(day,0, created)) return '2009-11-02 00:00:00.000'

select sum(amount) as total, dateadd(DAY,0, datediff(day,0, created)) as created
from sales
group by dateadd(DAY,0, datediff(day,0, created))

How to set max and min value for Y axis

Writing this in 2016 while Chart js 2.3.0 is the latest one. Here is how one can change it

var options = {
    scales: {
        yAxes: [{
            display: true,
            stacked: true,
            ticks: {
                min: 0, // minimum value
                max: 10 // maximum value
            }
        }]
    }
};

Query comparing dates in SQL

Try to use "#" before and after of the date and be sure of your system date format. maybe "YYYYMMDD O YYYY-MM-DD O MM-DD-YYYY O USING '/ O \' "

Ex:

 select id,numbers_from,created_date,amount_numbers,SMS_text 
 from Test_Table
 where 
 created_date <= #2013-04-12#

time.sleep -- sleeps thread or process?

The thread will block, but the process is still alive.

In a single threaded application, this means everything is blocked while you sleep. In a multithreaded application, only the thread you explicitly 'sleep' will block and the other threads still run within the process.

Styling the last td in a table with css

For IE, how about using a CSS expression:

<style type="text/css">
table td { 
  h: expression(this.style.border = (this == this.parentNode.lastChild ? 'none' : '1px solid #000' ) );
}
</style>

What is the correct way to read a serial port using .NET framework?

I used similar code to @MethodMan but I had to keep track of the data the serial port was sending and look for a terminating character to know when the serial port was done sending data.

private string buffer { get; set; }
private SerialPort _port { get; set; }

public Port() 
{
    _port = new SerialPort();
    _port.DataReceived += new SerialDataReceivedEventHandler(dataReceived);
    buffer = string.Empty;
}

private void dataReceived(object sender, SerialDataReceivedEventArgs e)
{    
    buffer += _port.ReadExisting();

    //test for termination character in buffer
    if (buffer.Contains("\r\n"))
    {
        //run code on data received from serial port
    }
}

Node.js - SyntaxError: Unexpected token import

I'm shocked esm hasn't been mentioned. This small, but mighty package allows you to use either import or require.

Install esm in your project

$ npm install --save esm

Update your Node Start Script to use esm

node -r esm app.js

esm just works. I wasted a TON of time with .mjs and --experimental-modules only to find out a .mjs file cannot import a file that uses require or module.exports. This was a huge problem, whereas esm allows you to mix and match and it just figures it out... esm just works.

iOS 9 not opening Instagram app with URL SCHEME

Facebook sharing from a share dialog fails even with @Matthieu answer (which is 100% correct for the rest of social URLs). I had to add a set of URL i reversed from Facebook SDK.

<array>
        <string>fbapi</string>
        <string>fbauth2</string>
        <string>fbshareextension</string>
        <string>fb-messenger-api</string>
        <string>twitter</string>
        <string>whatsapp</string>
        <string>wechat</string>
        <string>line</string>
        <string>instagram</string>
        <string>kakaotalk</string>
        <string>mqq</string>
        <string>vk</string>
        <string>comgooglemaps</string>
        <string>fbapi20130214</string>                                                    
        <string>fbapi20130410</string>                                                     
        <string>fbapi20130702</string>                                                    
        <string>fbapi20131010</string>                                                    
        <string>fbapi20131219</string>                                                    
        <string>fbapi20140410</string>                                                     
        <string>fbapi20140116</string>                                                     
        <string>fbapi20150313</string>                                                     
        <string>fbapi20150629</string>
    </array>

What is the color code for transparency in CSS?

Simply choose your background color of your item and specify the opacity separatly:

div { background-color:#000; opacity:0.8; }

Git ignore file for Xcode projects

The people of GitHub have exhaustive and documented .gitignore files for Xcode projects:

Swift: https://github.com/github/gitignore/blob/master/Swift.gitignore

Objective-C: https://github.com/github/gitignore/blob/master/Objective-C.gitignore

Java Keytool error after importing certificate , "keytool error: java.io.FileNotFoundException & Access Denied"

You can store orther disk or path (not C) EX : D\

C:\Program Files\Java\jre1.8.0_101\bin>keytool -genkey -alias server -keyalg RSA -keysize 2048 -keystore D:\myserver.jks -dname "CN=myserver,OU=IT-WebDev, O=TIACHOP, L=HCM, ST=0753, C=VN" && keytool -certreq -alias server -file D:\myserver.csr -keystore D:\myserver.jks

enter image description here

Openssl is not recognized as an internal or external command

This is worked for me successfully.

"C:\Program Files\Java\jdk1.6.0_26\bin\keytool.exe" -exportcert -alias sociallisting -keystore "D:\keystore\SocialListing" | "C:\cygwin\bin\openssl.exe" sha1 -binary | "C:\cygwin\bin\openssl.exe" base64

Be careful with below path :

  • "C:\Program Files\Java\jdk1.6.0_26\bin\keytool.exe"
  • "D:\keystore\SocialListing" or it can be like this "C:\Users\Shaon.android\debug.keystore"
  • "C:\cygwin\bin\openssl.exe" or can be like this C:\Users\openssl\bin\openssl.exe

If command successfully work then you will see this command :

Enter keystore password : typeyourpassword

Encryptedhashkey**

Two HTML tables side by side, centered on the page

The problem is that the DIV that should center your tables has no width defined. By default, DIVs are block elements and take up the entire width of their parent - in this case the entire document (propagating through the #outer DIV), so the automatic margin style has no effect.

For this technique to work, you simply have to set the width of the div that has margin:auto to anything but "auto" or "inherit" (either a fixed pixel value or a percentage).

Regular Expression For Duplicate Words

The widely-used PCRE library can handle such situations (you won't achieve the the same with POSIX-compliant regex engines, though):

(\b\w+\b)\W+\1

How to clear File Input

In my case other solutions did not work than this way:

$('.bootstrap-filestyle :input').val('');

However, if you will have more than 1 file input on page, it will reset the text on all of them.

Why is semicolon allowed in this python snippet?

Semicolons can be used to one line two or more commands. They don't have to be used, but they aren't restricted.

The semicolon ( ; ) allows multiple statements on the single line given that neither statement starts a new code block.

http://www.tutorialspoint.com/python/python_basic_syntax.htm

How to select an option from drop down using Selenium WebDriver C#?

Adding a point to this- I came across a problem that OpenQA.Selenium.Support.UI namespace was not available after installing Selenium.NET binding into the C# project. Later found out that we can easily install latest version of Selenium WebDriver Support Classes by running the command:

Install-Package Selenium.Support

in NuGet Package Manager Console, or install Selenium.Support from NuGet Manager.

How can I sort a dictionary by key?

I think the easiest thing is to sort the dict by key and save the sorted key:value pair in a new dict.

dict1 = {'renault': 3, 'ford':4, 'volvo': 1, 'toyota': 2} 
dict2 = {}                  # create an empty dict to store the sorted values
for key in sorted(dict1.keys()):
    if not key in dict2:    # Depending on the goal, this line may not be neccessary
        dict2[key] = dict1[key]

To make it clearer:

dict1 = {'renault': 3, 'ford':4, 'volvo': 1, 'toyota': 2} 
dict2 = {}                  # create an empty dict to store the sorted     values
for key in sorted(dict1.keys()):
    if not key in dict2:    # Depending on the goal, this line may not be  neccessary
        value = dict1[key]
        dict2[key] = value

How to select all columns, except one column in pandas?

df[df.columns.difference(['b'])]

Out: 
          a         c         d
0  0.427809  0.459807  0.333869
1  0.678031  0.668346  0.645951
2  0.996573  0.673730  0.314911
3  0.786942  0.719665  0.330833

How to suppress scientific notation when printing float values?

If it is a string then use the built in float on it to do the conversion for instance: print( "%.5f" % float("1.43572e-03")) answer:0.00143572

Regex AND operator

It is impossible for both (?=foo) and (?=baz) to match at the same time. It would require the next character to be both f and b simultaneously which is impossible.

Perhaps you want this instead:

(?=.*foo)(?=.*baz)

This says that foo must appear anywhere and baz must appear anywhere, not necessarily in that order and possibly overlapping (although overlapping is not possible in this specific case because the letters themselves don't overlap).

Cast Object to Generic Type for returning

If you do not want to depend on throwing exception (which you probably should not) you can try this:

public static <T> T cast(Object o, Class<T> clazz) {
    return clazz.isInstance(o) ? clazz.cast(o) : null;
}

Min width in window resizing

Well, you pretty much gave yourself the answer. In your CSS give the containing element a min-width. If you have to support IE6 you can use the min-width-trick:

#container {
    min-width:800px;
    width: auto !important;
    width:800px;
}

That will effectively give you 800px min-width in IE6 and any up-to-date browsers.

How do I set the timeout for a JAX-WS webservice client?

In case your appserver is WebLogic (for me it was 10.3.6) then properties responsible for timeouts are:

com.sun.xml.ws.connect.timeout 
com.sun.xml.ws.request.timeout

Any way to write a Windows .bat file to kill processes?

I'm assuming as a developer, you have some degree of administrative control over your machine. If so, from the command line, run msconfig.exe. You can remove many processes from even starting, thereby eliminating the need to kill them with the above mentioned solutions.

How to export plots from matplotlib with transparent background?

Use the matplotlib savefig function with the keyword argument transparent=True to save the image as a png file.

In [30]: x = np.linspace(0,6,31)

In [31]: y = np.exp(-0.5*x) * np.sin(x)

In [32]: plot(x, y, 'bo-')
Out[32]: [<matplotlib.lines.Line2D at 0x3f29750>]            

In [33]: savefig('demo.png', transparent=True)

Result: demo.png

Of course, that plot doesn't demonstrate the transparency. Here's a screenshot of the PNG file displayed using the ImageMagick display command. The checkerboard pattern is the background that is visible through the transparent parts of the PNG file.

display screenshot

Why does the PHP json_encode function convert UTF-8 strings to hexadecimal entities?

Since PHP/5.4.0, there is an option called JSON_UNESCAPED_UNICODE. Check it out:

https://php.net/function.json-encode

Therefore you should try:

json_encode( $text, JSON_UNESCAPED_UNICODE );

How to return values in javascript

The return statement stops the execution of a function and returns a value from that function.

While updating global variables is one way to pass information back to the code that called the function, this is not an ideal way of doing so. A much better alternative is to write the function so that values that are used by the function are passed to it as parameters and the function returns whatever value that it needs to without using or updating any global variables.

By limiting the way in which information is passed to and from functions we can make it easier to reuse the same function from multiple places in our code.

JavaScript provides for passing one value back to the code that called it after everything in the function that needs to run has finished running.

JavaScript passes a value from a function back to the code that called it by using the return statement. The value to be returned is specified in the return keyword.

How to increase application heap size in Eclipse?

Find the Run button present on the top of the Eclipse, then select Run Configuration -> Arguments, in VM arguments section just mention the heap size you want to extend as below:

-Xmx1024m

What is the list of valid @SuppressWarnings warning names in Java?

The list is compiler specific. But here are the values supported in Eclipse:

  • allDeprecation deprecation even inside deprecated code
  • allJavadoc invalid or missing javadoc
  • assertIdentifier occurrence of assert used as identifier
  • boxing autoboxing conversion
  • charConcat when a char array is used in a string concatenation without being converted explicitly to a string
  • conditionAssign possible accidental boolean assignment
  • constructorName method with constructor name
  • dep-ann missing @Deprecated annotation
  • deprecation usage of deprecated type or member outside deprecated code
  • discouraged use of types matching a discouraged access rule
  • emptyBlock undocumented empty block
  • enumSwitch, incomplete-switch incomplete enum switch
  • fallthrough possible fall-through case
  • fieldHiding field hiding another variable
  • finalBound type parameter with final bound
  • finally finally block not completing normally
  • forbidden use of types matching a forbidden access rule
  • hiding macro for fieldHiding, localHiding, typeHiding and maskedCatchBlock
  • indirectStatic indirect reference to static member
  • intfAnnotation annotation type used as super interface
  • intfNonInherited interface non-inherited method compatibility
  • javadoc invalid javadoc
  • localHiding local variable hiding another variable
  • maskedCatchBlocks hidden catch block
  • nls non-nls string literals (lacking of tags //$NON-NLS-)
  • noEffectAssign assignment with no effect
  • null potential missing or redundant null check
  • nullDereference missing null check
  • over-ann missing @Override annotation
  • paramAssign assignment to a parameter
  • pkgDefaultMethod attempt to override package-default method
  • raw usage a of raw type (instead of a parametrized type)
  • semicolon unnecessary semicolon or empty statement
  • serial missing serialVersionUID
  • specialParamHiding constructor or setter parameter hiding another field
  • static-access macro for indirectStatic and staticReceiver
  • staticReceiver if a non static receiver is used to get a static field or call a static method
  • super overriding a method without making a super invocation
  • suppress enable @SuppressWarnings
  • syntheticAccess, synthetic-access when performing synthetic access for innerclass
  • tasks enable support for tasks tags in source code
  • typeHiding type parameter hiding another type
  • unchecked unchecked type operation
  • unnecessaryElse unnecessary else clause
  • unqualified-field-access, unqualifiedField unqualified reference to field
  • unused macro for unusedArgument, unusedImport, unusedLabel, unusedLocal, unusedPrivate and unusedThrown
  • unusedArgument unused method argument
  • unusedImport unused import reference
  • unusedLabel unused label
  • unusedLocal unused local variable
  • unusedPrivate unused private member declaration
  • unusedThrown unused declared thrown exception
  • uselessTypeCheck unnecessary cast/instanceof operation
  • varargsCast varargs argument need explicit cast
  • warningToken unhandled warning token in @SuppressWarnings

Sun JDK (1.6) has a shorter list of supported warnings:

  • deprecation Check for use of depreciated items.
  • unchecked Give more detail for unchecked conversion warnings that are mandated by the Java Language Specification.
  • serial Warn about missing serialVersionUID definitions on serializable classes.
  • finally Warn about finally clauses that cannot complete normally.
  • fallthrough Check switch blocks for fall-through cases and provide a warning message for any that are found.
  • path Check for a nonexistent path in environment paths (such as classpath).

The latest available javac (1.6.0_13) for mac have the following supported warnings

  • all
  • cast
  • deprecation
  • divzero
  • empty
  • unchecked
  • fallthrough
  • path
  • serial
  • finally
  • overrides

Copying a HashMap in Java

Since the OP has mentioned he does not have access to the base class inside of which exists a HashMap - I am afraid there are very few options available.

One (painfully slow and resource intensive) way of performing a deep copy of an object in Java is to abuse the 'Serializable' interface which many classes either intentionally - or unintentionally extend - and then utilise this to serialise your class to ByteStream. Upon de-serialisation you will have a deep copy of the object in question.

A guide for this can be found here: https://www.avajava.com/tutorials/lessons/how-do-i-perform-a-deep-clone-using-serializable.html

Python: Open file in zip without temporarily extracting it

In theory, yes, it's just a matter of plugging things in. Zipfile can give you a file-like object for a file in a zip archive, and image.load will accept a file-like object. So something like this should work:

import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgfile = archive.open('img_01.png')
try:
    image = pygame.image.load(imgfile, 'img_01.png')
finally:
    imgfile.close()

how to convert milliseconds to date format in android?

Coverting epoch format to SimpleDateFormat in Android (Java / Kotlin)

input: 1613316655000

output: 2021-02-14T15:30:55.726Z

In Java

long milliseconds = 1613316655000L;
Date date = new Date(milliseconds);
String mobileDateTime = Utils.getFormatTimeWithTZ(date);

//method that returns SimpleDateFormat in String

public static String getFormatTimeWithTZ(Date currentTime) {
    SimpleDateFormat timeZoneDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault());
    return timeZoneString = timeZoneDate.format(currentTime);
}

In Kotlin

var milliseconds = 1613316655000L
var date = Date(milliseconds)
var mobileDateTime = Utils.getFormatTimeWithTZ(date)

//method that returns SimpleDateFormat in String

fun getFormatTimeWithTZ(currentTime:Date):String {
  val timeZoneDate = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault())
  return timeZoneString = timeZoneDate.format(currentTime)
}

Finding the max value of an attribute in an array of objects

I'd like to explain the terse accepted answer step-by-step:

_x000D_
_x000D_
var objects = [{ x: 3 }, { x: 1 }, { x: 2 }];_x000D_
_x000D_
// array.map lets you extract an array of attribute values_x000D_
var xValues = objects.map(function(o) { return o.x; });_x000D_
// es6_x000D_
xValues = Array.from(objects, o => o.x);_x000D_
_x000D_
// function.apply lets you expand an array argument as individual arguments_x000D_
// So the following is equivalent to Math.max(3, 1, 2)_x000D_
// The first argument is "this" but since Math.max doesn't need it, null is fine_x000D_
var xMax = Math.max.apply(null, xValues);_x000D_
// es6_x000D_
xMax = Math.max(...xValues);_x000D_
_x000D_
// Finally, to find the object that has the maximum x value (note that result is array):_x000D_
var maxXObjects = objects.filter(function(o) { return o.x === xMax; });_x000D_
_x000D_
// Altogether_x000D_
xMax = Math.max.apply(null, objects.map(function(o) { return o.x; }));_x000D_
var maxXObject = objects.filter(function(o) { return o.x === xMax; })[0];_x000D_
// es6_x000D_
xMax = Math.max(...Array.from(objects, o => o.x));_x000D_
maxXObject = objects.find(o => o.x === xMax);_x000D_
_x000D_
_x000D_
document.write('<p>objects: ' + JSON.stringify(objects) + '</p>');_x000D_
document.write('<p>xValues: ' + JSON.stringify(xValues) + '</p>');_x000D_
document.write('<p>xMax: ' + JSON.stringify(xMax) + '</p>');_x000D_
document.write('<p>maxXObjects: ' + JSON.stringify(maxXObjects) + '</p>');_x000D_
document.write('<p>maxXObject: ' + JSON.stringify(maxXObject) + '</p>');
_x000D_
_x000D_
_x000D_

Further information:

How to color System.out.println output?

No, but there are third party API's that can handle it

http://www.javaworld.com/javaworld/javaqa/2002-12/02-qa-1220-console.html

Edit: of course there are newer articles than that one I posted, the information is still viable though.

If input value is blank, assign a value of "empty" with Javascript

I think the easiest way to solve this issue, if you only need it on 1 or 2 boxes is by using the HTML input's "onsubmit" function.

Check this out and i will explain what it does:

<input type="text" name="val" onsubmit="if(this == ''){$this.val('empty');}" />

So we have created the HTML text box, assigned it a name ("val" in this case) and then we added the onsubmit code, this code checks to see if the current input box is empty and if it is, then, upon form submit it will fill it with the words empty.

Please note, this code should also function perfectly when using the HTML "Placeholder" tag as the placeholder tag doesn't actually assign a value to the input box.

Add my custom http header to Spring RestTemplate request / extend RestTemplate

If the goal is to have a reusable RestTemplate which is in general useful for attaching the same header to a series of similar request a org.springframework.boot.web.client.RestTemplateCustomizer parameter can be used with a RestTemplateBuilder:

 String accessToken= "<the oauth 2 token>";
 RestTemplate restTemplate = new RestTemplateBuilder(rt-> rt.getInterceptors().add((request, body, execution) -> {
        request.getHeaders().add("Authorization", "Bearer "+accessToken);
        return execution.execute(request, body);
    })).build();

How to remove the first and the last character of a string

It may be nicer one to use slice like :

string.slice(1, -1)

Remove duplicate values from JS array

$(document).ready(function() {

    var arr1=["dog","dog","fish","cat","cat","fish","apple","orange"]

    var arr2=["cat","fish","mango","apple"]

    var uniquevalue=[];
    var seconduniquevalue=[];
    var finalarray=[];

    $.each(arr1,function(key,value){

       if($.inArray (value,uniquevalue) === -1)
       {
           uniquevalue.push(value)

       }

    });

     $.each(arr2,function(key,value){

       if($.inArray (value,seconduniquevalue) === -1)
       {
           seconduniquevalue.push(value)

       }

    });

    $.each(uniquevalue,function(ikey,ivalue){

        $.each(seconduniquevalue,function(ukey,uvalue){

            if( ivalue == uvalue)

            {
                finalarray.push(ivalue);
            }   

        });

    });
    alert(finalarray);
});

Switch android x86 screen resolution

OK, maybe there are more like me that do not have any UVESA_MODE or S3 references in their menu.lst. First, do "VBoxManage setextradata "VM_NAME_HERE" "CustomVideoMode1" "320x480x32"" procedure through terminal. My custom videomode was "1920x1089x32"... (sorry, I use Linux, so procedure works on linux) for Windows, just add .exe to VBoxManage.. Look in the first entry as described before, this is the menu entry you would normally boot. I normally use nano as it works more easy for me. And nano happens to be present in Android >6 too. (other version not tried)

Procedure:

  • Boot VM, chose the "debug mode" option to boot. Pressing "enter" after a while will result in the prompt
  • Change directory to /mnt/grub "cd /mnt/grub"
  • list directory content with "ls" (not necessary but I like to see where I am)
  • copy menu.lst (make this standard procedure before changing anything) "cp menu.lst menu.lst.bak" (or whatever extension you like to use for backup)
  • open menu.lst, e.g.: "nano menu.lst".
  • look in first menu entry (normally there are 4, starting with the titles you see in the boot menu) the "kernel" entry, which ends with the word "quiet"
  • replace "quiet" with something like "vga=ask" if you would like to be asked every time at boot for the screen resolution, or "vga=(HEX value)" as seen in surlac's anwer.
  • exit and save, don't forget to actually save it! double check this. (ctrl+X, YES, Enter for nano)
  • reboot VM with "YOUR HOST KEY" + "R" (normally "right control" + "R")

Hope this helps anyone as it did solve my problem.

edit: I see that I did place this article in the wrong place, since the original question is about another Android version. Does anyone know how to move it to an appropriate location?

AngularJS For Loop with Numbers & Ranges

For those new to angularjs. The index can be gotten by using $index.

For example:

<div ng-repeat="n in [] | range:10">
    do something number {{$index}}
</div>

Which will, when you're using Gloopy's handy filter, print:
do something number 0
do something number 1
do something number 2
do something number 3
do something number 4
do something number 5
do something number 6
do something number 7
do something number 8
do something number 9