Programs & Examples On #Persist

PersistentObjectException: detached entity passed to persist thrown by JPA and Hibernate

In your entity definition, you're not specifying the @JoinColumn for the Account joined to a Transaction. You'll want something like this:

@Entity
public class Transaction {
    @ManyToOne(cascade = {CascadeType.ALL},fetch= FetchType.EAGER)
    @JoinColumn(name = "accountId", referencedColumnName = "id")
    private Account fromAccount;
}

EDIT: Well, I guess that would be useful if you were using the @Table annotation on your class. Heh. :)

JPA EntityManager: Why use persist() over merge()?

Another observation:

merge() will only care about an auto-generated id(tested on IDENTITY and SEQUENCE) when a record with such an id already exists in your table. In that case merge() will try to update the record. If, however, an id is absent or is not matching any existing records, merge() will completely ignore it and ask a db to allocate a new one. This is sometimes a source of a lot of bugs. Do not use merge() to force an id for a new record.

persist() on the other hand will never let you even pass an id to it. It will fail immediately. In my case, it's:

Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist

hibernate-jpa javadoc has a hint:

Throws: javax.persistence.EntityExistsException - if the entity already exists. (If the entity already exists, the EntityExistsException may be thrown when the persist operation is invoked, or the EntityExistsException or another PersistenceException may be thrown at flush or commit time.)

String to object in JS

Your string looks like a JSON string without the curly braces.

This should work then:

obj = eval('({' + str + '})');

String comparison in Python: is vs. ==

The logic is not flawed. The statement

if x is y then x==y is also True

should never be read to mean

if x==y then x is y

It is a logical error on the part of the reader to assume that the converse of a logic statement is true. See http://en.wikipedia.org/wiki/Converse_(logic)

Importing two classes with same name. How to handle?

This scenario is not so common in real-world programming, but not so strange too. It happens sometimes that two classes in different packages have same name and we need both of them.

It is not mandatory that if two classes have same name, then both will contain same functionalities and we should pick only one of them.

If we need both, then there is no harm in using that. And it's not a bad programming idea too.

But we should use fully qualified names of the classes (that have same name) in order to make it clear which class we are referring too.

:)

Android EditText Hint

et.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {

            et.setHint(temp +" Characters");
        }
    });

Row count with PDO

When it is matter of mysql how to count or get how many rows in a table with PHP PDO I use this

// count total number of rows
$query = "SELECT COUNT(*) as total_rows FROM sometable";
$stmt = $con->prepare($query);

// execute query
$stmt->execute();

// get total rows
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$total_rows = $row['total_rows'];

credits goes to Mike @ codeofaninja.com

C++ convert hex string to signed integer

Try this. This solution is a bit risky. There are no checks. The string must only have hex values and the string length must match the return type size. But no need for extra headers.

char hextob(char ch)
{
    if (ch >= '0' && ch <= '9') return ch - '0';
    if (ch >= 'A' && ch <= 'F') return ch - 'A' + 10;
    if (ch >= 'a' && ch <= 'f') return ch - 'a' + 10;
    return 0;
}
template<typename T>
T hextot(char* hex)
{
    T value = 0;
    for (size_t i = 0; i < sizeof(T)*2; ++i)
        value |= hextob(hex[i]) << (8*sizeof(T)-4*(i+1));
    return value;
};

Usage:

int main()
{
    char str[4] = {'f','f','f','f'};
    std::cout << hextot<int16_t>(str)  << "\n";
}

Note: the length of the string must be divisible by 2

Installing a dependency with Bower from URL and specify version

I believe that specifying version works only for git-endpoints. And not for folder/zip ones. As when you point bower to a js-file/folder/zip you already specified package and version (except for js indeed). Because a package has bower.json with version in it. Specifying a version in 'bower install' makes sense when you're pointing bower to a repository which can have many versions of a package. It can be only git I think.

VB.Net .Clear() or txtbox.Text = "" textbox clear methods

Clear() set the Text property to nothing. So txtbox1.Text = Nothing does the same thing as clear. An empty string (also available through String.Empty) is not a null reference, but has no value of course.

IDEA: javac: source release 1.7 requires target release 1.7

IntelliJ 15, 2016 & 2017

Similar to that discussed below for IntelliJ 13 & 14, but with an extra level in the Settings/Preferences panel: Settings > Build, Execution, Deployment > Compiler > Java Compiler.

enter image description here

IntelliJ 13 & 14

In IntelliJ 13 and 14, check the Settings > Compiler > Java Compiler UI to ensure you're not targeting a different bytecode version in your module.

enter image description here

How to create an empty R vector to add new items

I pre-allocate a vector with

> (a <- rep(NA, 10))
 [1] NA NA NA NA NA NA NA NA NA NA

You can then use [] to insert values into it.

How to pass a type as a method parameter in Java

If you want to pass the type, than the equivalent in Java would be

java.lang.Class

If you want to use a weakly typed method, then you would simply use

java.lang.Object

and the corresponding operator

instanceof

e.g.

private void foo(Object o) {

  if(o instanceof String) {

  }

}//foo

However, in Java there are primitive types, which are not classes (i.e. int from your example), so you need to be careful.

The real question is what you actually want to achieve here, otherwise it is difficult to answer:

Or is there a better way?

Make more than one chart in same IPython Notebook cell

You can also call the show() function after each plot. e.g

   plt.plot(a)
   plt.show()
   plt.plot(b)
   plt.show()

Angular 5 ngHide ngShow [hidden] not working

Try this:

<button (click)="click()">Click me</button>

<input class="txt" type="password" [(ngModel)]="input_pw" [ngClass]="{'hidden': isHidden}" />

component.ts:

isHidden: boolean = false;
click(){
    this.isHidden = !this.isHidden;
}

How to sanity check a date in Java

You can use SimpleDateFormat

For example something like:

boolean isLegalDate(String s) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    sdf.setLenient(false);
    return sdf.parse(s, new ParsePosition(0)) != null;
}

Converting a Pandas GroupBy output from Series to DataFrame

g1 here is a DataFrame. It has a hierarchical index, though:

In [19]: type(g1)
Out[19]: pandas.core.frame.DataFrame

In [20]: g1.index
Out[20]: 
MultiIndex([('Alice', 'Seattle'), ('Bob', 'Seattle'), ('Mallory', 'Portland'),
       ('Mallory', 'Seattle')], dtype=object)

Perhaps you want something like this?

In [21]: g1.add_suffix('_Count').reset_index()
Out[21]: 
      Name      City  City_Count  Name_Count
0    Alice   Seattle           1           1
1      Bob   Seattle           2           2
2  Mallory  Portland           2           2
3  Mallory   Seattle           1           1

Or something like:

In [36]: DataFrame({'count' : df1.groupby( [ "Name", "City"] ).size()}).reset_index()
Out[36]: 
      Name      City  count
0    Alice   Seattle      1
1      Bob   Seattle      2
2  Mallory  Portland      2
3  Mallory   Seattle      1

Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?'

Installing mysqlclient using anaconda is pretty simple and straight forward.

conda install -c bioconda mysqlclient

and then, install pymysql using pip.

pip install pymysql

happy learning..

A cycle was detected in the build path of project xxx - Build Path Problem

Eclipse had a bug which reported more cycles than necessary. This has been fixed with the 2019-12 release. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=551105

How can you debug a CORS request with cURL?

Here's how you can debug CORS requests using curl.

Sending a regular CORS request using cUrl:

curl -H "Origin: http://example.com" --verbose \
  https://www.googleapis.com/discovery/v1/apis?fields=

The -H "Origin: http://example.com" flag is the third party domain making the request. Substitute in whatever your domain is.

The --verbose flag prints out the entire response so you can see the request and response headers.

The url I'm using above is a sample request to a Google API that supports CORS, but you can substitute in whatever url you are testing.

The response should include the Access-Control-Allow-Origin header.

Sending a preflight request using cUrl:

curl -H "Origin: http://example.com" \
  -H "Access-Control-Request-Method: POST" \
  -H "Access-Control-Request-Headers: X-Requested-With" \
  -X OPTIONS --verbose \
  https://www.googleapis.com/discovery/v1/apis?fields=

This looks similar to the regular CORS request with a few additions:

The -H flags send additional preflight request headers to the server

The -X OPTIONS flag indicates that this is an HTTP OPTIONS request.

If the preflight request is successful, the response should include the Access-Control-Allow-Origin, Access-Control-Allow-Methods, and Access-Control-Allow-Headers response headers. If the preflight request was not successful, these headers shouldn't appear, or the HTTP response won't be 200.

You can also specify additional headers, such as User-Agent, by using the -H flag.

Swift add icon/image in UITextField

UITextField with image (left or right)

Another way, inspired from previous posts to make an extension.

We can put the image on the right or on the left

extension UITextField {

enum Direction {
    case Left
    case Right
}

// add image to textfield
func withImage(direction: Direction, image: UIImage, colorSeparator: UIColor, colorBorder: UIColor){
    let mainView = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 45))
    mainView.layer.cornerRadius = 5

    let view = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 45))
    view.backgroundColor = .white
    view.clipsToBounds = true
    view.layer.cornerRadius = 5
    view.layer.borderWidth = CGFloat(0.5)
    view.layer.borderColor = colorBorder.cgColor
    mainView.addSubview(view)

    let imageView = UIImageView(image: image)
    imageView.contentMode = .scaleAspectFit
    imageView.frame = CGRect(x: 12.0, y: 10.0, width: 24.0, height: 24.0)
    view.addSubview(imageView)

    let seperatorView = UIView()
    seperatorView.backgroundColor = colorSeparator
    mainView.addSubview(seperatorView)

    if(Direction.Left == direction){ // image left
        seperatorView.frame = CGRect(x: 45, y: 0, width: 5, height: 45)
        self.leftViewMode = .always
        self.leftView = mainView
    } else { // image right
        seperatorView.frame = CGRect(x: 0, y: 0, width: 5, height: 45)
        self.rightViewMode = .always
        self.rightView = mainView
    }

    self.layer.borderColor = colorBorder.cgColor
    self.layer.borderWidth = CGFloat(0.5)
    self.layer.cornerRadius = 5
}

}

Use :

if let myImage = UIImage(named: "my_image"){
    textfield.withImage(direction: .Left, image: myImage, colorSeparator: UIColor.orange, colorBorder: UIColor.black)
}

Enjoy :)

number of values in a list greater than a certain number

You can do like this using function:

l = [34,56,78,2,3,5,6,8,45,6]  
print ("The list : " + str(l))   
def count_greater30(l):  
    count = 0  
    for i in l:  
        if i > 30:  
            count = count + 1.  
    return count
print("Count greater than 30 is : " + str(count)).  
count_greater30(l)

Convert Pandas DataFrame to JSON format

To transform a dataFrame in a real json (not a string) I use:

    from io import StringIO
    import json
    import DataFrame

    buff=StringIO()
    #df is your DataFrame
    df.to_json(path_or_buf=buff,orient='records')
    dfJson=json.loads(buff)

Jmeter - get current date and time

Use __time function:

  • ${__time(dd/MM/yyyy,)}

  • ${__time(hh:mm a,)}

Since JMeter 3.3, there are two new functions that let you compute a time:

__timeShift

  "The timeShift function returns a date in the given format with the specified amount of seconds, minutes, hours, days or months added" and 

__RandomDate

  "The RandomDate function returns a random date that lies between the given start date and end date values." 

Since JMeter 4.0:

dateTimeConvert

Convert a date or time from source to target format

If you're looking to learn jmeter correctly, this book will help you.

How to delete multiple pandas (python) dataframes from memory to save RAM?

del statement does not delete an instance, it merely deletes a name.

When you do del i, you are deleting just the name i - but the instance is still bound to some other name, so it won't be Garbage-Collected.

If you want to release memory, your dataframes has to be Garbage-Collected, i.e. delete all references to them.

If you created your dateframes dynamically to list, then removing that list will trigger Garbage Collection.

>>> lst = [pd.DataFrame(), pd.DataFrame(), pd.DataFrame()]
>>> del lst     # memory is released

If you created some variables, you have to delete them all.

>>> a, b, c = pd.DataFrame(), pd.DataFrame(), pd.DataFrame()
>>> lst = [a, b, c]
>>> del a, b, c # dfs still in list
>>> del lst     # memory release now

How to convert string representation of list to a list?

If you know that your lists only contain quoted strings, this pyparsing example will give you your list of stripped strings (even preserving the original Unicode-ness).

>>> from pyparsing import *
>>> x =u'[ "A","B","C" , " D"]'
>>> LBR,RBR = map(Suppress,"[]")
>>> qs = quotedString.setParseAction(removeQuotes, lambda t: t[0].strip())
>>> qsList = LBR + delimitedList(qs) + RBR
>>> print qsList.parseString(x).asList()
[u'A', u'B', u'C', u'D']

If your lists can have more datatypes, or even contain lists within lists, then you will need a more complete grammar - like this one on the pyparsing wiki, which will handle tuples, lists, ints, floats, and quoted strings. Will work with Python versions back to 2.4.

Dynamically add event listener

I will add a StackBlitz example and a comment to the answer from @tahiche.

The return value is a function to remove the event listener after you have added it. It is considered good practice to remove event listeners when you don't need them anymore. So you can store this return value and call it inside your ngOnDestroy method.

I admit that it might seem confusing at first, but it is actually a very useful feature. How else can you clean up after yourself?

export class MyComponent implements OnInit, OnDestroy {

  public removeEventListener: () => void;

  constructor(
    private renderer: Renderer2, 
    private elementRef: ElementRef
  ) {
  }

  public ngOnInit() {
    this.removeEventListener = this.renderer.listen(this.elementRef.nativeElement, 'click', (event) => {
      if (event.target instanceof HTMLAnchorElement) {
        // Prevent opening anchors the default way
        event.preventDefault();
        // Your custom anchor click event handler
        this.handleAnchorClick(event);
      }
    });
  }

  public ngOnDestroy() {
    this.removeEventListener();
  }
}

You can find a StackBlitz here to show how this could work for catching clicking on anchor elements.

I added a body with an image as follows:
<img src="x" onerror="alert(1)"></div>
to show that the sanitizer is doing its job.

Here in this fiddle you find the same body attached to an innerHTML without sanitizing it and it will demonstrate the issue.

Display image at 50% of its "native" size

The zoom property sounds as though it's perfect for Adam Ernst as it suits his target device. However, for those who need a solution to this and have to support as many devices as possible you can do the following:

<img src="..." onload="this.width/=2;this.onload=null;" />

The reason for the this.onload=null addition is to avoid older browsers that sometimes trigger the load event twice (which means you can end up with quater-sized images). If you aren't worried about that though you could write:

<img src="..." onload="this.width/=2;" />

Which is quite succinct.

Django download a file

You can add "download" attribute inside your tag to download files.

<a  href="/project/download" download> Download Document </a>

https://www.w3schools.com/tags/att_a_download.asp

With form validation: why onsubmit="return functionname()" instead of onsubmit="functionname()"?

Returning false from the function will stop the event continuing. I.e. it will stop the form submitting.

i.e.

function someFunction()
{
    if (allow) // For example, checking that a field isn't empty
    {
       return true; // Allow the form to submit
    }
    else
    {
       return false; // Stop the form submitting
    }
}

How is using "<%=request.getContextPath()%>" better than "../"

request.getContextPath()- returns root path of your application, while ../ - returns parent directory of a file.

You use request.getContextPath(), as it will always points to root of your application. If you were to move your jsp file from one directory to another, nothing needs to be changed. Now, consider the second approach. If you were to move your jsp files from one folder to another, you'd have to make changes at every location where you are referring your files.

Also, better approach of using request.getContextPath() will be to set 'request.getContextPath()' in a variable and use that variable for referring your path.

<c:set var="context" value="${pageContext.request.contextPath}" />
<script src="${context}/themes/js/jquery.js"></script>

PS- This is the one reason I can figure out. Don't know if there is any more significance to it.

How to swap String characters in Java?

//this is a very basic way of how to order a string alpha-wise, this does not use anything fancy and is great for school use

package string_sorter;

public class String_Sorter {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        String word = "jihgfedcba";
        for (int endOfString = word.length(); endOfString > 0; endOfString--) {

            int largestWord = word.charAt(0);
            int location = 0;
            for (int index = 0; index < endOfString; index++) {

                if (word.charAt(index) > largestWord) {

                    largestWord = word.charAt(index);
                    location = index;
                }
            }

            if (location < endOfString - 1) {

                String newString = word.substring(0, location) + word.charAt(endOfString - 1) + word.substring(location + 1, endOfString - 1) + word.charAt(location);
                word = newString;
            }
            System.out.println(word);
        }

        System.out.println(word);
    }

}

Confusing "duplicate identifier" Typescript error message

It can be because of having both typing and dependency in your node folder. so first check what you have in your @types folder and if you have them in dependencies, remove the duplicate. for me it was core.js

How to make an AJAX call without jQuery?

<html>
  <script>
    var xmlDoc = null ;

  function load() {
    if (typeof window.ActiveXObject != 'undefined' ) {
      xmlDoc = new ActiveXObject("Microsoft.XMLHTTP");
      xmlDoc.onreadystatechange = process ;
    }
    else {
      xmlDoc = new XMLHttpRequest();
      xmlDoc.onload = process ;
    }
    xmlDoc.open( "GET", "background.html", true );
    xmlDoc.send( null );
  }

  function process() {
    if ( xmlDoc.readyState != 4 ) return ;
    document.getElementById("output").value = xmlDoc.responseText ;
  }

  function empty() {
    document.getElementById("output").value = '<empty>' ;
  }
</script>

<body>
  <textarea id="output" cols='70' rows='40'><empty></textarea>
  <br></br>
  <button onclick="load()">Load</button> &nbsp;
  <button onclick="empty()">Clear</button>
</body>
</html>

Using {% url ??? %} in django templates

Instead of importing the logout_view function, you should provide a string in your urls.py file:

So not (r'^login/', login_view),

but (r'^login/', 'login.views.login_view'),

That is the standard way of doing things. Then you can access the URL in your templates using:

{% url login.views.login_view %}

Error when checking Java version: could not find java.dll

Reinstall JDK and set system variable JAVA_HOME on your JDK. (e.g. C:\tools\jdk7)
And add JAVA_HOME variable to your PATH system variable

Type in command line

echo %JAVA_HOME%

and

java -version

To verify whether your installation was done successfully.


This problem generally occurs in Windows when your "Java Runtime Environment" registry entry is missing or mismatched with the installed JDK. The mismatch can be due to multiple JDKs.

Steps to resolve:

  1. Open the Run window:

    Press windows+R

  2. Open registry window:

    Type regedit and enter.

  3. Go to: \HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\

  4. If Java Runtime Environment is not present inside JavaSoft, then create a new Key and give the name Java Runtime Environment.

  5. For Java Runtime Environment create "CurrentVersion" String Key and give appropriate version as value:

JRE regedit entry

  1. Create a new subkey of 1.8.

  2. For 1.8 create a String Key with name JavaHome with the value of JRE home:

    JRE regedit entry 2

Ref: https://mybindirectory.blogspot.com/2019/05/error-could-not-find-javadll.html

OS X cp command in Terminal - No such file or directory

In my case, I had accidentally named a folder 'samples '. I couldn't see the space when I did 'ls -la'.

Eventually I realized this when I tried tabbing to autocomplete and saw 'samples\ /'.

To fix this I ran

mv samples\  samples

How can I share Jupyter notebooks with non-programmers?

Google has recently made public its internal Collaboratory project (link here). You can start a notebook in the same way as starting a Google Sheet or Google Doc, and then simply share the notebook or add collaborators..

For now, this is the easiest way for me.

JQuery Find #ID, RemoveClass and AddClass

Try this

$('#testID').addClass('nameOfClass');

or

$('#testID').removeClass('nameOfClass');

Undefined index error PHP

Hey this is happening because u r trying to display value before assignnig it U just fill in the values and submit form it will display correct output Or u can write ur php code below form tags It ll run without any errors

dropping infinite values from dataframes in pandas?

The above solution will modify the infs that are not in the target columns. To remedy that,

lst = [np.inf, -np.inf]
to_replace = {v: lst for v in ['col1', 'col2']}
df.replace(to_replace, np.nan)

Conditional formatting using AND() function

I had a similar problem with a less complicated formula:

= If (x > A & x <= B) 

and found that I could Remove the AND and join the two comparisons with +

  = (x > A1) + (x <= B1)        [without all the spaces]

Hope this helps others with less complex comparisons.

Display array values in PHP

Iterate over the array and do whatever you want with the individual values.

foreach ($array as $key => $value) {
    echo $key . ' contains ' . $value . '<br/>';
}

Merge up to a specific commit

Recently we had a similar problem and had to solve it in a different way. We had to merge two branches up to two commits, which were not the heads of either branches:

branch A: A1 -> A2 -> A3 -> A4
branch B: B1 -> B2 -> B3 -> B4
branch C: C1 -> A2 -> B3 -> C2

For example, we had to merge branch A up to A2 and branch B up to B3. But branch C had cherry-picks from A and B. When using the SHA of A2 and B3 it looked like there was confusion because of the local branch C which had the same SHA.

To avoid any kind of ambiguity we removed branch C locally, and then created a branch AA starting from commit A2:

git co A
git co SHA-of-A2
git co -b AA

Then we created a branch BB from commit B3:

git co B
git co SHA-of-B3
git co -b BB

At that point we merged the two branches AA and BB. By removing branch C and then referencing the branches instead of the commits it worked.

It's not clear to me how much of this was superstition or what actually made it work, but this "long approach" may be helpful.

Disable Chrome strict MIME type checking

For Windows Users :

If this issue occurs on your self hosted server (eg: your custom CDN) and the browser (Chrome) says something like ... ('text/plain') is not executable ... when trying to load your javascript file ...

Here is what you need to do :

  1. Open the Registry Editor i.e Win + R > regedit
  2. Head over to HKEY_LOCAL_MACHINE\SOFTWARE\Classes\.js
  3. Check to if the Content Type is application/javascript or not
  4. If not, then change it to application/javascript and try again

How to Apply global font to whole HTML document

You should never use * + !important. What if you want to change font in some parts your HTML document? You should always use body without important. Use !important only if there is no other option.

"Server Tomcat v7.0 Server at localhost failed to start" without stack trace while it works in terminal

After trying all above mentioned steps , issue was not resolved.

Finally it resolved with below steps.

1- Check .log file inside your work space directory. Issue with Java Version

"Caused by: java.io.IOException: Cannot run program "C:\jdk1.7.0_45\bin\java": CreateProcess error=193, %1 is not a valid Win32 application at java.lang.ProcessBuilder.start(Unknown Source) at java.lang.Runtime.exec(Unknown Source) at java.lang.Runtime.exec(Unknown Source) at org.eclipse.debug.core.DebugPlugin.exec(DebugPlugin.java:869) ... 80 more

Caused by: java.io.IOException: CreateProcess error=193, %1 is not a valid Win32 application at java.lang.ProcessImpl.create(Native Method) at java.lang.ProcessImpl.(Unknown Source) at java.lang.ProcessImpl.start(Unknown Source)"

I have installed correct OS compatible JDK and issue was resolved. PS: I have explicitly set JDK path through eclipse (Window->preference->installed JRE )but after setting correct JDK path ,it work fine for me.

multiprocessing.Pool: When to use apply, apply_async or map?

Regarding apply vs map:

pool.apply(f, args): f is only executed in ONE of the workers of the pool. So ONE of the processes in the pool will run f(args).

pool.map(f, iterable): This method chops the iterable into a number of chunks which it submits to the process pool as separate tasks. So you take advantage of all the processes in the pool.

How do I format axis number format to thousands with a comma in matplotlib?

You can use matplotlib.ticker.funcformatter

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as tkr


def func(x, pos):  # formatter function takes tick label and tick position
    s = '%d' % x
    groups = []
    while s and s[-1].isdigit():
        groups.append(s[-3:])
        s = s[:-3]
    return s + ','.join(reversed(groups))

y_format = tkr.FuncFormatter(func)  # make formatter

x = np.linspace(0,10,501)
y = 1000000*np.sin(x)
ax = plt.subplot(111)
ax.plot(x,y)
ax.yaxis.set_major_formatter(y_format)  # set formatter to needed axis

plt.show()

enter image description here

How to put a jpg or png image into a button in HTML

This may work for you, try it and see if it works:

<input type="image" src="/library/graphics/cecb2.gif">

Add MIME mapping in web.config for IIS Express

I was having a problem getting my ASP.NET 5.0/MVC 6 app to serve static binary file types or browse virtual directories. It looks like this is now done in Configure() at startup. See http://docs.asp.net/en/latest/fundamentals/static-files.html for a quick primer.

Extract time from moment js object

You can do something like this

var now = moment();
var time = now.hour() + ':' + now.minutes() + ':' + now.seconds();
time = time + ((now.hour()) >= 12 ? ' PM' : ' AM');

Aliases in Windows command prompt

Also, you can create an alias.cmd in your path (for example C:\Windows) with the command

@echo %2 %3 %4 %5 %6 > %windir%\%1.cmd

Once you do that, you can do something like this:

alias nameOfYourAlias commands to run 

And after that you can type in comman line

nameOfYourAlias 

this will execute

commands to run 

BUT the best way for me is just adding the path of a programm.

setx PATH "%PATH%;%ProgramFiles%\Sublime Text 3" /M 

And now I run sublime as

subl index.html

Disable browsers vertical and horizontal scrollbars

In case you need possibility to hide and show scrollbars dynamically you could use

$("body").css("overflow", "hidden");

and

$("body").css("overflow", "auto");

somewhere in your code.

Repeat String - Javascript

Here's the JSLint safe version

String.prototype.repeat = function (num) {
  var a = [];
  a.length = num << 0 + 1;
  return a.join(this);
};

Displaying output of a remote command with Ansible

Prints pubkey and avoid the changed status by adding changed_when: False to cat task:

- name: Generate SSH keys for vagrant user   
  user: name=vagrant generate_ssh_key=yes ssh_key_bits=2048

- name: Check SSH public key   
  command: /bin/cat $home_directory/.ssh/id_rsa.pub
  register: cat
  changed_when: False

- name: Print SSH public key
  debug: var=cat.stdout

- name: Wait for user to copy SSH public key   
  pause: prompt="Please add the SSH public key above to your GitHub account"

Convert string with comma to integer

Some more convenient

"1,1200.00".gsub(/[^0-9]/,'') 

it makes "1 200 200" work properly aswell

svn list of files that are modified in local copy

I couldn't get svn status -q to work. Assuming you are on a linux box, to see only the files that are modified, run: svn status | grep 'M ' On windows I am not sure what you would do, maybe something with 'FindStr'

How to secure an ASP.NET Web API

Web API introduced an Attribute [Authorize] to provide security. This can be set globally (global.asx)

public static void Register(HttpConfiguration config)
{
    config.Filters.Add(new AuthorizeAttribute());
}

Or per controller:

[Authorize]
public class ValuesController : ApiController{
...

Of course your type of authentication may vary and you may want to perform your own authentication, when this occurs you may find useful inheriting from Authorizate Attribute and extending it to meet your requirements:

public class DemoAuthorizeAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        if (Authorize(actionContext))
        {
            return;
        }
        HandleUnauthorizedRequest(actionContext);
    }

    protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        var challengeMessage = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
        challengeMessage.Headers.Add("WWW-Authenticate", "Basic");
        throw new HttpResponseException(challengeMessage);
    }

    private bool Authorize(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        try
        {
            var someCode = (from h in actionContext.Request.Headers where h.Key == "demo" select h.Value.First()).FirstOrDefault();
            return someCode == "myCode";
        }
        catch (Exception)
        {
            return false;
        }
    }
}

And in your controller:

[DemoAuthorize]
public class ValuesController : ApiController{

Here is a link on other custom implemenation for WebApi Authorizations:

http://www.piotrwalat.net/basic-http-authentication-in-asp-net-web-api-using-membership-provider/

How do I check if I'm running on Windows in Python?

import platform
is_windows = any(platform.win32_ver())

or

import sys
is_windows = hasattr(sys, 'getwindowsversion')

How can I make the Android emulator show the soft keyboard?

There is a bug in the new version of NOX app. Software keyboard doesn't work after switching to it in settings. To fix this, I installed Gboard using the Play Market.

Can you 'exit' a loop in PHP?

You can use the break keyword.

What does elementFormDefault do in XSD?

Important to note with elementFormDefault is that it applies to locally defined elements, typically named elements inside a complexType block, as opposed to global elements defined on the top-level of the schema. With elementFormDefault="qualified" you can address local elements in the schema from within the xml document using the schema's target namespace as the document's default namespace.

In practice, use elementFormDefault="qualified" to be able to declare elements in nested blocks, otherwise you'll have to declare all elements on the top level and refer to them in the schema in nested elements using the ref attribute, resulting in a much less compact schema.

This bit in the XML Schema Primer talks about it: http://www.w3.org/TR/xmlschema-0/#NS

MySQL "CREATE TABLE IF NOT EXISTS" -> Error 1050

Works fine for me in 5.0.27

I just get a warning (not an error) that the table exists;

Read file As String

Reworked the method set originating from -> the accepted answer

@JaredRummler An answer to your comment:

Read file As String

Won't this add an extra new line at the end of the string?

To prevent having a newline added at the end you can use a Boolean value set during the first loop as you will in the code example Boolean firstLine

public static String convertStreamToString(InputStream is) throws IOException {
   // http://www.java2s.com/Code/Java/File-Input-Output/ConvertInputStreamtoString.htm
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    String line = null;
    Boolean firstLine = true;
    while ((line = reader.readLine()) != null) {
        if(firstLine){
            sb.append(line);
            firstLine = false;
        } else {
            sb.append("\n").append(line);
        }
    }
    reader.close();
    return sb.toString();
}

public static String getStringFromFile (String filePath) throws IOException {
    File fl = new File(filePath);
    FileInputStream fin = new FileInputStream(fl);
    String ret = convertStreamToString(fin);
    //Make sure you close all streams.
    fin.close();
    return ret;
}

postgresql: INSERT INTO ... (SELECT * ...)

insert into TABLENAMEA (A,B,C,D) 
select A::integer,B,C,D from TABLENAMEB

Given an RGB value, how do I create a tint (or shade)?

I'm currently experimenting with canvas and pixels... I'm finding this logic works out for me better.

  1. Use this to calculate the grey-ness ( luma ? )
  2. but with both the existing value and the new 'tint' value
  3. calculate the difference ( I found I did not need to multiply )
  4. add to offset the 'tint' value

    var grey =  (r + g + b) / 3;    
    var grey2 = (new_r + new_g + new_b) / 3;
    
    var dr =  grey - grey2 * 1;    
    var dg =  grey - grey2 * 1    
    var db =  grey - grey2 * 1;  
    
    tint_r = new_r + dr;    
    tint_g = new_g + dg;   
    tint_b = new_b _ db;
    

or something like that...

How to limit depth for recursive file list?

tree -L 2 -u -g -p -d

Prints the directory tree in a pretty format up to depth 2 (-L 2). Print user (-u) and group (-g) and permissions (-p). Print only directories (-d). tree has a lot of other useful options.

How to implement a property in an interface

In the interface, you specify the property:

public interface IResourcePolicy
{
   string Version { get; set; }
}

In the implementing class, you need to implement it:

public class ResourcePolicy : IResourcePolicy
{
   public string Version { get; set; }
}

This looks similar, but it is something completely different. In the interface, there is no code. You just specify that there is a property with a getter and a setter, whatever they will do.

In the class, you actually implement them. The shortest way to do this is using this { get; set; } syntax. The compiler will create a field and generate the getter and setter implementation for it.

Adding a background image to a <div> element

Use this style to get a centered background image without repeat.

.bgImgCenter{
    background-image: url('imagePath');
    background-repeat: no-repeat;
    background-position: center; 
    position: relative;
}

In HTML, set this style for your div:

<div class="bgImgCenter"></div>

Cursor inside cursor

You have a variety of problems. First, why are you using your specific @@FETCH_STATUS values? It should just be @@FETCH_STATUS = 0.

Second, you are not selecting your inner Cursor into anything. And I cannot think of any circumstance where you would select all fields in this way - spell them out!

Here's a sample to go by. Folder has a primary key of "ClientID" that is also a foreign key for Attend. I'm just printing all of the Attend UIDs, broken down by Folder ClientID:

Declare @ClientID int;
Declare @UID int;

DECLARE Cur1 CURSOR FOR
    SELECT ClientID From Folder;

OPEN Cur1
FETCH NEXT FROM Cur1 INTO @ClientID;
WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT 'Processing ClientID: ' + Cast(@ClientID as Varchar);
    DECLARE Cur2 CURSOR FOR
        SELECT UID FROM Attend Where ClientID=@ClientID;
    OPEN Cur2;
    FETCH NEXT FROM Cur2 INTO @UID;
    WHILE @@FETCH_STATUS = 0
    BEGIN
        PRINT 'Found UID: ' + Cast(@UID as Varchar);
        FETCH NEXT FROM Cur2 INTO @UID;
    END;
    CLOSE Cur2;
    DEALLOCATE Cur2;
    FETCH NEXT FROM Cur1 INTO @ClientID;
END;
PRINT 'DONE';
CLOSE Cur1;
DEALLOCATE Cur1;

Finally, are you SURE you want to be doing something like this in a stored procedure? It is very easy to abuse stored procedures and often reflects problems in characterizing your problem. The sample I gave, for example, could be far more easily accomplished using standard select calls.

How to pattern match using regular expression in Scala?

String.matches is the way to do pattern matching in the regex sense.

But as a handy aside, word.firstLetter in real Scala code looks like:

word(0)

Scala treats Strings as a sequence of Char's, so if for some reason you wanted to explicitly get the first character of the String and match it, you could use something like this:

"Cat"(0).toString.matches("[a-cA-C]")
res10: Boolean = true

I'm not proposing this as the general way to do regex pattern matching, but it's in line with your proposed approach to first find the first character of a String and then match it against a regex.

EDIT: To be clear, the way I would do this is, as others have said:

"Cat".matches("^[a-cA-C].*")
res14: Boolean = true

Just wanted to show an example as close as possible to your initial pseudocode. Cheers!

Div show/hide media query

 Small devices (landscape phones, 576px and up)
@media (min-width: 576px) { 
  #my-content{
   width:100%;
 }

// Medium devices (tablets, 768px and up)
@media (min-width: 768px) { 
  #my-content{
   width:100%;
 }
 }

// Large devices (desktops, 992px and up)
@media (min-width: 992px) { 
display: none;
 }

// Extra large devices (large desktops, 1200px and up)
@media (min-width: 1200px) {
// Havent code only get for more informations 
 } 

How to pass a parameter to Vue @click event handler

Just use a normal Javascript expression, no {} or anything necessary:

@click="addToCount(item.contactID)"

if you also need the event object:

@click="addToCount(item.contactID, $event)"

Cannot send a content-body with this verb-type

Don't get the request stream, quite simply. GET requests don't usually have bodies (even though it's not technically prohibited by HTTP) and WebRequest doesn't support it - but that's what calling GetRequestStream is for, providing body data for the request.

Given that you're trying to read from the stream, it looks to me like you actually want to get the response and read the response stream from that:

WebRequest request = WebRequest.Create(get.AbsoluteUri + args);
request.Method = "GET";
using (WebResponse response = request.GetResponse())
{
    using (Stream stream = response.GetResponseStream())
    {
        XmlTextReader reader = new XmlTextReader(stream);
        ...
    }
}

Reset AutoIncrement in SQL Server after Delete

If you're using MySQL, try this:

ALTER TABLE tablename AUTO_INCREMENT = 1

git rebase: "error: cannot stat 'file': Permission denied"

Killing the w3wp.exe process related to the repository fixed this for me.

Convert java.util.Date to String

public static void main(String[] args) 
{
    Date d = new Date();
    SimpleDateFormat form = new SimpleDateFormat("dd-mm-yyyy hh:mm:ss");
    System.out.println(form.format(d));
    String str = form.format(d); // or if you want to save it in String str
    System.out.println(str); // and print after that
}

How do I import a .sql file in mysql database using PHP?

Grain Script is superb and save my day. Meanwhile mysql is depreciated and I rewrote Grain answer using PDO.

    $server  =  'localhost'; 
    $username   = 'root'; 
    $password   = 'your password';  
    $database = 'sample_db';

    /* PDO connection start */
    $conn = new PDO("mysql:host=$server; dbname=$database", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);         
    $conn->exec("SET CHARACTER SET utf8");     
    /* PDO connection end */

    // your config
    $filename = 'yourFile.sql';

    $maxRuntime = 8; // less then your max script execution limit


    $deadline = time()+$maxRuntime; 
    $progressFilename = $filename.'_filepointer'; // tmp file for progress
    $errorFilename = $filename.'_error'; // tmp file for erro



    ($fp = fopen($filename, 'r')) OR die('failed to open file:'.$filename);

    // check for previous error
    if( file_exists($errorFilename) ){
        die('<pre> previous error: '.file_get_contents($errorFilename));
    }

    // activate automatic reload in browser
    echo '<html><head> <meta http-equiv="refresh" content="'.($maxRuntime+2).'"><pre>';

    // go to previous file position
    $filePosition = 0;
    if( file_exists($progressFilename) ){
        $filePosition = file_get_contents($progressFilename);
        fseek($fp, $filePosition);
    }

    $queryCount = 0;
    $query = '';
    while( $deadline>time() AND ($line=fgets($fp, 1024000)) ){
        if(substr($line,0,2)=='--' OR trim($line)=='' ){
            continue;
        }

        $query .= $line;
        if( substr(trim($query),-1)==';' ){

            $igweze_prep= $conn->prepare($query);

            if(!($igweze_prep->execute())){ 
                $error = 'Error performing query \'<strong>' . $query . '\': ' . print_r($conn->errorInfo());
                file_put_contents($errorFilename, $error."\n");
                exit;
            }
            $query = '';
            file_put_contents($progressFilename, ftell($fp)); // save the current file position for 
            $queryCount++;
        }
    }

    if( feof($fp) ){
        echo 'dump successfully restored!';
    }else{
        echo ftell($fp).'/'.filesize($filename).' '.(round(ftell($fp)/filesize($filename), 2)*100).'%'."\n";
        echo $queryCount.' queries processed! please reload or wait for automatic browser refresh!';
    }

Printing a 2D array in C

Is this any help?

#include <stdio.h>

#define MAX 10

int main()
{
    char grid[MAX][MAX];
    int i,j,row,col;

    printf("Please enter your grid size: ");
    scanf("%d %d", &row, &col);


    for (i = 0; i < row; i++) {
        for (j = 0; j < col; j++) {
            grid[i][j] = '.';
            printf("%c ", grid[i][j]);
        }
        printf("\n");
    }

    return 0;
}

AngularJS toggle class using ng-class

Add more than one class based on the condition:

<div ng-click="AbrirPopUp(s)" 
ng-class="{'class1 class2 class3':!isNew, 
           'class1 class4': isNew}">{{ isNew }}</div>

Apply: class1 + class2 + class3 when isNew=false,

Apply: class1+ class4 when isNew=true

How to read files and stdout from a running Docker container

A bit late but this is what I'm doing with journald. It's pretty powerful.

You need to be running your docker containers on an OS with systemd-journald.

docker run -d --log-driver=journald myapp

This pipes the whole lot into host's journald which takes care of stuff like log pruning, storage format etc and gives you some cool options for viewing them:

journalctl CONTAINER_NAME=myapp -f

which will feed it to your console as it is logged,

journalctl CONTAINER_NAME=myapp > output.log

which gives you the whole lot in a file to take away, or

journalctl CONTAINER_NAME=myapp --since=17:45

Plus you can still see the logs via docker logs .... if that's your preference.

No more > my.log or -v "/apps/myapp/logs:/logs" etc

'cout' was not declared in this scope

Use std::cout, since cout is defined within the std namespace. Alternatively, add a using std::cout; directive.

Run git pull over all subdirectories

I use this one:

find . -name ".git" -type d | sed 's/\/.git//' |  xargs -P10 -I{} git -C {} pull

Universal: Updates all git repositories that are below current directory.

How to specify an alternate location for the .m2 folder or settings.xml permanently?

You can change the default location of .m2 directory in m2.conf file. It resides in your maven installation directory.

add modify this line in

m2.conf

set maven.home C:\Users\me\.m2

What is the difference between origin and upstream on GitHub?

after cloning a fork you have to explicitly add a remote upstream, with git add remote "the original repo you forked from". This becomes your upstream, you mostly fetch and merge from your upstream. Any other business such as pushing from your local to upstream should be done using pull request.

os.walk without digging into directories below

root folder changes for every directory os.walk finds. I solver that checking if root == directory

def _dir_list(self, dir_name, whitelist):
    outputList = []
    for root, dirs, files in os.walk(dir_name):
        if root == dir_name: #This only meet parent folder
            for f in files:
                if os.path.splitext(f)[1] in whitelist:
                    outputList.append(os.path.join(root, f))
                else:
                    self._email_to_("ignore")
    return outputList

Is there any publicly accessible JSON data source to test with real world data?

Found one from Flickr that doesn't need registration / api.

Basic sample, Fiddle: http://jsfiddle.net/Braulio/vDr36/

More info: post

Pasted sample

HTML

<div id="images">

</div>

Javascript

// Querystring, "tags" search term, comma delimited
var query = "http://www.flickr.com/services/feeds/photos_public.gne?tags=soccer&format=json&jsoncallback=?";


// This function is called once the call is satisfied
// http://stackoverflow.com/questions/13854250/understanding-cross-domain-xhr-and-xml-data
var mycallback = function (data) {

    // Start putting together the HTML string
    var htmlString = "";

    // Now start cycling through our array of Flickr photo details
    $.each(data.items, function(i,item){

        // I only want the ickle square thumbnails
        var sourceSquare = (item.media.m).replace("_m.jpg", "_s.jpg");

        // Here's where we piece together the HTML
        htmlString += '<li><a href="' + item.link + '" target="_blank">';
        htmlString += '<img title="' + item.title + '" src="' + sourceSquare;
        htmlString += '" alt="'; htmlString += item.title + '" />';
        htmlString += '</a></li>';

    });

    // Pop our HTML in the #images DIV
    $('#images').html(htmlString);
};


// Ajax call to retrieve data
$.getJSON(query, mycallback);

Another very interesting is Star Wars Rest API:

https://swapi.co/

How to enable bulk permission in SQL Server

Note that the accepted answer or either of these two solutions work for Windows only.

GRANT ADMINISTER BULK OPERATIONS TO [login_name];
-- OR
ALTER SERVER ROLE [bulkadmin] ADD MEMBER [login_name];

If you run any of them on SQL Server based on a linux machine, you will get these errors:

Msg 16202, Level 15, State 1, Line 1
Keyword or statement option 'bulkadmin' is not supported on the 'Linux' platform.
Msg 16202, Level 15, State 3, Line 1
Keyword or statement option 'ADMINISTER BULK OPERATIONS' is not supported on the 'Linux' platform.

Check the docs.

Requires INSERT and ADMINISTER BULK OPERATIONS permissions. In Azure SQL Database, INSERT and ADMINISTER DATABASE BULK OPERATIONS permissions are required. ADMINISTER BULK OPERATIONS permissions or the bulkadmin role is not supported for SQL Server on Linux. Only the sysadmin can perform bulk inserts for SQL Server on Linux.

Solution for Linux

ALTER SERVER ROLE [sysadmin] ADD MEMBER [login_name];

How to declare local variables in postgresql?

Postgresql historically doesn't support procedural code at the command level - only within functions. However, in Postgresql 9, support has been added to execute an inline code block that effectively supports something like this, although the syntax is perhaps a bit odd, and there are many restrictions compared to what you can do with SQL Server. Notably, the inline code block can't return a result set, so can't be used for what you outline above.

In general, if you want to write some procedural code and have it return a result, you need to put it inside a function. For example:

CREATE OR REPLACE FUNCTION somefuncname() RETURNS int LANGUAGE plpgsql AS $$
DECLARE
  one int;
  two int;
BEGIN
  one := 1;
  two := 2;
  RETURN one + two;
END
$$;
SELECT somefuncname();

The PostgreSQL wire protocol doesn't, as far as I know, allow for things like a command returning multiple result sets. So you can't simply map T-SQL batches or stored procedures to PostgreSQL functions.

How to extract filename.tar.gz file

Internally tar xcvf <filename> will call the binary gzip from the PATH environment variable to decompress the files in the tar archive. Sometimes third party tools use a custom gzip binary which is not compatible with the tar binary. It is a good idea to check the gzip binary in your PATH with which gzip and make sure that a correct gzip binary is called.

How to get JSON from webpage into Python script

you can use json.dumps:

import json

# Hier comes you received data

data = json.dumps(response)

print(data)

for loading json and write it on file the following code is useful:

data = json.loads(json.dumps(Response, sort_keys=False, indent=4))
with open('data.json', 'w') as outfile:
json.dump(data, outfile, sort_keys=False, indent=4)

How to "EXPIRE" the "HSET" child key in redis?

If your use-case is that you're caching values in Redis and are tolerant of stale values but would like to refresh them occasionally so that they don't get too stale, a hacky workaround is to just include a timestamp in the field value and handle expirations in whatever place you're accessing the value.

This allows you to keep using Redis hashes normally without needing to worry about any complications that might arise from the other approaches. The only cost is a bit of extra logic and parsing on the client end. Not a perfect solution, but it's what I typically do as I haven't needed TTL for any other reason and I'm usually needing to do extra parsing on the cached value anyways.

So basically it'll be something like this:

In Redis:

hash_name
- field_1: "2021-01-15;123"
- field_2: "2021-01-20;125"
- field_2: "2021-02-01;127"

Your (pseudo)code:

val = redis.hget(hash_name, field_1)
timestamp = val.substring(0, val.index_of(";"))

if now() > timestamp:
  new_val = get_updated_value()
  new_timestamp = now() + EXPIRY_LENGTH
  redis.hset(hash_name, field_1, new_timestamp + ";" + new_val)
  val = new_val
else:
  val = val.substring(val.index_of(";"))

// proceed to use val

The biggest caveat imo is that you don't ever remove fields so the hash can grow quite large. Not sure there's an elegant solution for that - I usually just delete the hash every once in a while if it feels too big. Maybe you could keep track of everything you've stored somewhere and remove them periodically (though at that point, you might as well just be using that mechanism to expire the fields manually...).

grep for special characters in Unix

grep -n "\*\^\%\Q\&\$\&\^\@\$\&\!\^\@\$\&\^\&\^\&\^\&" test.log
1:*^%Q&$&^@$&!^@$&^&^&^&
8:*^%Q&$&^@$&!^@$&^&^&^&
14:*^%Q&$&^@$&!^@$&^&^&^&

json_decode returns NULL after webservice call

EDIT: Just did some quick inspection of the string provided by the OP. The small "character" in front of the curly brace is a UTF-8 B(yte) O(rder) M(ark) 0xEF 0xBB 0xBF. I don't know why this byte sequence is displayed as ? here.

Essentially the system you aquire the data from sends it encoded in UTF-8 with a BOM preceding the data. You should remove the first three bytes from the string before you throw it into json_decode() (a substr($string, 3) will do).

string(62) "?{"action":"set","user":"123123123123","status":"OK"}"
            ^
            |
            This is the UTF-8 BOM

As Kuroki Kaze discovered, this character surely is the reason why json_decode fails. The string in its given form is not correctly a JSON formated structure (see RFC 4627)

Load vs. Stress testing

Load Testing: Load testing is meant to test the system by constantly and steadily increasing the load on the system till the time it reaches the threshold limit.

Example For example, to check the email functionality of an application, it could be flooded with 1000 users at a time. Now, 1000 users can fire the email transactions (read, send, delete, forward, reply) in many different ways. If we take one transaction per user per hour, then it would be 1000 transactions per hour. By simulating 10 transactions/user, we could load test the email server by occupying it with 10000 transactions/hour.

Stress Testing: Under stress testing, various activities to overload the existing resources with excess jobs are carried out in an attempt to break the system down.

Example: As an example, a word processor like Writer1.1.0 by OpenOffice.org is utilized in development of letters, presentations, spread sheets etc… Purpose of our stress testing is to load it with the excess of characters.

To do this, we will repeatedly paste a line of data, till it reaches its threshold limit of handling large volume of text. As soon as the character size reaches 65,535 characters, it would simply refuse to accept more data. The result of stress testing on Writer 1.1.0 produces the result that, it does not crash under the stress and that it handle the situation gracefully, which make sure that application is working correctly even under rigorous stress conditions.

To add server using sp_addlinkedserver

Add the linked server first with

exec sp_addlinkedserver
@server = 'SNRJDI\SLAMANAGEMENT',
@srvproduct=N'',
@provider=N'SQLNCLI'

See http://msdn.microsoft.com/en-us/library/ms190479.aspx

Index of Currently Selected Row in DataGridView

try this it will work...it will give you the index of selected row index...

int rowindex = dataGridView1.CurrentRow.Index;
MessageBox.Show(rowindex.ToString());

How do you dynamically add elements to a ListView on Android?

If you want to have the ListView in an AppCompatActivity instead of ListActivity, you can do the following (Modifying @Shardul's answer):

public class ListViewDemoActivity extends AppCompatActivity {
    //LIST OF ARRAY STRINGS WHICH WILL SERVE AS LIST ITEMS
    ArrayList<String> listItems=new ArrayList<String>();

    //DEFINING A STRING ADAPTER WHICH WILL HANDLE THE DATA OF THE LISTVIEW
    ArrayAdapter<String> adapter;

    //RECORDING HOW MANY TIMES THE BUTTON HAS BEEN CLICKED
    int clickCounter=0;
    private ListView mListView;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.activity_list_view_demo);

        if (mListView == null) {
            mListView = (ListView) findViewById(R.id.listDemo);
        }

        adapter=new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1,
                listItems);
        setListAdapter(adapter);
    }

    //METHOD WHICH WILL HANDLE DYNAMIC INSERTION
    public void addItems(View v) {
        listItems.add("Clicked : "+clickCounter++);
        adapter.notifyDataSetChanged();
    }

    protected ListView getListView() {
        if (mListView == null) {
            mListView = (ListView) findViewById(R.id.listDemo);
        }
        return mListView;
    }

    protected void setListAdapter(ListAdapter adapter) {
        getListView().setAdapter(adapter);
    }

    protected ListAdapter getListAdapter() {
        ListAdapter adapter = getListView().getAdapter();
        if (adapter instanceof HeaderViewListAdapter) {
            return ((HeaderViewListAdapter)adapter).getWrappedAdapter();
        } else {
            return adapter;
        }
    }
}

And in you layout instead of using android:id="@android:id/list" you can use android:id="@+id/listDemo"

So now you can have a ListView inside a normal AppCompatActivity.

How can I exclude multiple folders using Get-ChildItem -exclude?

My KISS approach to skip some folders is chaining Get-ChildItem calls. This excludes root level folders but not deeper level folders if that is what you want.

Get-ChildItem -Exclude folder1,folder2 | Get-ChildItem -Recurse | ...
  • Start excluding folders you don't want
  • Then do the recursive search with non desired folders excluded.

What I like from this approach is that it is simple and easy to remember. If you don't want to mix folders and files in the first search a filter would be needed.

What's the best UML diagramming tool?

As I usually use UML more as a communication tool rather than a modeling tool I sometimes have the need to flex the language a bit, which makes the strict modeling tools quite unwieldy. Also, they tend to have a large overhead for the occasional drawing. This also means I don't give tools that handle round-trip modeling well any bonus points. With this in mind...

When using Visio, I tend to use these stencils for my UMLing needs (the built in kind of suck). It could be that I have grown used to it as it is the primary diagramming tool at my current assignment.

OmniGraffle also has some UML stencils built in and more are available at Graffletopia, but I wouldn't recommend that as a diagramming tool as it has too many quirks (quirks that are good for many things, but not UML). Free trial though, so by all means... :)

I've been trying out MagicDraw a bit, but while functional, I found the user interface distracting.

Otherwise i find the Topcased an interesting project (or group of projects). Last I used it it still had some bugs, but it worked, and seems to have evolved nicely since. Works great on any Eclipse-enabled platform. Free as in speech and beer :)

As for the diagramming tool Dia, it's quite ugly (interface and resulting drawings), but it does get the job done. An interesting modeling tool free alternative is Umbrello, but I haven't really used it much.

I definitely agree with mashi that whiteboards are great (together with a digital camera or cellphone).

Probably some of the nicest tools I've used belong to the Rational family of tools.

How to refer environment variable in POM.xml?

It might be safer to directly pass environment variables to maven system properties. For example, say on Linux you want to access environment variable MY_VARIABLE. You can use a system property in your pom file.

<properties>
    ...
    <!-- Default value for my.variable can be defined here -->
    <my.variable>foo</my.variable>
    ...
</properties>
...
<!-- Use my.variable -->
... ${my.variable} ...

Set the property value on the maven command line:

mvn clean package -Dmy.variable=$MY_VARIABLE

.htaccess not working apache

Most probably, AllowOverride is set to None. in Directory section of apache2.conf located in /etc/apache2 folder

Try setting it to AllowOverride All

How can I set a website image that will show as preview on Facebook?

If you're using Weebly, start by viewing the published site and right-clicking the image to Copy Image Address. Then in Weebly, go to Edit Site, Pages, click the page you wish to use, SEO Settings, under Header Code enter the code from Shef's answer:

<meta property="og:image" content="/uploads/..." />

just replacing /uploads/... with the copied image address. Click Publish to apply the change.

You can skip the part of Shef's answer about namespace, because that's already set by default in Weebly.

How to temporarily disable a click handler in jQuery?

You can do it like the other people before me told you using a look:

A.) Use .data of the button element to share a look variable (or a just global variable)

if ($('#buttonId').data('locked') == 1)
    return
$('#buttonId').data('locked') = 1;
// Do your thing
$('#buttonId').data('locked') = 0;

B.) Disable mouse signals

$("#buttonId").css("pointer-events", "none");
// Do your thing
$("#buttonId").css("pointer-events", "auto");

C.) If it is a HTML button you can disable it (input [type=submit] or button)

$("#buttonId").attr("disabled", "true");
// Do your thing
$("#buttonId").attr("disabled", "false");

But watch out for other threads! I failed many times because my animation (fading in or out) took one second. E.g. fadeIn/fadeOut supports a callback function as second parameter. If there is no other way just do it using setTimeout(callback, delay).

Greets, Thomas

How do I hide certain files from the sidebar in Visual Studio Code?

Sometimes you just want to hide certain file types for a specific project. In that case, you can create a folder in your project folder called .vscode and create the settings.json file in there, (i.e. .vscode/settings.json). All settings within that file will affect your current workspace only.

For example, in a TypeScript project, this is what I have used:

// Workspace settings
{
    // The following will hide the js and map files in the editor
    "files.exclude": {
        "**/*.js": true,
        "**/*.map": true
    }
}

Upload DOC or PDF using PHP

Please add the correct mime-types to your code - at least these ones:

.jpeg -> image/jpeg
.gif  -> image/gif
.png  -> image/png

A list of mime-types can be found here.

Furthermore, simplify the code's logic and report an error number to help the first level support track down problems:

$allowedExts = array(
  "pdf", 
  "doc", 
  "docx"
); 

$allowedMimeTypes = array( 
  'application/msword',
  'text/pdf',
  'image/gif',
  'image/jpeg',
  'image/png'
);

$extension = end(explode(".", $_FILES["file"]["name"]));

if ( 20000 < $_FILES["file"]["size"]  ) {
  die( 'Please provide a smaller file [E/1].' );
}

if ( ! ( in_array($extension, $allowedExts ) ) ) {
  die('Please provide another file type [E/2].');
}

if ( in_array( $_FILES["file"]["type"], $allowedMimeTypes ) ) 
{      
 move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); 
}
else
{
die('Please provide another file type [E/3].');
}

How can I check if a user is logged-in in php?

Almost all of the answers on this page rely on checking a session variable's existence to validate a user login. That is absolutely fine, but it is important to consider that the PHP session state is not unique to your application if there are multiple virtual hosts/sites on the same bare metal.

If you have two PHP applications on a webserver, both checking a user's login status with a boolean flag in a session variable called 'isLoggedIn', then a user could log into one of the applications and then automagically gain access to the second without credentials.

I suspect even the most dinosaur of commercial shared hosting wouldn't let virtual hosts share the same PHP environment in such a way that this could happen across multiple customers site's (anymore), but its something to consider in your own environments.

The very simple solution is to use a session variable that identifies the app rather than a boolean flag. e.g $SESSION["isLoggedInToExample.com"].

Source: I'm a penetration tester, with a lot of experience on how you shouldn't do stuff.

CentOS: Enabling GD Support in PHP Installation

The thing that did the trick for me eventually was:

yum install gd gd-devel php-gd

and then restart apache:

service httpd restart

Saving results with headers in Sql Server Management Studio

Another possibility is to use the clipboard to copy and paste the results directly into Excel. Just be careful with General type Excel columns, as they can sometimes have unpredictable results, depending on your data. CTL-A anywhere in the result grid, and then right-click:

enter image description here

If you have trouble with Excel's General format doing undesired conversions, select the blank columns in Excel before you paste and change the format to "text".

How can I get the current date and time in UTC or GMT in Java?

Here is my implementation of toUTC:

    public static Date toUTC(Date date){
    long datems = date.getTime();
    long timezoneoffset = TimeZone.getDefault().getOffset(datems);
    datems -= timezoneoffset;
    return new Date(datems);
}

There's probably several ways to improve it, but it works for me.

Convert string to binary then back again using PHP

A string is just a sequence of bytes, hence it's actually binary data in PHP. What exactly are you trying to do?

EDIT

If you want to store binary data in your database, the problem most often is the column definition in your database. PHP does not differentiate between binary data and strings, but databases do. In MySQL for example you should store binary data in BINARY, VARBINARY or BLOB columns.

Another option would be to base64_encode your PHP string and store it in some VARCHAR or TEXT column in the database. But be aware that the string's length will increase when base64_encode is used.

Open URL in Java to get the content

String url_open ="http://javadl.sun.com/webapps/download/AutoDL?BundleId=76860";
java.awt.Desktop.getDesktop().browse(java.net.URI.create(url_open));

node.js string.replace doesn't work?

According to the Javascript standard, String.replace isn't supposed to modify the string itself. It just returns the modified string. You can refer to the Mozilla Developer Network documentation for more info.

You can always just set the string to the modified value:

variableABC = variableABC.replace('B', 'D')

Edit: The code given above is to only replace the first occurrence.

To replace all occurrences, you could do:

 variableABC = variableABC.replace(/B/g, "D");  

To replace all occurrences and ignore casing

 variableABC = variableABC.replace(/B/gi, "D");  

Convert timedelta to total seconds

You can use mx.DateTime module

import mx.DateTime as mt

t1 = mt.now() 
t2 = mt.now()
print int((t2-t1).seconds)

Composer: The requested PHP extension ext-intl * is missing from your system

This is bit old question but I had faced same problem on linux base server while installing magento 2.

When I am firing composer update or composer install command from my magento root dir. Its was firing below error.

Problem 1
    - The requested PHP extension ext-intl * is missing from your system. Install or enable PHP's intl extension.
  Problem 2
    - The requested PHP extension ext-mbstring * is missing from your system. Install or enable PHP's mbstring extension.
  Problem 3
    - Installation request for pelago/emogrifier 0.1.1 -> satisfiable by pelago/emogrifier[v0.1.1].
    - pelago/emogrifier v0.1.1 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
   ...

Then, I searched for the available intl & intl extensions, using below commands.

yum list php*intl
yum install php-intl.x86_64  

yum list php*mbstring
yum install php-mbstring.x86_64

And it fixed the issue.

How to find the users list in oracle 11g db?

You can think of a mysql database as a schema/user in Oracle. If you have the privileges, you can query the DBA_USERS view to see the list of schema.

how to set ulimit / file descriptor on docker container the image tag is phusion/baseimage-docker

After some searching I found this on a Google groups discussion:

docker currently inhibits this capability for enhanced safety.

That is because the ulimit settings of the host system apply to the docker container. It is regarded as a security risk that programs running in a container can change the ulimit settings for the host.

The good news is that you have two different solutions to choose from.

  1. Remove sys_resource from lxc_template.go and recompile docker. Then you'll be able to set the ulimit as high as you like.

or

  1. Stop the docker demon. Change the ulimit settings on the host. Start the docker demon. It now has your revised limits, and its child processes as well.

I applied the second method:

  1. sudo service docker stop;

  2. changed the limits in /etc/security/limits.conf

  3. reboot the machine

  4. run my container

  5. run ulimit -a in the container to confirm the open files limit has been inherited.

See: https://groups.google.com/forum/#!searchin/docker-user/limits/docker-user/T45Kc9vD804/v8J_N4gLbacJ

invalid_client in google oauth2

in this thread i found my answer.

  1. I went to google console,
  2. generate a new project, made refresh, because in my case after create the page didn't reload
  3. select new project
  4. create a client ID
  5. use it for what you need

thanks guys :D

Java Object Null Check for method

You can add a guard condition to the method to ensure books is not null and then check for null when iterating the array:

public static double calculateInventoryTotal(Book[] books)
{
    if(books == null){
        throw new IllegalArgumentException("Books cannot be null");
    }

    double total = 0;

    for (int i = 0; i < books.length; i++)
    {
        if(books[i] != null){
            total += books[i].getPrice();
        }
    }

    return total;
}

What does {0} mean when found in a string in C#?

This is what we called Composite Formatting of the .NET Framework to convert the value of an object to its text representation and embed that representation in a string. The resulting string is written to the output stream.

The overloaded Console.WriteLine Method (String, Object)Writes the text representation of the specified object, followed by the current line terminator, to the standard output stream using the specified format information.

Rails - How to use a Helper Inside a Controller

Note: This was written and accepted back in the Rails 2 days; nowadays grosser's answer is the way to go.

Option 1: Probably the simplest way is to include your helper module in your controller:

class MyController < ApplicationController
  include MyHelper

  def xxxx
    @comments = []
    Comment.find_each do |comment|
      @comments << {:id => comment.id, :html => html_format(comment.content)}
    end
  end
end

Option 2: Or you can declare the helper method as a class function, and use it like so:

MyHelper.html_format(comment.content)

If you want to be able to use it as both an instance function and a class function, you can declare both versions in your helper:

module MyHelper
  def self.html_format(str)
    process(str)
  end

  def html_format(str)
    MyHelper.html_format(str)
  end
end

Hope this helps!

How to create a numpy array of arbitrary length strings?

You could use the object data type:

>>> import numpy
>>> s = numpy.array(['a', 'b', 'dude'], dtype='object')
>>> s[0] += 'bcdef'
>>> s
array([abcdef, b, dude], dtype=object)

adding x and y axis labels in ggplot2

[Note: edited to modernize ggplot syntax]

Your example is not reproducible since there is no ex1221new (there is an ex1221 in Sleuth2, so I guess that is what you meant). Also, you don't need (and shouldn't) pull columns out to send to ggplot. One advantage is that ggplot works with data.frames directly.

You can set the labels with xlab() and ylab(), or make it part of the scale_*.* call.

library("Sleuth2")
library("ggplot2")
ggplot(ex1221, aes(Discharge, Area)) +
  geom_point(aes(size=NO3)) + 
  scale_size_area() + 
  xlab("My x label") +
  ylab("My y label") +
  ggtitle("Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")

enter image description here

ggplot(ex1221, aes(Discharge, Area)) +
  geom_point(aes(size=NO3)) + 
  scale_size_area("Nitrogen") + 
  scale_x_continuous("My x label") +
  scale_y_continuous("My y label") +
  ggtitle("Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")

enter image description here

An alternate way to specify just labels (handy if you are not changing any other aspects of the scales) is using the labs function

ggplot(ex1221, aes(Discharge, Area)) +
  geom_point(aes(size=NO3)) + 
  scale_size_area() + 
  labs(size= "Nitrogen",
       x = "My x label",
       y = "My y label",
       title = "Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")

which gives an identical figure to the one above.

How can I increase the JVM memory?

If you are using Eclipse then you can do this by specifying the required size for the particular application in its Run Configuration's VM Arguments as EX: -Xms128m -Xmx512m

Or if you want all applications running from your eclipse to have the same specified size then you can specify this in the eclipse.ini file which is present in your Eclipse home directory.

To get the size of the JVM during Runtime you can use Runtime.totalMemory() which returns the total amount of memory in the Java virtual machine, measured in bytes.

Styling every 3rd item of a list using CSS?

Yes, you can use what's known as :nth-child selectors.

In this case you would use:

li:nth-child(3n) {
// Styling for every third element here.
}

:nth-child(3n):

3(0) = 0
3(1) = 3
3(2) = 6
3(3) = 9
3(4) = 12

:nth-child() is compatible in Chrome, Firefox, and IE9+.

For a work around to use :nth-child() amongst other pseudo-classes/attribute selectors in IE6 through to IE8, see this link.

Check date with todays date

Android already has a dedicated class for this. Check DateUtils.isToday(long when)

Ignoring new fields on JSON objects using Jackson

For whom are using Spring Boot, you can configure the default behaviour of Jackson by using the Jackson2ObjectMapperBuilder.

For example :

@Bean
public Jackson2ObjectMapperBuilder configureObjectMapper() {
    Jackson2ObjectMapperBuilder oMapper = new Jackson2ObjectMapperBuilder();
    oMapper.failOnUnknownProperties(false);
    return oMapper;
}

Then you can autowire the ObjectMapper everywhere you need it (by default, this object mapper will also be used for http content conversion).

How to find current transaction level?

If you are talking about the current transaction nesting level, then you would use @@TRANCOUNT.

If you are talking about transaction isolation level, use DBCC USEROPTIONS and look for an option of isolation level. If it isn't set, it's read committed.

'xmlParseEntityRef: no name' warnings while loading xml into a php file

This is in deed due to characters messing around with the data. Using htmlentities($yourText) worked for me (I had html code inside the xml document). See http://uk3.php.net/htmlentities.

When is "java.io.IOException:Connection reset by peer" thrown?

java.io.IOException: Connection reset by peer

In my case, the problem was with PUT requests (GET and POST were passing successfully).

Communication went through VPN tunnel and ssh connection. And there was a firewall with default restrictions on PUT requests... PUT requests haven't been passing throughout, to the server...

Problem was solved after exception was added to the firewall for my IP address.

How to compile without warnings being treated as errors?

Thanks for all the helpful suggestions. I finally made sure that there are no warnings in my code, but again was getting this warning from sqlite3:

Assuming signed overflow does not occur when assuming that (X - c) <= X is always true

which I fixed by adding the following CFLAG:

-fno-strict-overflow

Applying .gitignore to committed files

After editing .gitignore to match the ignored files, you can do git ls-files -ci --exclude-standard to see the files that are included in the exclude lists; you can then do

  • Linux/MacOS: git ls-files -ci --exclude-standard -z | xargs -0 git rm --cached
  • Windows (PowerShell): git ls-files -ci --exclude-standard | % { git rm --cached "$_" }
  • Windows (cmd.exe): for /F "tokens=*" %a in ('git ls-files -ci --exclude-standard') do @git rm --cached "%a"

to remove them from the repository (without deleting them from disk).

Edit: You can also add this as an alias in your .gitconfig file so you can run it anytime you like. Just add the following line under the [alias] section (modify as needed for Windows or Mac):

apply-gitignore = !git ls-files -ci --exclude-standard -z | xargs -0 git rm --cached

(The -r flag in xargs prevents git rm from running on an empty result and printing out its usage message, but may only be supported by GNU findutils. Other versions of xargs may or may not have a similar option.)

Now you can just type git apply-gitignore in your repo, and it'll do the work for you!

open new tab(window) by clicking a link in jquery

Try this:

window.open(url, '_blank');

This will open in new tab (if your code is synchronous and in this case it is. in other case it would open a window)

How to shift a column in Pandas DataFrame

If you don't want to lose the columns you shift past the end of your dataframe, simply append the required number first:

    offset = 5
    DF = DF.append([np.nan for x in range(offset)])
    DF = DF.shift(periods=offset)
    DF = DF.reset_index() #Only works if sequential index

How to use OpenSSL to encrypt/decrypt files?

There is an open source program that I find online it uses openssl to encrypt and decrypt files. It does this with a single password. The great thing about this open source script is that it deletes the original unencrypted file by shredding the file. But the dangerous thing about is once the original unencrypted file is gone you have to make sure you remember your password otherwise they be no other way to decrypt your file.

Here the link it is on github

https://github.com/EgbieAnderson1/linux_file_encryptor/blob/master/file_encrypt.py

Checkout old commit and make it a new commit

It sounds like you just want to reset to C; that is make the tree:

A-B-C

You can do that with reset:

git reset --hard HEAD~3

(Note: You said three commits ago so that's what I wrote; in your example C is only two commits ago, so you might want to use HEAD~2)


You can also use revert if you want, although as far as I know you need to do the reverts one at a time:

git revert HEAD     # Reverts E
git revert HEAD~2   # Reverts D

That will create a new commit F that's the same contents as D, and G that's the same contents as C. You can rebase to squash those together if you want

How to send 500 Internal Server Error error from a PHP script

PHP 5.4 has a function called http_response_code, so if you're using PHP 5.4 you can just do:

http_response_code(500);

I've written a polyfill for this function (Gist) if you're running a version of PHP under 5.4.


To answer your follow-up question, the HTTP 1.1 RFC says:

The reason phrases listed here are only recommendations -- they MAY be replaced by local equivalents without affecting the protocol.

That means you can use whatever text you want (excluding carriage returns or line feeds) after the code itself, and it'll work. Generally, though, there's usually a better response code to use. For example, instead of using a 500 for no record found, you could send a 404 (not found), and for something like "conditions failed" (I'm guessing a validation error), you could send something like a 422 (unprocessable entity).

How to configure log4j with a properties file

I have this code in my application today

File log4jfile = new File("./conf/log4j.properties");
PropertyConfigurator.configure(log4jfile.getAbsolutePath());

The relative path is from the working directory of the JVM (where the JVM starts).

Disable JavaScript error in WebBrowser control

None of the above solutions were suitable for my scenario, handling .Navigated and .FileDownload events seemed like a good fit but accessing the WebBrowser.Document property threw an UnauthorizedAccessException which is caused by cross frame scripting security (our web content contains frames - all on the same domain/address but frames have their own security holes that are being blocked).

The solution that worked was to override IOleCommandTarget and to catch the script error commands at that level. Here's the WebBrowser sub-class to achieve this:

/// <summary>
/// Subclassed WebBrowser that suppresses error pop-ups.
/// 
/// Notes.
/// ScriptErrorsSuppressed property is not used because this actually suppresses *all* pop-ups.
/// 
/// More info at:
/// http://stackoverflow.com/questions/2476360/disable-javascript-error-in-webbrowser-control
/// </summary>
public class WebBrowserEx : WebBrowser
{
    #region Constructor

    /// <summary>
    /// Default constructor.
    /// Initialise browser control and attach customer event handlers.
    /// </summary>
    public WebBrowserEx()
    {
        this.ScriptErrorsSuppressed = false;
    }

    #endregion

    #region Overrides

    /// <summary>
    /// Override to allow custom script error handling.
    /// </summary>
    /// <returns></returns>
    protected override WebBrowserSiteBase CreateWebBrowserSiteBase()
    {
        return new WebBrowserSiteEx(this);
    }

    #endregion

    #region Inner Class [WebBrowserSiteEx]

    /// <summary>
    /// Sub-class to allow custom script error handling.
    /// </summary>
    protected class WebBrowserSiteEx : WebBrowserSite, NativeMethods.IOleCommandTarget
    {
        /// <summary>
        /// Default constructor.
        /// </summary>
        public WebBrowserSiteEx(WebBrowserEx webBrowser) : base (webBrowser)
        {   
        }

        /// <summary>Queries the object for the status of one or more commands generated by user interface events.</summary>
        /// <param name="pguidCmdGroup">The GUID of the command group.</param>
        /// <param name="cCmds">The number of commands in <paramref name="prgCmds" />.</param>
        /// <param name="prgCmds">An array of OLECMD structures that indicate the commands for which the caller needs status information. This method fills the <paramref name="cmdf" /> member of each structure with values taken from the OLECMDF enumeration.</param>
        /// <param name="pCmdText">An OLECMDTEXT structure in which to return name and/or status information of a single command. This parameter can be null to indicate that the caller does not need this information.</param>
        /// <returns>This method returns S_OK on success. Other possible return values include the following.
        /// E_FAIL The operation failed.
        /// E_UNEXPECTED An unexpected error has occurred.
        /// E_POINTER The <paramref name="prgCmds" /> argument is null.
        /// OLECMDERR_E_UNKNOWNGROUP The <paramref name="pguidCmdGroup" /> parameter is not null but does not specify a recognized command group.</returns>
        public int QueryStatus(ref Guid pguidCmdGroup, int cCmds, NativeMethods.OLECMD prgCmds, IntPtr pCmdText)
        {
            if((int)NativeMethods.OLECMDID.OLECMDID_SHOWSCRIPTERROR == prgCmds.cmdID)
            {   // Do nothing (suppress script errors)
                return NativeMethods.S_OK;
            }

            // Indicate that command is unknown. The command will then be handled by another IOleCommandTarget.
            return NativeMethods.OLECMDERR_E_UNKNOWNGROUP;
        }

        /// <summary>Executes the specified command.</summary>
        /// <param name="pguidCmdGroup">The GUID of the command group.</param>
        /// <param name="nCmdID">The command ID.</param>
        /// <param name="nCmdexecopt">Specifies how the object should execute the command. Possible values are taken from the <see cref="T:Microsoft.VisualStudio.OLE.Interop.OLECMDEXECOPT" /> and <see cref="T:Microsoft.VisualStudio.OLE.Interop.OLECMDID_WINDOWSTATE_FLAG" /> enumerations.</param>
        /// <param name="pvaIn">The input arguments of the command.</param>
        /// <param name="pvaOut">The output arguments of the command.</param>
        /// <returns>This method returns S_OK on success. Other possible return values include 
        /// OLECMDERR_E_UNKNOWNGROUP The <paramref name="pguidCmdGroup" /> parameter is not null but does not specify a recognized command group.
        /// OLECMDERR_E_NOTSUPPORTED The <paramref name="nCmdID" /> parameter is not a valid command in the group identified by <paramref name="pguidCmdGroup" />.
        /// OLECMDERR_E_DISABLED The command identified by <paramref name="nCmdID" /> is currently disabled and cannot be executed.
        /// OLECMDERR_E_NOHELP The caller has asked for help on the command identified by <paramref name="nCmdID" />, but no help is available.
        /// OLECMDERR_E_CANCELED The user canceled the execution of the command.</returns>
        public int Exec(ref Guid pguidCmdGroup, int nCmdID, int nCmdexecopt, object[] pvaIn, int pvaOut)
        {
            if((int)NativeMethods.OLECMDID.OLECMDID_SHOWSCRIPTERROR == nCmdID)
            {   // Do nothing (suppress script errors)
                return NativeMethods.S_OK;
            }

            // Indicate that command is unknown. The command will then be handled by another IOleCommandTarget.
            return NativeMethods.OLECMDERR_E_UNKNOWNGROUP;
        }
    }

    #endregion
}

~

/// <summary>
/// Native (unmanaged) methods, required for custom command handling for the WebBrowser control.
/// </summary>
public static class NativeMethods
{
    /// From docobj.h
    public const int OLECMDERR_E_UNKNOWNGROUP = -2147221244;

    /// <summary>
    /// From Microsoft.VisualStudio.OLE.Interop (Visual Studio 2010 SDK).
    /// </summary>
    public enum OLECMDID
    {
        /// <summary />
        OLECMDID_OPEN = 1,
        /// <summary />
        OLECMDID_NEW,
        /// <summary />
        OLECMDID_SAVE,
        /// <summary />
        OLECMDID_SAVEAS,
        /// <summary />
        OLECMDID_SAVECOPYAS,
        /// <summary />
        OLECMDID_PRINT,
        /// <summary />
        OLECMDID_PRINTPREVIEW,
        /// <summary />
        OLECMDID_PAGESETUP,
        /// <summary />
        OLECMDID_SPELL,
        /// <summary />
        OLECMDID_PROPERTIES,
        /// <summary />
        OLECMDID_CUT,
        /// <summary />
        OLECMDID_COPY,
        /// <summary />
        OLECMDID_PASTE,
        /// <summary />
        OLECMDID_PASTESPECIAL,
        /// <summary />
        OLECMDID_UNDO,
        /// <summary />
        OLECMDID_REDO,
        /// <summary />
        OLECMDID_SELECTALL,
        /// <summary />
        OLECMDID_CLEARSELECTION,
        /// <summary />
        OLECMDID_ZOOM,
        /// <summary />
        OLECMDID_GETZOOMRANGE,
        /// <summary />
        OLECMDID_UPDATECOMMANDS,
        /// <summary />
        OLECMDID_REFRESH,
        /// <summary />
        OLECMDID_STOP,
        /// <summary />
        OLECMDID_HIDETOOLBARS,
        /// <summary />
        OLECMDID_SETPROGRESSMAX,
        /// <summary />
        OLECMDID_SETPROGRESSPOS,
        /// <summary />
        OLECMDID_SETPROGRESSTEXT,
        /// <summary />
        OLECMDID_SETTITLE,
        /// <summary />
        OLECMDID_SETDOWNLOADSTATE,
        /// <summary />
        OLECMDID_STOPDOWNLOAD,
        /// <summary />
        OLECMDID_ONTOOLBARACTIVATED,
        /// <summary />
        OLECMDID_FIND,
        /// <summary />
        OLECMDID_DELETE,
        /// <summary />
        OLECMDID_HTTPEQUIV,
        /// <summary />
        OLECMDID_HTTPEQUIV_DONE,
        /// <summary />
        OLECMDID_ENABLE_INTERACTION,
        /// <summary />
        OLECMDID_ONUNLOAD,
        /// <summary />
        OLECMDID_PROPERTYBAG2,
        /// <summary />
        OLECMDID_PREREFRESH,
        /// <summary />
        OLECMDID_SHOWSCRIPTERROR,
        /// <summary />
        OLECMDID_SHOWMESSAGE,
        /// <summary />
        OLECMDID_SHOWFIND,
        /// <summary />
        OLECMDID_SHOWPAGESETUP,
        /// <summary />
        OLECMDID_SHOWPRINT,
        /// <summary />
        OLECMDID_CLOSE,
        /// <summary />
        OLECMDID_ALLOWUILESSSAVEAS,
        /// <summary />
        OLECMDID_DONTDOWNLOADCSS,
        /// <summary />
        OLECMDID_UPDATEPAGESTATUS,
        /// <summary />
        OLECMDID_PRINT2,
        /// <summary />
        OLECMDID_PRINTPREVIEW2,
        /// <summary />
        OLECMDID_SETPRINTTEMPLATE,
        /// <summary />
        OLECMDID_GETPRINTTEMPLATE
    }

    /// <summary>
    /// From Microsoft.VisualStudio.Shell (Visual Studio 2010 SDK).
    /// </summary>
    public const int S_OK = 0;

    /// <summary>
    /// OLE command structure.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    public class OLECMD
    {
        /// <summary>
        /// Command ID.
        /// </summary>
        [MarshalAs(UnmanagedType.U4)]
        public int cmdID;
        /// <summary>
        /// Flags associated with cmdID.
        /// </summary>
        [MarshalAs(UnmanagedType.U4)]
        public int cmdf;
    }

    /// <summary>
    /// Enables the dispatching of commands between objects and containers.
    /// </summary>
    [ComVisible(true), Guid("B722BCCB-4E68-101B-A2BC-00AA00404770"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    [ComImport]
    public interface IOleCommandTarget
    {
        /// <summary>Queries the object for the status of one or more commands generated by user interface events.</summary>
        /// <param name="pguidCmdGroup">The GUID of the command group.</param>
        /// <param name="cCmds">The number of commands in <paramref name="prgCmds" />.</param>
        /// <param name="prgCmds">An array of <see cref="T:Microsoft.VisualStudio.OLE.Interop.OLECMD" /> structures that indicate the commands for which the caller needs status information.</param>
        /// <param name="pCmdText">An <see cref="T:Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT" /> structure in which to return name and/or status information of a single command. This parameter can be null to indicate that the caller does not need this information.</param>
        /// <returns>This method returns S_OK on success. Other possible return values include the following.
        /// E_FAIL The operation failed.
        /// E_UNEXPECTED An unexpected error has occurred.
        /// E_POINTER The <paramref name="prgCmds" /> argument is null.
        /// OLECMDERR_E_UNKNOWNGROUPThe <paramref name="pguidCmdGroup" /> parameter is not null but does not specify a recognized command group.</returns>
        [PreserveSig]
        [return: MarshalAs(UnmanagedType.I4)]
        int QueryStatus(ref Guid pguidCmdGroup, int cCmds, [In] [Out] NativeMethods.OLECMD prgCmds, [In] [Out] IntPtr pCmdText);

        /// <summary>Executes the specified command.</summary>
        /// <param name="pguidCmdGroup">The GUID of the command group.</param>
        /// <param name="nCmdID">The command ID.</param>
        /// <param name="nCmdexecopt">Specifies how the object should execute the command. Possible values are taken from the <see cref="T:Microsoft.VisualStudio.OLE.Interop.OLECMDEXECOPT" /> and <see cref="T:Microsoft.VisualStudio.OLE.Interop.OLECMDID_WINDOWSTATE_FLAG" /> enumerations.</param>
        /// <param name="pvaIn">The input arguments of the command.</param>
        /// <param name="pvaOut">The output arguments of the command.</param>
        /// <returns>This method returns S_OK on success. Other possible return values include 
        /// OLECMDERR_E_UNKNOWNGROUP The <paramref name="pguidCmdGroup" /> parameter is not null but does not specify a recognized command group.
        /// OLECMDERR_E_NOTSUPPORTED The <paramref name="nCmdID" /> parameter is not a valid command in the group identified by <paramref name="pguidCmdGroup" />.
        /// OLECMDERR_E_DISABLED The command identified by <paramref name="nCmdID" /> is currently disabled and cannot be executed.
        /// OLECMDERR_E_NOHELP The caller has asked for help on the command identified by <paramref name="nCmdID" />, but no help is available.
        /// OLECMDERR_E_CANCELED The user canceled the execution of the command.</returns>
        [PreserveSig]
        [return: MarshalAs(UnmanagedType.I4)]
        int Exec(ref Guid pguidCmdGroup, int nCmdID, int nCmdexecopt, [MarshalAs(UnmanagedType.LPArray)] [In] object[] pvaIn, int pvaOut);
    }
}

How can I create a dynamically sized array of structs?

Here is how I would do it in C++

size_t size = 500;
char* dynamicAllocatedString = new char[ size ];

Use same principal for any struct or c++ class.

How to solve "Fatal error: Class 'MySQLi' not found"?

You can check if the mysqli libraries are present by executing this code:

if (!function_exists('mysqli_init') && !extension_loaded('mysqli')) {
    echo 'We don\'t have mysqli!!!';
} else {
    echo 'Phew we have it!';
}

CSS Auto hide elements after 5 seconds

YES!

But you can't do it in the way you may immediately think, because you cant animate or create a transition around the properties you'd otherwise rely on (e.g. display, or changing dimensions and setting to overflow:hidden) in order to correctly hide the element and prevent it from taking up visible space.

Therefore, create an animation for the elements in question, and simply toggle visibility:hidden; after 5 seconds, whilst also setting height and width to zero to prevent the element from still occupying space in the DOM flow.

FIDDLE

CSS

html, body {
    height:100%;
    width:100%;
    margin:0;
    padding:0;
}
#hideMe {
    -moz-animation: cssAnimation 0s ease-in 5s forwards;
    /* Firefox */
    -webkit-animation: cssAnimation 0s ease-in 5s forwards;
    /* Safari and Chrome */
    -o-animation: cssAnimation 0s ease-in 5s forwards;
    /* Opera */
    animation: cssAnimation 0s ease-in 5s forwards;
    -webkit-animation-fill-mode: forwards;
    animation-fill-mode: forwards;
}
@keyframes cssAnimation {
    to {
        width:0;
        height:0;
        overflow:hidden;
    }
}
@-webkit-keyframes cssAnimation {
    to {
        width:0;
        height:0;
        visibility:hidden;
    }
}

HTML

<div id='hideMe'>Wait for it...</div>

Bytes of a string in Java

To avoid try catch, use:

String s = "some text here";
byte[] b = s.getBytes(StandardCharsets.UTF_8);
System.out.println(b.length);

How to convert a Hibernate proxy to a real entity object

I've written following code which cleans object from proxies (if they are not already initialized)

public class PersistenceUtils {

    private static void cleanFromProxies(Object value, List<Object> handledObjects) {
        if ((value != null) && (!isProxy(value)) && !containsTotallyEqual(handledObjects, value)) {
            handledObjects.add(value);
            if (value instanceof Iterable) {
                for (Object item : (Iterable<?>) value) {
                    cleanFromProxies(item, handledObjects);
                }
            } else if (value.getClass().isArray()) {
                for (Object item : (Object[]) value) {
                    cleanFromProxies(item, handledObjects);
                }
            }
            BeanInfo beanInfo = null;
            try {
                beanInfo = Introspector.getBeanInfo(value.getClass());
            } catch (IntrospectionException e) {
                // LOGGER.warn(e.getMessage(), e);
            }
            if (beanInfo != null) {
                for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
                    try {
                        if ((property.getWriteMethod() != null) && (property.getReadMethod() != null)) {
                            Object fieldValue = property.getReadMethod().invoke(value);
                            if (isProxy(fieldValue)) {
                                fieldValue = unproxyObject(fieldValue);
                                property.getWriteMethod().invoke(value, fieldValue);
                            }
                            cleanFromProxies(fieldValue, handledObjects);
                        }
                    } catch (Exception e) {
                        // LOGGER.warn(e.getMessage(), e);
                    }
                }
            }
        }
    }

    public static <T> T cleanFromProxies(T value) {
        T result = unproxyObject(value);
        cleanFromProxies(result, new ArrayList<Object>());
        return result;
    }

    private static boolean containsTotallyEqual(Collection<?> collection, Object value) {
        if (CollectionUtils.isEmpty(collection)) {
            return false;
        }
        for (Object object : collection) {
            if (object == value) {
                return true;
            }
        }
        return false;
    }

    public static boolean isProxy(Object value) {
        if (value == null) {
            return false;
        }
        if ((value instanceof HibernateProxy) || (value instanceof PersistentCollection)) {
            return true;
        }
        return false;
    }

    private static Object unproxyHibernateProxy(HibernateProxy hibernateProxy) {
        Object result = hibernateProxy.writeReplace();
        if (!(result instanceof SerializableProxy)) {
            return result;
        }
        return null;
    }

    @SuppressWarnings("unchecked")
    private static <T> T unproxyObject(T object) {
        if (isProxy(object)) {
            if (object instanceof PersistentCollection) {
                PersistentCollection persistentCollection = (PersistentCollection) object;
                return (T) unproxyPersistentCollection(persistentCollection);
            } else if (object instanceof HibernateProxy) {
                HibernateProxy hibernateProxy = (HibernateProxy) object;
                return (T) unproxyHibernateProxy(hibernateProxy);
            } else {
                return null;
            }
        }
        return object;
    }

    private static Object unproxyPersistentCollection(PersistentCollection persistentCollection) {
        if (persistentCollection instanceof PersistentSet) {
            return unproxyPersistentSet((Map<?, ?>) persistentCollection.getStoredSnapshot());
        }
        return persistentCollection.getStoredSnapshot();
    }

    private static <T> Set<T> unproxyPersistentSet(Map<T, ?> persistenceSet) {
        return new LinkedHashSet<T>(persistenceSet.keySet());
    }

}

I use this function over result of my RPC services (via aspects) and it cleans recursively all result objects from proxies (if they are not initialized).

Extract directory path and filename

You can simply do:

base=$(basename "$fspec")

React eslint error missing in props validation

It seems that the problem is in eslint-plugin-react.

It can not correctly detect what props were mentioned in propTypes if you have annotated named objects via destructuring anywhere in the class.

There was similar problem in the past

Stupid error: Failed to load resource: net::ERR_CACHE_MISS

Google declares that this is not a failure, but some "misleading error reports". This bug will be fixed in version 40 of chrome.

You can read this:

Chromium forum
Chromium forum
Patch

Update statement using with clause

If anyone comes here after me, this is the answer that worked for me.

NOTE: please make to read the comments before using this, this not complete. The best advice for update queries I can give is to switch to SqlServer ;)

update mytable t
set z = (
  with comp as (
    select b.*, 42 as computed 
    from mytable t 
    where bs_id = 1
  )
  select c.computed
  from  comp c
  where c.id = t.id
)

Good luck,

GJ

UML diagram shapes missing on Visio 2013

Microsoft Visio 2013 Standard Edition does not provide UML shapes, you have to upgrade to Microsoft Visio 2013 Professional.

Visio 2013 Professional

MongoDB/Mongoose querying at a specific date?

...5+ years later, I strongly suggest using date-fns instead

import endOfDayfrom 'date-fns/endOfDay'
import startOfDay from 'date-fns/startOfDay'

MyModel.find({
  createdAt: {
    $gte: startOfDay(new Date()),
    $lte: endOfDay(new Date())
  }
})

For those of us using Moment.js

const moment = require('moment')

const today = moment().startOf('day')

MyModel.find({
  createdAt: {
    $gte: today.toDate(),
    $lte: moment(today).endOf('day').toDate()
  }
})

Important: all moments are mutable!

tomorrow = today.add(1, 'days') does not work since it also mutates today. Calling moment(today) solves that problem by implicitly cloning today.

Clear History and Reload Page on Login/Logout Using Ionic Framework

I have found a solution which helped me to get it done. Setting cache-view="false" on ion-view tag resolved my problem.

<ion-view cache-view="false" view-title="My Title!">
  ....
</ion-view>

How do I update pip itself from inside my virtual environment?

Upgrading pip using 'pip install --upgrade pip' does not always work because of the dreaded cert issue: There was a problem confirming the ssl certificate: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version

I like to use the one line command for virtual envs:

curl https://bootstrap.pypa.io/get-pip.py | python -

Or if you want to install it box wide you will need

curl https://bootstrap.pypa.io/get-pip.py | sudo python -

you can give curl a -s flag if you want to silence the output when running in an automation script.

Google Maps API warning: NoApiKeys

Google maps requires an API key for new projects since june 2016. For more information take a look at the Google Developers Blog. Also more information in german you'll find at this blog post from the clickstorm Blog.

How do I compare strings in GoLang?

== is the correct operator to compare strings in Go. However, the strings that you read from STDIN with reader.ReadString do not contain "a", but "a\n" (if you look closely, you'll see the extra line break in your example output).

You can use the strings.TrimRight function to remove trailing whitespaces from your input:

if strings.TrimRight(input, "\n") == "a" {
    // ...
}

CSS how to make an element fade in and then fade out?

A way to do this would be to set the color of the element to black, and then fade to the color of the background like this:

<style> 
p {
animation-name: example;
animation-duration: 2s;
}

@keyframes example {
from {color:black;}
to {color:white;}
}
</style>
<p>I am FADING!</p>

I hope this is what you needed!

How to pass arguments within docker-compose?

Now docker-compose supports variable substitution.

Compose uses the variable values from the shell environment in which docker-compose is run. For example, suppose the shell contains POSTGRES_VERSION=9.3 and you supply this configuration in your docker-compose.yml file:

db:
  image: "postgres:${POSTGRES_VERSION}"

When you run docker-compose up with this configuration, Compose looks for the POSTGRES_VERSION environment variable in the shell and substitutes its value in. For this example, Compose resolves the image to postgres:9.3 before running the configuration.

About "*.d.ts" in TypeScript

This answer assumes you have some JavaScript that you don't want to convert to TypeScript, but you want to benefit from type checking with minimal changes to your .js. A .d.ts file is very much like a C or C++ header file. Its purpose is to define an interface. Here is an example:

mashString.d.ts

/** Makes a string harder to read. */
declare function mashString(
    /** The string to obscure */
    str: string
):string;
export = mashString;

mashString.js

// @ts-check
/** @type {import("./mashString")} */
module.exports = (str) => [...str].reverse().join("");

main.js

// @ts-check
const mashString = require("./mashString");
console.log(mashString("12345"));

The relationship here is: mashString.d.ts defines an interface, mashString.js implements the interface and main.js uses the interface.

To get the type checking to work you add // @ts-check to your .js files. But this only checks that main.js uses the interface correctly. To also ensure that mashString.js implements it correctly we add /** @type {import("./mashString")} */ before the export.

You can create your initial .d.ts files using tsc -allowJs main.js -d then edit them as required manually to improve the type checking and documentation.

In most cases the implementation and interface have the same name, here mashString. But you can have alternative implementations. For example we could rename mashString.js to reverse.js and have an alternative encryptString.js.

How do I use a 32-bit ODBC driver on 64-bit Server 2008 when the installer doesn't create a standard DSN?

A lot of these answers are pretty old, so I thought I would update with a solution that I think is helpful.

Our issue was similar to OP's, we upgraded 32 bit XP machines to 64 bit windows 7 and our application software that uses a 32 bit ODBC driver stopped being able to write to our database.

Turns out, there are two ODBC Data Source Managers, one for 32 bit and one for 64 bit. So I had to run the 32 bit version which is found in C:\Windows\SysWOW64\odbcad32.exe. Inside the ODBC Data Source Manager, I was able to go to the System DSN tab and Add my driver to the list using the Add button. (You can check the Drivers tab to see a list of the drivers you can add, if your driver isn't in this list then you may need to install it).

The next issue was the software that we ran was compiled to use 'Any CPU'. This would see the operating system was 64 bit, so it would look at the 64 bit ODBC Data Sources. So I had to force the program to compile as an x86 program, which then tells it to look at the 32 bit ODBC Data Sources. To set your program to x86, in Visual Studio go to your project properties and under the build tab at the top there is a platform drop down list, and choose x86. If you don't have the source code and can't compile the program as x86, you might be able to right click the program .exe and go to the compatibility tab and choose a compatibility that works for you.

Once I had the drivers added and the program pointing to the right drivers, everything worked like it use to. Hopefully this helps anyone working with older software.

use std::fill to populate vector with increasing numbers

We can use generate function which exists in algorithm header file.

Code Snippet :

#include<bits/stdc++.h>
using namespace std;


int main()
{
    ios::sync_with_stdio(false);

    vector<int>v(10);

    int n=0;

    generate(v.begin(), v.end(), [&n] { return n++;});

    for(auto item : v)
    {
      cout<<item<<" ";
    }
    cout<<endl;

    return 0;
}

Tkinter scrollbar for frame

"Am i doing it right?Is there better/smarter way to achieve the output this code gave me?"

Generally speaking, yes, you're doing it right. Tkinter has no native scrollable container other than the canvas. As you can see, it's really not that difficult to set up. As your example shows, it only takes 5 or 6 lines of code to make it work -- depending on how you count lines.

"Why must i use grid method?(i tried place method, but none of the labels appear on the canvas?)"

You ask about why you must use grid. There is no requirement to use grid. Place, grid and pack can all be used. It's simply that some are more naturally suited to particular types of problems. In this case it looks like you're creating an actual grid -- rows and columns of labels -- so grid is the natural choice.

"What so special about using anchor='nw' when creating window on canvas?"

The anchor tells you what part of the window is positioned at the coordinates you give. By default, the center of the window will be placed at the coordinate. In the case of your code above, you want the upper left ("northwest") corner to be at the coordinate.

How to use icons and symbols from "Font Awesome" on Native Android Application

There is small and useful library designed for this purposes:

dependencies {
    compile 'com.shamanland:fonticon:0.1.9'
}

Get demo on Google Play.

enter image description here

You can easily add font-based icon in your layout:

<com.shamanland.fonticon.FontIconView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/ic_android"
    android:textSize="@dimen/icon_size"
    android:textColor="@color/icon_color"
    />

You can inflate font-icon as Drawable from xml:

<?xml version="1.0" encoding="utf-8"?>
<font-icon
    xmlns:android="http://schemas.android.com/apk/res-auto"
    android:text="@string/ic_android"
    android:textSize="@dimen/big_icon_size"
    android:textColor="@color/green_170"
    />

Java code:

Drawable icon = FontIconDrawable.inflate(getResources(), R.xml.ic_android);

Links:

How to center and crop an image to always appear in square shape with CSS?

<div style="specify your dimension:overflow:hidden">
    <div style="margin-top:-50px">
       <img ...  />
    </div>
</div>

The above will crop 50px from the top of the image. You may want to compute to come up wit a top margin that will fit your requirements based on the dimension of the image.

To crop from the bottom simply specify the height of the outer div and remove the inner div. Apply the same principle to crop from the sides.

Java, Simplified check if int array contains int

You could simply use ArrayUtils.contains from Apache Commons Lang library.

public boolean contains(final int[] array, final int key) {     
    return ArrayUtils.contains(array, key);
}

How to remove/delete a large file from commit history in Git repository?

This will remove it from your history

git filter-branch --force --index-filter 'git rm -r --cached --ignore-unmatch bigfile.txt' --prune-empty --tag-name-filter cat -- --all

What is the difference between Forking and Cloning on GitHub?

In a nutshell, "fork" creates a copy of the project hosted on your own GitHub account.

"Clone" uses git software on your computer to download the source code and it's entire version history unto that computer

Switching from zsh to bash on OSX, and back again?

In Mac OS Catalina default interactive shell is zsh. To change shell to zsh from bash:

chsh -s /bin/zsh

Then you need to enter your Mac password. Quit the terminal and reopen it. To check whether it's changed successfully to ssh, issue the following command.

echo $SHELL

If the result is /bin/zsh, your task is completed.

To change it back to bash, issue the following command on terminal.

chsh -s /bin/bash

Verify it again using echo $SHELL. Then result should be /bin/bash.

'python3' is not recognized as an internal or external command, operable program or batch file

For Python 27

virtualenv -p C:\Python27\python.exe django_concurrent_env

For Pyton36

 virtualenv -p C:\Python36\python.exe django_concurrent_env

Is there a better way to refresh WebView?

try this :

mWebView.loadUrl(mWebView.getUrl().toString());

SQL - Select first 10 rows only?

Oracle

WHERE ROWNUM <= 10  and whatever_else ;

ROWNUM is a magic variable which contains each row's sequence number 1..n.

What does '&' do in a C++ declaration?

One way to look at the & (reference) operator in c++ is that is merely a syntactic sugar to a pointer. For example, the following are roughly equivalent:

void foo(int &x)
{
    x = x + 1;
}

void foo(int *x)
{
    *x = *x + 1;
}

The more useful is when you're dealing with a class, so that your methods turn from x->bar() to x.bar().

The reason I said roughly is that using references imposes additional compile-time restrictions on what you can do with the reference, in order to protect you from some of the problems caused when dealing with pointers. For instance, you can't accidentally change the pointer, or use the pointer in any way other than to reference the singular object you've been passed.

Simple If/Else Razor Syntax

Just use this for the closing tag:

  @:</tr>

And leave your if/else as is.

Seems like the if statement doesn't wanna' work.

It works fine. You're working in 2 language-spaces here, it seems only proper not to split open/close sandwiches over the border.

Google Play on Android 4.0 emulator

It is simple for me i downloaded the apk file in my computer and drag that file to emulator it install the google play for me Hope it help some one

Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine

The first solution I can think of, is to use ViewBag to store the values that must be rendered.

Onestly I never tried if this work from a partial view, but it should imo.

What is the Linux equivalent to DOS pause?

read without any parameters will only continue if you press enter. The DOS pause command will continue if you press any key. Use read –n1 if you want this behaviour.

Server http:/localhost:8080 requires a user name and a password. The server says: XDB

Just change your default port 8080 to something else like below example

SQL> begin
 2   dbms_xdb.sethttpport('9090');
 3   end;
 4  /

How to get a JavaScript object's class?

Any object in JavaScript is created based on a constructor function. And each function, including a constructor one, owns a name, which we can easily read:

class Person {
  type = "developer";
}
let p = new Person();

p.constructor.name // Person

Adding a column to a data.frame

Data.frame[,'h_new_column'] <- as.integer(Data.frame[,'h_no'], breaks=c(1, 4, 7))

How to check list A contains any value from list B?

If you didn't care about performance, you could try:

a.Any(item => b.Contains(item))
// or, as in the column using a method group
a.Any(b.Contains)

But I would try this first:

a.Intersect(b).Any()

Unable to run Java GUI programs with Ubuntu

This command worked for me.

Sudo dnf install java-1.8.0-openjdk (Fedora)

Sudo apt-get install java-1.8.0-openjdk

Should work for Ubuntu.

What is the difference between char array and char pointer in C?

char p[3] = "hello" ? should be char p[6] = "hello" remember there is a '\0' char in the end of a "string" in C.

anyway, array in C is just a pointer to the first object of an adjust objects in the memory. the only different s are in semantics. while you can change the value of a pointer to point to a different location in the memory an array, after created, will always point to the same location.
also when using array the "new" and "delete" is automatically done for you.

Days between two dates?

Referencing my comments on other answers. This is how I would work out the difference in days based on 24 hours and calender days. the days attribute works well for 24 hours and the function works best for calendar checks.

from datetime import timedelta, datetime

def cal_days_diff(a,b):

    A = a.replace(hour = 0, minute = 0, second = 0, microsecond = 0)
    B = b.replace(hour = 0, minute = 0, second = 0, microsecond = 0)
    return (A - B).days

if __name__ == '__main__':

    x = datetime(2013, 06, 18, 16, 00)
    y = datetime(2013, 06, 19, 2, 00)

    print (y - x).days          # 0
    print cal_days_diff(y, x)   # 1 

    z = datetime(2013, 06, 20, 2, 00)

    print (z - x).days          # 1
    print cal_days_diff(z, x)   # 2 

Pros/cons of using redux-saga with ES6 generators vs redux-thunk with ES2017 async/await

An easier way is to use redux-auto.

from the documantasion

redux-auto fixed this asynchronous problem simply by allowing you to create an "action" function that returns a promise. To accompany your "default" function action logic.

  1. No need for other Redux async middleware. e.g. thunk, promise-middleware, saga
  2. Easily allows you to pass a promise into redux and have it managed for you
  3. Allows you to co-locate external service calls with where they will be transformed
  4. Naming the file "init.js" will call it once at app start. This is good for loading data from the server at start

The idea is to have each action in a specific file. co-locating the server call in the file with reducer functions for "pending", "fulfilled" and "rejected". This makes handling promises very easy.

It also automatically attaches a helper object(called "async") to the prototype of your state, allowing you to track in your UI, requested transitions.

How to read file binary in C#?

Quick and dirty version:

byte[] fileBytes = File.ReadAllBytes(inputFilename);
StringBuilder sb = new StringBuilder();

foreach(byte b in fileBytes)
{
    sb.Append(Convert.ToString(b, 2).PadLeft(8, '0'));  
}

File.WriteAllText(outputFilename, sb.ToString());

No mapping found for HTTP request with URI Spring MVC

<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

Hey Please use / in your web.xml (instead of /*)

Value cannot be null. Parameter name: source

This exception will be returned if you attempt to count values in a null collection.

For example the below works when Errors is not null, however if Errors is null then the Value cannot be null. Parameter name: source exception occurs.

if (graphQLResponse.Errors.Count() > 0)

This exception can be avoided by checking for null instead.

if (graphQLResponse.Errors != null)

When should I use the new keyword in C++?

If you are writing in C++ you are probably writing for performance. Using new and the free store is much slower than using the stack (especially when using threads) so only use it when you need it.

As others have said, you need new when your object needs to live outside the function or object scope, the object is really large or when you don't know the size of an array at compile time.

Also, try to avoid ever using delete. Wrap your new into a smart pointer instead. Let the smart pointer call delete for you.

There are some cases where a smart pointer isn't smart. Never store std::auto_ptr<> inside a STL container. It will delete the pointer too soon because of copy operations inside the container. Another case is when you have a really large STL container of pointers to objects. boost::shared_ptr<> will have a ton of speed overhead as it bumps the reference counts up and down. The better way to go in that case is to put the STL container into another object and give that object a destructor that will call delete on every pointer in the container.

Does IE9 support console.log, and is it a real function?

After reading the article from Marc Cliament's comment above, I've now changed my all-purpose cross-browser console.log function to look like this:

function log()
{
    "use strict";

    if (typeof(console) !== "undefined" && console.log !== undefined)
    {
        try
        {
            console.log.apply(console, arguments);
        }
        catch (e)
        {
            var log = Function.prototype.bind.call(console.log, console);
            log.apply(console, arguments);
        }
    }
}

Generate random number between two numbers in JavaScript

function randomIntFromInterval(min, max) { // min and max included 
  return Math.floor(Math.random() * (max - min + 1) + min);
}

What it does "extra" is it allows random intervals that do not start with 1. So you can get a random number from 10 to 15 for example. Flexibility.

How to have jQuery restrict file types on upload?

No plugin necessary for just this task. Cobbled this together from a couple other scripts:

$('INPUT[type="file"]').change(function () {
    var ext = this.value.match(/\.(.+)$/)[1];
    switch (ext) {
        case 'jpg':
        case 'jpeg':
        case 'png':
        case 'gif':
            $('#uploadButton').attr('disabled', false);
            break;
        default:
            alert('This is not an allowed file type.');
            this.value = '';
    }
});

The trick here is to set the upload button to disabled unless and until a valid file type is selected.

How to detect orientation change in layout in Android?

For loading the layout in layout-land folder means you have two separate layouts then you have to make setContentView in onConfigurationChanged method.

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        setContentView(R.layout.yourxmlinlayout-land);
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        setContentView(R.layout.yourxmlinlayoutfolder);
    }
}

If you have only one layout then no necessary to make setContentView in This method. simply

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
}

Create URL from a String

URL url = new URL(yourUrl, "/api/v1/status.xml");

According to the javadocs this constructor just appends whatever resource to the end of your domain, so you would want to create 2 urls:

URL domain = new URL("http://example.com");
URL url = new URL(domain + "/files/resource.xml");

Sources: http://docs.oracle.com/javase/6/docs/api/java/net/URL.html

convert big endian to little endian in C [without using provided func]

By including:

#include <byteswap.h>

you can get an optimized version of machine-dependent byte-swapping functions. Then, you can easily use the following functions:

__bswap_32 (uint32_t input)

or

__bswap_16 (uint16_t input)

Android: combining text & image on a Button or ImageButton

You can use drawableTop (also drawableLeft, etc) for the image and set text below the image by adding the gravity left|center_vertical

<Button
            android:id="@+id/btn_video"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:background="@null"
            android:drawableTop="@drawable/videos"
            android:gravity="left|center_vertical"
            android:onClick="onClickFragment"
            android:text="Videos"
            android:textColor="@color/white" />

Arduino error: does not name a type?

The two includes you mention in your comment are essential. 'does not name a type' just means there is no definition for that identifier visible to the compiler. If there are errors in the LCD library you mention, then those need to be addressed - omitting the #include will definitely not fix it!

Two notes from experience which might be helpful:

  1. You need to add all #include's to the main sketch - irrespective of whether they are included via another #include.

  2. If you add files to the library folder, the Arduino IDE must be restarted before those new files will be visible.

Sourcetree - undo unpushed commits

  1. Right click on the commit you like to reset to (not the one you like to delete!)
  2. Select "Reset master to this commit"
  3. Select "Soft" reset.

A soft reset will keep your local changes.

Source: https://answers.atlassian.com/questions/153791/how-should-i-remove-push-commit-from-sourcetree

Edit

About git revert: This command creates a new commit which will undo other commits. E.g. if you have a commit which adds a new file, git revert could be used to make a commit which will delete the new file.

About applying a soft reset: Assume you have the commits A to E (A---B---C---D---E) and you like to delete the last commit (E). Then you can do a soft reset to commit D. With a soft reset commit E will be deleted from git but the local changes will be kept. There are more examples in the git reset documentation.

How to set some xlim and ylim in Seaborn lmplot facetgrid

You need to get hold of the axes themselves. Probably the cleanest way is to change your last row:

lm = sns.lmplot('X','Y',df,col='Z',sharex=False,sharey=False)

Then you can get hold of the axes objects (an array of axes):

axes = lm.axes

After that you can tweak the axes properties

axes[0,0].set_ylim(0,)
axes[0,1].set_ylim(0,)

creates:

enter image description here