Programs & Examples On #Red gate ants

How to convert UTF8 string to byte array?

The logic of encoding Unicode in UTF-8 is basically:

  • Up to 4 bytes per character can be used. The fewest number of bytes possible is used.
  • Characters up to U+007F are encoded with a single byte.
  • For multibyte sequences, the number of leading 1 bits in the first byte gives the number of bytes for the character. The rest of the bits of the first byte can be used to encode bits of the character.
  • The continuation bytes begin with 10, and the other 6 bits encode bits of the character.

Here's a function I wrote a while back for encoding a JavaScript UTF-16 string in UTF-8:

function toUTF8Array(str) {
    var utf8 = [];
    for (var i=0; i < str.length; i++) {
        var charcode = str.charCodeAt(i);
        if (charcode < 0x80) utf8.push(charcode);
        else if (charcode < 0x800) {
            utf8.push(0xc0 | (charcode >> 6), 
                      0x80 | (charcode & 0x3f));
        }
        else if (charcode < 0xd800 || charcode >= 0xe000) {
            utf8.push(0xe0 | (charcode >> 12), 
                      0x80 | ((charcode>>6) & 0x3f), 
                      0x80 | (charcode & 0x3f));
        }
        // surrogate pair
        else {
            i++;
            // UTF-16 encodes 0x10000-0x10FFFF by
            // subtracting 0x10000 and splitting the
            // 20 bits of 0x0-0xFFFFF into two halves
            charcode = 0x10000 + (((charcode & 0x3ff)<<10)
                      | (str.charCodeAt(i) & 0x3ff));
            utf8.push(0xf0 | (charcode >>18), 
                      0x80 | ((charcode>>12) & 0x3f), 
                      0x80 | ((charcode>>6) & 0x3f), 
                      0x80 | (charcode & 0x3f));
        }
    }
    return utf8;
}

How to enable curl in xampp?

For XAMPP on MACOS or Linux, remove the semicolon in php.ini file after extension=curl.so

How do I do a case-insensitive string comparison?

Using Python 2, calling .lower() on each string or Unicode object...

string1.lower() == string2.lower()

...will work most of the time, but indeed doesn't work in the situations @tchrist has described.

Assume we have a file called unicode.txt containing the two strings S?s?f?? and S?S?F?S. With Python 2:

>>> utf8_bytes = open("unicode.txt", 'r').read()
>>> print repr(utf8_bytes)
'\xce\xa3\xce\xaf\xcf\x83\xcf\x85\xcf\x86\xce\xbf\xcf\x82\n\xce\xa3\xce\x8a\xce\xa3\xce\xa5\xce\xa6\xce\x9f\xce\xa3\n'
>>> u = utf8_bytes.decode('utf8')
>>> print u
S?s?f??
S?S?F?S

>>> first, second = u.splitlines()
>>> print first.lower()
s?s?f??
>>> print second.lower()
s?s?f?s
>>> first.lower() == second.lower()
False
>>> first.upper() == second.upper()
True

The S character has two lowercase forms, ? and s, and .lower() won't help compare them case-insensitively.

However, as of Python 3, all three forms will resolve to ?, and calling lower() on both strings will work correctly:

>>> s = open('unicode.txt', encoding='utf8').read()
>>> print(s)
S?s?f??
S?S?F?S

>>> first, second = s.splitlines()
>>> print(first.lower())
s?s?f??
>>> print(second.lower())
s?s?f??
>>> first.lower() == second.lower()
True
>>> first.upper() == second.upper()
True

So if you care about edge-cases like the three sigmas in Greek, use Python 3.

(For reference, Python 2.7.3 and Python 3.3.0b1 are shown in the interpreter printouts above.)

Can´t run .bat file under windows 10

There is no inherent reason that a simple batch file would run in XP but not Windows 10. It is possible you are referencing a command or a 3rd party utility that no longer exists. To know more about what is actually happening, you will need to do one of the following:

  • Add a pause to the batch file so that you can see what is happening before it exits.
    1. Right click on one of the .bat files and select "edit". This will open the file in notepad.
    2. Go to the very end of the file and add a new line by pressing "enter".
    3. type pause.
    4. Save the file.
    5. Run the file again using the same method you did before.

- OR -

  • Run the batch file from a static command prompt so the window does not close.
    1. In the folder where the .bat files are located, hold down the "shift" key and right click in the white space.
    2. Select "Open Command Window Here".
    3. You will now see a new command prompt. Type in the name of the batch file and press enter.

Once you have done this, I recommend creating a new question with the output you see after using one of the methods above.

How do I detect whether a Python variable is a function?

Whatever function is a class so you can take the name of the class of instance x and compare:


if(x.__class__.__name__ == 'function'):
     print "it's a function"

How do I close an open port from the terminal on the Mac?

  1. First find out the Procees id (pid) which has occupied the required port.(e.g 5434)

    ps aux | grep 5434

2.kill that process

   kill -9 <pid>

jQuery Ajax calls and the Html.AntiForgeryToken()

I'm using a ajax post to run a delete method (happens to be from a visjs timeline but that's not relelvant). This is what I sis:

This is my Index.cshtml

@Scripts.Render("~/bundles/schedule")
@Styles.Render("~/bundles/visjs")
@Html.AntiForgeryToken()

<!-- div to attach schedule to -->
<div id='schedule'></div>

<!-- div to attach popups to -->
<div id='dialog-popup'></div>

All I added here was @Html.AntiForgeryToken() to make the token appear in the page

Then in my ajax post I used:

$.ajax(
    {
        type: 'POST',
        url: '/ScheduleWorks/Delete/' + item.id,
        data: {
            '__RequestVerificationToken': 
            $("input[name='__RequestVerificationToken']").val()
              }
     }
);

Which adds the token value, scraped off the page, to the fields posted

Before this I tried putting the value in the headers but I got the same error

Feel free to post improvements. This certainly seems to be a simple approach that I can understand

diff to output only the file names

On my linux system to get just the filenames

diff -q /dir1 /dir2|cut -f2 -d' '

Sending Arguments To Background Worker?

You can use the DoWorkEventArgs.Argument property.

A full example (even using an int argument) can be found on Microsoft's site:

Unit tests vs Functional tests

The basic distinction, though, is that functional tests test the application from the outside, from the point of view of the user. Unit tests test the application from the inside, from the point of view of the programmer. Functional tests should help you build an application with the right functionality, and guarantee you never accidentally break it. Unit tests should help you to write code that’s clean and bug free.

Taken from "Python TDD" book by Harry Percival

<modules runAllManagedModulesForAllRequests="true" /> Meaning

Modules Preconditions:

The IIS core engine uses preconditions to determine when to enable a particular module. Performance reasons, for example, might determine that you only want to execute managed modules for requests that also go to a managed handler. The precondition in the following example (precondition="managedHandler") only enables the forms authentication module for requests that are also handled by a managed handler, such as requests to .aspx or .asmx files:

<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" preCondition="managedHandler" />

If you remove the attribute precondition="managedHandler", Forms Authentication also applies to content that is not served by managed handlers, such as .html, .jpg, .doc, but also for classic ASP (.asp) or PHP (.php) extensions. See "How to Take Advantage of IIS Integrated Pipeline" for an example of enabling ASP.NET modules to run for all content.

You can also use a shortcut to enable all managed (ASP.NET) modules to run for all requests in your application, regardless of the "managedHandler" precondition.

To enable all managed modules to run for all requests without configuring each module entry to remove the "managedHandler" precondition, use the runAllManagedModulesForAllRequests property in the <modules> section:

<modules runAllManagedModulesForAllRequests="true" />    

When you use this property, the "managedHandler" precondition has no effect and all managed modules run for all requests.

Copied from IIS Modules Overview: Preconditions

MySQL - how to front pad zip code with "0"?

Store your zipcodes as CHAR(5) instead of a numeric type, or have your application pad it with zeroes when you load it from the DB. A way to do it with PHP using sprintf():

echo sprintf("%05d", 205); // prints 00205
echo sprintf("%05d", 1492); // prints 01492

Or you could have MySQL pad it for you with LPAD():

SELECT LPAD(zip, 5, '0') as zipcode FROM table;

Here's a way to update and pad all rows:

ALTER TABLE `table` CHANGE `zip` `zip` CHAR(5); #changes type
UPDATE table SET `zip`=LPAD(`zip`, 5, '0'); #pads everything

Using a string variable as a variable name

You will be much happier using a dictionary instead:

my_data = {}
foo = "hello"
my_data[foo] = "goodbye"
assert my_data["hello"] == "goodbye"

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

Jquery Ajax Posting json to webservice

I tried Dave Ward's solution. The data part was not being sent from the browser in the payload part of the post request as the contentType is set to "application/json". Once I removed this line everything worked great.

var markers = [{ "position": "128.3657142857143", "markerPosition": "7" },

               { "position": "235.1944023323615", "markerPosition": "19" },

               { "position": "42.5978231292517", "markerPosition": "-3" }];

$.ajax({

    type: "POST",
    url: "/webservices/PodcastService.asmx/CreateMarkers",
    // The key needs to match your method's input parameter (case-sensitive).
    data: JSON.stringify({ Markers: markers }),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data){alert(data);},
    failure: function(errMsg) {
        alert(errMsg);
    }
});

Broadcast receiver for checking internet connection in android app

Complete answer here

Menifest file

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />

<receiver android:name=".NetworkStateReceiver">
    <intent-filter>
      <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
    </intent-filter>
  </receiver>

BroadecardReceiver class

public class NetworkStateReceiver extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
     Log.d("app","Network connectivity change");
     if(intent.getExtras()!=null) {
        NetworkInfo ni=(NetworkInfo) intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO);
        if(ni!=null && ni.getState()==NetworkInfo.State.CONNECTED) {
            Log.i("app","Network "+ni.getTypeName()+" connected");
        } else if(intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,Boolean.FALSE)) {
            Log.d("app","There's no network connectivity");
        }
   }
}

Registering receiver in MainActivity

@Override
protected void onResume() {
    super.onResume();
    IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
    registerReceiver(networkReceiver, intentFilter);
}

@Override
protected void onPause() {
    super.onPause();
    if (networkReceiver != null)
        unregisterReceiver(networkReceiver);
}

Enjoy!

What is the cleanest way to ssh and run multiple commands in Bash?

For anyone stumbling over here like me - I had success with escaping the semicolon and the newline:

First step: the semicolon. This way, we do not break the ssh command:

ssh <host> echo test\;ls
                    ^ backslash!

Listed the remote hosts /home directory (logged in as root), whereas

ssh <host> echo test;ls
                    ^ NO backslash

listed the current working directory.

Next step: breaking up the line:

                      v another backslash!
ssh <host> echo test\;\
ls

This again listed the remote working directory - improved formatting:

ssh <host>\
  echo test\;\
  ls

If really nicer than here document or quotes around broken lines - well, not me to decide...

(Using bash, Ubuntu 14.04 LTS.)

How to programmatically send a 404 response with Express/Node?

According to the site I'll post below, it's all how you set up your server. One example they show is this:

var http = require("http");
var url = require("url");

function start(route, handle) {
  function onRequest(request, response) {
    var pathname = url.parse(request.url).pathname;
    console.log("Request for " + pathname + " received.");

    route(handle, pathname, response);
  }

  http.createServer(onRequest).listen(8888);
  console.log("Server has started.");
}

exports.start = start;

and their route function:

function route(handle, pathname, response) {
  console.log("About to route a request for " + pathname);
  if (typeof handle[pathname] === 'function') {
    handle[pathname](response);
  } else {
    console.log("No request handler found for " + pathname);
    response.writeHead(404, {"Content-Type": "text/plain"});
    response.write("404 Not found");
    response.end();
  }
}

exports.route = route;

This is one way. http://www.nodebeginner.org/

From another site, they create a page and then load it. This might be more of what you're looking for.

fs.readFile('www/404.html', function(error2, data) {
            response.writeHead(404, {'content-type': 'text/html'});
            response.end(data);
        });

http://blog.poweredbyalt.net/?p=81

How to read lines of a file in Ruby

It is because of the endlines in each lines. Use the chomp method in ruby to delete the endline '\n' or 'r' at the end.

line_num=0
File.open('xxx.txt').each do |line|
  print "#{line_num += 1} #{line.chomp}"
end

How do I center a window onscreen in C#?

You can use the Screen.PrimaryScreen.Bounds to retrieve the size of the primary monitor (or inspect the Screen object to retrieve all monitors). Use those with MyForms.Bounds to figure out where to place your form.

What do the result codes in SVN mean?

Also note that a result code in the second column refers to the properties of the file. For example:

U   filename.1
 U  filename.2  
UU  filename.3

filename.1: the file was updated
filename.2: a property or properties on the file (such as svn:keywords) was updated
filename.3: both the file and its properties were updated

How to create custom exceptions in Java?

To define a checked exception you create a subclass (or hierarchy of subclasses) of java.lang.Exception. For example:

public class FooException extends Exception {
  public FooException() { super(); }
  public FooException(String message) { super(message); }
  public FooException(String message, Throwable cause) { super(message, cause); }
  public FooException(Throwable cause) { super(cause); }
}

Methods that can potentially throw or propagate this exception must declare it:

public void calculate(int i) throws FooException, IOException;

... and code calling this method must either handle or propagate this exception (or both):

try {
  int i = 5;
  myObject.calculate(5);
} catch(FooException ex) {
  // Print error and terminate application.
  ex.printStackTrace();
  System.exit(1);
} catch(IOException ex) {
  // Rethrow as FooException.
  throw new FooException(ex);
}

You'll notice in the above example that IOException is caught and rethrown as FooException. This is a common technique used to encapsulate exceptions (typically when implementing an API).

Sometimes there will be situations where you don't want to force every method to declare your exception implementation in its throws clause. In this case you can create an unchecked exception. An unchecked exception is any exception that extends java.lang.RuntimeException (which itself is a subclass of java.lang.Exception):

public class FooRuntimeException extends RuntimeException {
  ...
}

Methods can throw or propagate FooRuntimeException exception without declaring it; e.g.

public void calculate(int i) {
  if (i < 0) {
    throw new FooRuntimeException("i < 0: " + i);
  }
}

Unchecked exceptions are typically used to denote a programmer error, for example passing an invalid argument to a method or attempting to breach an array index bounds.

The java.lang.Throwable class is the root of all errors and exceptions that can be thrown within Java. java.lang.Exception and java.lang.Error are both subclasses of Throwable. Anything that subclasses Throwable may be thrown or caught. However, it is typically bad practice to catch or throw Error as this is used to denote errors internal to the JVM that cannot usually be "handled" by the programmer (e.g. OutOfMemoryError). Likewise you should avoid catching Throwable, which could result in you catching Errors in addition to Exceptions.

How to provide a file download from a JSF backing bean?

Introduction

You can get everything through ExternalContext. In JSF 1.x, you can get the raw HttpServletResponse object by ExternalContext#getResponse(). In JSF 2.x, you can use the bunch of new delegate methods like ExternalContext#getResponseOutputStream() without the need to grab the HttpServletResponse from under the JSF hoods.

On the response, you should set the Content-Type header so that the client knows which application to associate with the provided file. And, you should set the Content-Length header so that the client can calculate the download progress, otherwise it will be unknown. And, you should set the Content-Disposition header to attachment if you want a Save As dialog, otherwise the client will attempt to display it inline. Finally just write the file content to the response output stream.

Most important part is to call FacesContext#responseComplete() to inform JSF that it should not perform navigation and rendering after you've written the file to the response, otherwise the end of the response will be polluted with the HTML content of the page, or in older JSF versions, you will get an IllegalStateException with a message like getoutputstream() has already been called for this response when the JSF implementation calls getWriter() to render HTML.

Turn off ajax / don't use remote command!

You only need to make sure that the action method is not called by an ajax request, but that it is called by a normal request as you fire with <h:commandLink> and <h:commandButton>. Ajax requests and remote commands are handled by JavaScript which in turn has, due to security reasons, no facilities to force a Save As dialogue with the content of the ajax response.

In case you're using e.g. PrimeFaces <p:commandXxx>, then you need to make sure that you explicitly turn off ajax via ajax="false" attribute. In case you're using ICEfaces, then you need to nest a <f:ajax disabled="true" /> in the command component.

Generic JSF 2.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    ExternalContext ec = fc.getExternalContext();

    ec.responseReset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    ec.setResponseContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ExternalContext#getMimeType() for auto-detection based on filename.
    ec.setResponseContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = ec.getResponseOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Generic JSF 1.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();

    response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    response.setContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
    response.setContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = response.getOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Common static file example

In case you need to stream a static file from the local disk file system, substitute the code as below:

File file = new File("/path/to/file.ext");
String fileName = file.getName();
String contentType = ec.getMimeType(fileName); // JSF 1.x: ((ServletContext) ec.getContext()).getMimeType(fileName);
int contentLength = (int) file.length();

// ...

Files.copy(file.toPath(), output);

Common dynamic file example

In case you need to stream a dynamically generated file, such as PDF or XLS, then simply provide output there where the API being used expects an OutputStream.

E.g. iText PDF:

String fileName = "dynamic.pdf";
String contentType = "application/pdf";

// ...

Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, output);
document.open();
// Build PDF content here.
document.close();

E.g. Apache POI HSSF:

String fileName = "dynamic.xls";
String contentType = "application/vnd.ms-excel";

// ...

HSSFWorkbook workbook = new HSSFWorkbook();
// Build XLS content here.
workbook.write(output);
workbook.close();

Note that you cannot set the content length here. So you need to remove the line to set response content length. This is technically no problem, the only disadvantage is that the enduser will be presented an unknown download progress. In case this is important, then you really need to write to a local (temporary) file first and then provide it as shown in previous chapter.

Utility method

If you're using JSF utility library OmniFaces, then you can use one of the three convenient Faces#sendFile() methods taking either a File, or an InputStream, or a byte[], and specifying whether the file should be downloaded as an attachment (true) or inline (false).

public void download() throws IOException {
    Faces.sendFile(file, true);
}

Yes, this code is complete as-is. You don't need to invoke responseComplete() and so on yourself. This method also properly deals with IE-specific headers and UTF-8 filenames. You can find source code here.

Tracking Google Analytics Page Views with AngularJS

app.run(function ($rootScope, $location) {
    $rootScope.$on('$routeChangeSuccess', function(){
        ga('send', 'pageview', $location.path());
    });
});

How to ignore whitespace in a regular expression subject string?

You can stick optional whitespace characters \s* in between every other character in your regex. Although granted, it will get a bit lengthy.

/cats/ -> /c\s*a\s*t\s*s/

How to list all Git tags?

Listing the available tags in Git is straightforward. Just type git tag (with optional -l or --list).

$ git tag
v5.5
v6.5

You can also search for tags that match a particular pattern.

$ git tag -l "v1.8.5*"
v1.8.5
v1.8.5-rc0
v1.8.5-rc1
v1.8.5-rc2

Getting latest tag on git repository

The command finds the most recent tag that is reachable from a commit. If the tag points to the commit, then only the tag is shown. Otherwise, it suffixes the tag name with the number of additional commits on top of the tagged object and the abbreviated object name of the most recent commit.

git describe

With --abbrev set to 0, the command can be used to find the closest tagname without any suffix:

git describe --abbrev=0

Other examples:

git describe --abbrev=0 --tags # gets tag from current branch
git describe --tags `git rev-list --tags --max-count=1` // gets tags across all branches, not just the current branch

How to prune local git tags that don't exist on remote

To put it simple, if you are trying to do something like git fetch -p -t, it will not work starting with git version 1.9.4.

However, there is a simple workaround that still works in latest versions:

git tag -l | xargs git tag -d  // remove all local tags
git fetch -t                   // fetch remote tags

How do I select and store columns greater than a number in pandas?

Sample DF:

In [79]: df = pd.DataFrame(np.random.randint(5, 15, (10, 3)), columns=list('abc'))

In [80]: df
Out[80]:
    a   b   c
0   6  11  11
1  14   7   8
2  13   5  11
3  13   7  11
4  13   5   9
5   5  11   9
6   9   8   6
7   5  11  10
8   8  10  14
9   7  14  13

present only those rows where b > 10

In [81]: df[df.b > 10]
Out[81]:
   a   b   c
0  6  11  11
5  5  11   9
7  5  11  10
9  7  14  13

Minimums (for all columns) for the rows satisfying b > 10 condition

In [82]: df[df.b > 10].min()
Out[82]:
a     5
b    11
c     9
dtype: int32

Minimum (for the b column) for the rows satisfying b > 10 condition

In [84]: df.loc[df.b > 10, 'b'].min()
Out[84]: 11

UPDATE: starting from Pandas 0.20.1 the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers.

text box input height

Just use CSS to increase it's height:

<input type="text" style="height:30px;" name="item" align="left" />

Or, often times, you want to increase it's height by using padding instead of specifying an exact height:

<input type="text" style="padding: 5px;" name="item" align="left" />

Add/remove class with jquery based on vertical scroll?

Is this value intended? if (scroll <= 500) { ... This means it's happening from 0 to 500, and not 500 and greater. In the original post you said "after the user scrolls down a little"

Apply vs transform on a group object

I am going to use a very simple snippet to illustrate the difference:

test = pd.DataFrame({'id':[1,2,3,1,2,3,1,2,3], 'price':[1,2,3,2,3,1,3,1,2]})
grouping = test.groupby('id')['price']

The DataFrame looks like this:

    id  price   
0   1   1   
1   2   2   
2   3   3   
3   1   2   
4   2   3   
5   3   1   
6   1   3   
7   2   1   
8   3   2   

There are 3 customer IDs in this table, each customer made three transactions and paid 1,2,3 dollars each time.

Now, I want to find the minimum payment made by each customer. There are two ways of doing it:

  1. Using apply:

    grouping.min()

The return looks like this:

id
1    1
2    1
3    1
Name: price, dtype: int64

pandas.core.series.Series # return type
Int64Index([1, 2, 3], dtype='int64', name='id') #The returned Series' index
# lenght is 3
  1. Using transform:

    grouping.transform(min)

The return looks like this:

0    1
1    1
2    1
3    1
4    1
5    1
6    1
7    1
8    1
Name: price, dtype: int64

pandas.core.series.Series # return type
RangeIndex(start=0, stop=9, step=1) # The returned Series' index
# length is 9    

Both methods return a Series object, but the length of the first one is 3 and the length of the second one is 9.

If you want to answer What is the minimum price paid by each customer, then the apply method is the more suitable one to choose.

If you want to answer What is the difference between the amount paid for each transaction vs the minimum payment, then you want to use transform, because:

test['minimum'] = grouping.transform(min) # ceates an extra column filled with minimum payment
test.price - test.minimum # returns the difference for each row

Apply does not work here simply because it returns a Series of size 3, but the original df's length is 9. You cannot integrate it back to the original df easily.

Execute PowerShell Script from C# with Commandline Arguments

Mine is a bit more smaller and simpler:

/// <summary>
/// Runs a PowerShell script taking it's path and parameters.
/// </summary>
/// <param name="scriptFullPath">The full file path for the .ps1 file.</param>
/// <param name="parameters">The parameters for the script, can be null.</param>
/// <returns>The output from the PowerShell execution.</returns>
public static ICollection<PSObject> RunScript(string scriptFullPath, ICollection<CommandParameter> parameters = null)
{
    var runspace = RunspaceFactory.CreateRunspace();
    runspace.Open();
    var pipeline = runspace.CreatePipeline();
    var cmd = new Command(scriptFullPath);
    if (parameters != null)
    {
        foreach (var p in parameters)
        {
            cmd.Parameters.Add(p);
        }
    }
    pipeline.Commands.Add(cmd);
    var results = pipeline.Invoke();
    pipeline.Dispose();
    runspace.Dispose();
    return results;
}

Python threading.timer - repeat function every 'n' seconds

In addition to the above great answers using Threads, in case you have to use your main thread or prefer an async approach - I wrapped a short class around aio_timers Timer class (to enable repeating)

import asyncio
from aio_timers import Timer

class RepeatingAsyncTimer():
    def __init__(self, interval, cb, *args, **kwargs):
        self.interval = interval
        self.cb = cb
        self.args = args
        self.kwargs = kwargs
        self.aio_timer = None
        self.start_timer()
    
    def start_timer(self):
        self.aio_timer = Timer(delay=self.interval, 
                               callback=self.cb_wrapper, 
                               callback_args=self.args, 
                               callback_kwargs=self.kwargs
                              )
    
    def cb_wrapper(self, *args, **kwargs):
        self.cb(*args, **kwargs)
        self.start_timer()


from time import time
def cb(timer_name):
    print(timer_name, time())

print(f'clock starts at: {time()}')
timer_1 = RepeatingAsyncTimer(interval=5, cb=cb, timer_name='timer_1')
timer_2 = RepeatingAsyncTimer(interval=10, cb=cb, timer_name='timer_2')

clock starts at: 1602438840.9690785

timer_1 1602438845.980087

timer_2 1602438850.9806316

timer_1 1602438850.9808934

timer_1 1602438855.9863033

timer_2 1602438860.9868324

timer_1 1602438860.9876585

Rails - How to use a Helper Inside a Controller

My problem resolved with Option 1. Probably the simplest way is to include your helper module in your controller:

class ApplicationController < ActionController::Base
  include ApplicationHelper

...

This version of the application is not configured for billing through Google Play

Recently google has implemented a change on their systems, and since you have uploaded at least one APK to your console, you can test your in-app requests with your app with any version code / number.

Cross reference LINK

Configure gradle to sign your debug build for debugging.

android {
    ...
    defaultConfig { ... }
    signingConfigs {
        release {
            storeFile file("my-release-key.jks")
            storePassword "password"
            keyAlias "my-alias"
            keyPassword "password"
        }
    }
    buildTypes {
        debug {
            signingConfig signingConfigs.release
            ...
        }
    }
}

How to find a parent with a known class in jQuery?

Extracted from @Resord's comments above. This one worked for me and more closely inclined with the question.

$(this).parent().closest('.a');

Thanks

What is the proper way to re-attach detached objects in Hibernate?

to reattach this object, you must use merge();

this methode accept in parameter your entity detached and return an entity will be attached and reloaded from Database.

Example :
    Lot objAttach = em.merge(oldObjDetached);
    objAttach.setEtat(...);
    em.persist(objAttach);

Setting up MySQL and importing dump within Dockerfile

edit: I had misunderstand the question here. My following answer explains how to run sql commands at container creation time, but not at image creation time as desired by OP.

I'm not quite fond of Kuhess's accepted answer as the sleep 5 seems a bit hackish to me as it assumes that the mysql db daemon has correctly loaded within this time frame. That's an assumption, no guarantee. Also if you use a provided mysql docker image, the image itself already takes care about starting up the server; I would not interfer with this with a custom /usr/bin/mysqld_safe.

I followed the other answers around here and copied bash and sql scripts into the folder /docker-entrypoint-initdb.d/ within the docker container as this is clearly the intended way by the mysql image provider. Everything in this folder is executed once the db daemon is ready, hence you should be able rely on it.

As an addition to the others - since no other answer explicitely mentions this: besides sql scripts you can also copy bash scripts into that folder which might give you more control.

This is what I had needed for example as I also needed to import a dump, but the dump alone was not sufficient as it did not provide which database it should import into. So in my case I have a script named db_custom_init.sh with this content:

mysql -u root -p$MYSQL_ROOT_PASSWORD -e 'create database my_database_to_import_into'
mysql -u root -p$MYSQL_ROOT_PASSWORD my_database_to_import_into < /home/db_dump.sql

and this Dockerfile copying that script:

FROM mysql/mysql-server:5.5.62
ENV MYSQL_ROOT_PASSWORD=XXXXX
COPY ./db_dump.sql /home/db_dump.sql
COPY ./db_custom_init.sh /docker-entrypoint-initdb.d/

ERROR:'keytool' is not recognized as an internal or external command, operable program or batch file

Found it.

GO TO:

my computer->rightClick->properties->Advanced system settings->environment variables->find path in system variables->dbl click-> paste the "C:\Program Files\Java\jdk1.6.0_16\bin"->OK

GO TO:

cmd -> keytool -list -alias androiddebugkey -keystore "C:\Users\meee\.android\debug.keystore" -storepass android -keypass android

How to run SQL in shell script

sqlplus -s /nolog <<EOF
whenever sqlerror exit sql.sqlcode;
set echo on;
set serveroutput on;

connect <SCHEMA>/<PASS>@<HOST>:<PORT>/<SID>;

truncate table tmp;

exit;
EOF

append to url and refresh page

If you are developing for a modern browser, Instead of parsing the url parameters yourself- you can use the built in URL functions to do it for you like this:

const parser = new URL(url || window.location);
parser.searchParams.set(key, value);
window.location = parser.href;

How to set an environment variable in a running docker container

here is how to update a docker container config permanently

  1. stop container: docker stop <container name>
  2. edit container config: docker run -it -v /var/lib/docker:/var/lib/docker alpine vi $(docker inspect --format='/var/lib/docker/containers/{{.Id}}/config.v2.json' <container name>)
  3. restart docker

Java Array, Finding Duplicates

You can also work with Set, which doesn't allow duplicates in Java..

    for (String name : names)
    {         
      if (set.add(name) == false) 
         { // your duplicate element }
    }

using add() method and check return value. If add() returns false it means that element is not allowed in the Set and that is your duplicate.

ImportError: No module named BeautifulSoup

you can import bs4 instead of BeautifulSoup. Since bs4 is a built-in module, no additional installation is required.

from bs4 import BeautifulSoup
import re

doc = ['<html><head><title>Page title</title></head>',
       '<body><p id="firstpara" align="center">This is paragraph <b>one</b>.',
       '<p id="secondpara" align="blah">This is paragraph <b>two</b>.',
       '</html>']
soup = BeautifulSoup(''.join(doc))

print soup.prettify()

If you want to request, using requests module. request is using urllib, requests modules. but I personally recommendation using requests module instead of urllib

module install for using:

$ pip install requests

Here's how to use the requests module:

import requests as rq
res = rq.get('http://www.example.com')

print(res.content)
print(res.status_code)

Why docker container exits immediately

Since the image is a linux, one thing to check is to make sure any shell scripts used in the container have unix line endings. If they have a ^M at the end then they are windows line endings. One way to fix them is with dos2unix on /usr/local/start-all.sh to convert them from windows to unix. Running the docker in interactive mode can help figure out other problems. You could have a file name typo or something. see https://en.wikipedia.org/wiki/Newline

Running JAR file on Windows 10

How do I run an executable JAR file? If you have a jar file called Example.jar, follow these rules:

Open a notepad.exe.
Write : java -jar Example.jar.
Save it with the extension .bat.
Copy it to the directory which has the .jar file.
Double click it to run your .jar file.

Spring Boot, Spring Data JPA with multiple DataSources

I checked the source code you provided on GitHub. There were several mistakes / typos in the configuration.

In CustomerDbConfig / OrderDbConfig you should refer to customerEntityManager and packages should point at existing packages:

@Configuration
@EnableJpaRepositories(
    entityManagerFactoryRef = "customerEntityManager",
    transactionManagerRef = "customerTransactionManager",
    basePackages = {"com.mm.boot.multidb.repository.customer"})
public class CustomerDbConfig {

The packages to scan in customerEntityManager and orderEntityManager were both not pointing at proper package:

em.setPackagesToScan("com.mm.boot.multidb.model.customer");

Also the injection of proper EntityManagerFactory did not work. It should be:

@Bean(name = "customerTransactionManager")
public PlatformTransactionManager transactionManager(EntityManagerFactory customerEntityManager){

}

The above was causing the issue and the exception. While providing the name in a @Bean method you are sure you get proper EMF injected.

The last thing I have done was to disable to automatic configuration of JpaRepositories:

@EnableAutoConfiguration(exclude = JpaRepositoriesAutoConfiguration.class)

And with all fixes the application starts as you probably expect!

How to Detect Browser Window /Tab Close Event?

This code prevents the checkbox events. It works when user clicks on browser close button but it doesn't work when checkbox clicked. You can modify it for other controls(texbox, radiobutton etc.)

    window.onbeforeunload = function () {
        return "Are you sure?";
    }

    $(function () {
        $('input[type="checkbox"]').click(function () {
            window.onbeforeunload = function () { };
        });
    });

php implode (101) with quotes

$array = array('lastname', 'email', 'phone');


echo "'" . implode("','", $array) . "'";

Running .sh scripts in Git Bash

If your running export command in your bash script the above-given solution may not export anything even if it will run the script. As an alternative for that, you can run your script using

. script.sh 

Now if you try to echo your var it will be shown. Check my the result on my git bash

(coffeeapp) user (master *) capstone
$ . setup.sh
 done
(coffeeapp) user (master *) capstone
$ echo $ALGORITHMS
[RS256]
(coffeeapp) user (master *) capstone
$

Check more detail in this question

lexers vs parsers

There are a number of reasons why the analysis portion of a compiler is normally separated into lexical analysis and parsing ( syntax analysis) phases.

  1. Simplicity of design is the most important consideration. The separation of lexical and syntactic analysis often allows us to simplify at least one of these tasks. For example, a parser that had to deal with comments and white space as syntactic units would be. Considerably more complex than one that can assume comments and white space have already been removed by the lexical analyzer. If we are designing a new language, separating lexical and syntactic concerns can lead to a cleaner overall language design.
  2. Compiler efficiency is improved. A separate lexical analyzer allows us to apply specialized techniques that serve only the lexical task, not the job of parsing. In addition, specialized buffering techniques for reading input characters can speed up the compiler significantly.
  3. Compiler portability is enhanced. Input-device-specific peculiarities can be restricted to the lexical analyzer.

resource___Compilers (2nd Edition) written by- Alfred V. Abo Columbia University Monica S. Lam Stanford University Ravi Sethi Avaya Jeffrey D. Ullman Stanford University

the MySQL service on local computer started and then stopped

In my case, I tried to open a DOS prompt and go to the MySQL bin\ directory and issue the below command:

mysqld --defaults-file="C:\Program Files\MySQL\MySQL Server 5.0\my.ini" --standalone --console

And it shows me I was missing the "C:\Program Files\MySQL\MySQL Server 5.0\Uploads" folder; I built one and problem solved.

How to run a class from Jar which is not the Main-Class in its Manifest file

First of all jar creates a jar, and does not run it. Try java -jar instead.

Second, why do you pass the class twice, as FQCN (com.mycomp.myproj.dir2.MainClass2) and as file (com/mycomp/myproj/dir2/MainClass2.class)?

Edit:

It seems as if java -jar requires a main class to be specified. You could try java -cp your.jar com.mycomp.myproj.dir2.MainClass2 ... instead. -cp sets the jar on the classpath and enables java to look up the main class there.

SQL Server - NOT IN

You're probably better off comparing the fields individually, rather than concatenating the strings.

SELECT t1.*
    FROM Table1 t1
        LEFT JOIN Table2 t2
            ON t1.MAKE = t2.MAKE
                AND t1.MODEL = t2.MODEL
                AND t1.[serial number] = t2.[serial number]
    WHERE t2.MAKE IS NULL

Spring CrudRepository findByInventoryIds(List<Long> inventoryIdList) - equivalent to IN clause

findByInventoryIdIn(List<Long> inventoryIdList) should do the trick.

The HTTP request parameter format would be like so:

Yes ?id=1,2,3
No  ?id=1&id=2&id=3

The complete list of JPA repository keywords can be found in the current documentation listing. It shows that IsIn is equivalent – if you prefer the verb for readability – and that JPA also supports NotIn and IsNotIn.

Failed to build gem native extension (installing Compass)

Not sure why none of these are marked as the correct answer, but I landed here through a google search, so I will pass along what I know...

@paul_g's method was pretty close for me, my steps on a Mac osx10.9 Retina:

  • Install macports
  • Install rvm (stable with ruby add --insecure flag for SSL related issues) $\curl -sSL --insecure https://get.rvm.io | bash -s stable --ruby
  • Restart Terminal / Resource your profile
  • Run rvm requirements --with-gcc=clang You won't have to update Ruby because you downloaded the last stable version
  • And last step to run gem install compass --pre

Android: adb: Permission Denied

Be careful with the slash, change "\" for "/" , like this: adb.exe push SuperSU-v2.79-20161205182033.apk /storage

How to set an image as a background for Frame in Swing GUI of java?

This is easily done by replacing the frame's content pane with a JPanel which draws your image:

try {
    final Image backgroundImage = javax.imageio.ImageIO.read(new File(...));
    setContentPane(new JPanel(new BorderLayout()) {
        @Override public void paintComponent(Graphics g) {
            g.drawImage(backgroundImage, 0, 0, null);
        }
    });
} catch (IOException e) {
    throw new RuntimeException(e);
}

This example also sets the panel's layout to BorderLayout to match the default content pane layout.

(If you have any trouble seeing the image, you might need to call setOpaque(false) on some other components so that you can see through to the background.)

How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception

My issue was a little different. Instead of jdbc:oracle:thin:@server:port/service i had it as server:port/service.

Missing was jdbc:oracle:thin:@ in url attribute in GlobalNamingResources.Resource. But I overlooked tomcat exception's

java.sql.SQLException: Cannot create JDBC driver of class 'oracle.jdbc.driver.OracleDriver' for connect URL 'server:port/service'

Change mysql user password using command line

This works for me. Got solution from MYSQL webpage

In MySQL run below queries:

FLUSH PRIVILEGES;
ALTER USER 'root'@'localhost' IDENTIFIED BY 'New_Password';

offsetTop vs. jQuery.offset().top

This is what jQuery API Doc says about .offset():

Get the current coordinates of the first element, or set the coordinates of every element, in the set of matched elements, relative to the document.

This is what MDN Web API says about .offsetTop:

offsetTop returns the distance of the current element relative to the top of the offsetParent node

This is what jQuery v.1.11 .offset() basically do when getting the coords:

var box = { top: 0, left: 0 };

// BlackBerry 5, iOS 3 (original iPhone)
if ( typeof elem.getBoundingClientRect !== strundefined ) {
  box = elem.getBoundingClientRect();
}
win = getWindow( doc );
return {
  top: box.top  + ( win.pageYOffset || docElem.scrollTop )  - ( docElem.clientTop  || 0 ),
  left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 )
};
  • pageYOffset intuitively says how much was the page scrolled
  • docElem.scrollTop is the fallback for IE<9 (which are BTW unsupported in jQuery 2)
  • docElem.clientTop is the width of the top border of an element (the document in this case)
  • elem.getBoundingClientRect() gets the coords relative to the document viewport (see comments). It may return fraction values, so this is the source of your bug. It also may cause a bug in IE<8 when the page is zoomed. To avoid fraction values, try to calculate the position iteratively

Conclusion

  • If you want coords relative to the parent node, use element.offsetTop. Add element.scrollTop if you want to take the parent scrolling into account. (or use jQuery .position() if you are fan of that library)
  • If you want coords relative to the viewport use element.getBoundingClientRect().top. Add window.pageYOffset if you want to take the document scrolling into account. You don't need to subtract document's clientTop if the document has no border (usually it doesn't), so you have position relative to the document
  • Subtract element.clientTop if you don't consider the element border as the part of the element

SQL how to increase or decrease one for a int column in one command

To answer the first:

UPDATE Orders SET Quantity = Quantity + 1 WHERE ...

To answer the second:

There are several ways to do this. Since you did not specify a database, I will assume MySQL.

  1. INSERT INTO table SET x=1, y=2 ON DUPLICATE KEY UPDATE x=x+1, y=y+2
  2. REPLACE INTO table SET x=1, y=2

They both can handle your question. However, the first syntax allows for more flexibility to update the record rather than just replace it (as the second one does).

Keep in mind that for both to exist, there has to be a UNIQUE key defined...

ListView with OnItemClickListener

Though a very old question, but I am still posting an answer to it so that it may help some one. If you are using any layout inside the list view then use ...

android:descendantFocusability="blocksDescendants"    

... on the first parent layout inside the list. This works as magic the click will not be consumed by any element inside the list but will directly go to the list item.

Delete all lines beginning with a # from a file

This answer builds upon the earlier answer by Keith.

egrep -v "^[[:blank:]]*#" should filter out comment lines.

egrep -v "^[[:blank:]]*(#|$)" should filter out both comments and empty lines, as is frequently useful.

For information about [:blank:] and other character classes, refer to https://en.wikipedia.org/wiki/Regular_expression#Character_classes.

How can I merge two MySQL tables?

Not as complicated as it sounds.... Just leave the duplicate primary key out of your query.... this works for me !

INSERT INTO
  Content(
    `status`,
    content_category,
    content_type,
    content_id,
    user_id,
    title,
    description,
    content_file,
    content_url,
    tags,
    create_date,
    edit_date,
    runs
  )
SELECT `status`,
  content_category,
  content_type,
  content_id,
  user_id,
  title,
  description,
  content_file,
  content_url,
  tags,
  create_date,
  edit_date,
  runs
FROM
  Content_Images

Writing your own square root function

use binary search

public class FindSqrt {

    public static void main(String[] strings) {

        int num = 10000;
        System.out.println(sqrt(num, 0, num));
    }

    private static int sqrt(int num, int min, int max) {
        int middle = (min + max) / 2;
        int x = middle * middle;
        if (x == num) {
            return middle;
        } else if (x < num) {
            return sqrt(num, middle, max);
        } else {
            return sqrt(num, min, middle);
        }
    }
}

Is there a .NET/C# wrapper for SQLite?

For those like me who don't need or don't want ADO.NET, those who need to run code closer to SQLite, but still compatible with netstandard (.net framework, .net core, etc.), I've built a 100% free open source project called SQLNado (for "Not ADO") available on github here:

https://github.com/smourier/SQLNado

It's available as a nuget here https://www.nuget.org/packages/SqlNado but also available as a single .cs file, so it's quite practical to use in any C# project type.

It supports all of SQLite features when using SQL commands, and also supports most of SQLite features through .NET:

  • Automatic class-to-table mapping (Save, Delete, Load, LoadAll, LoadByPrimaryKey, LoadByForeignKey, etc.)
  • Automatic synchronization of schema (tables, columns) between classes and existing table
  • Designed for thread-safe operations
  • Where and OrderBy LINQ/IQueryable .NET expressions are supported (work is still in progress in this area), also with collation support
  • SQLite database schema (tables, columns, etc.) exposed to .NET
  • SQLite custom functions can be written in .NET
  • SQLite incremental BLOB I/O is exposed as a .NET Stream to avoid high memory consumption
  • SQLite collation support, including the possibility to add custom collations using .NET code
  • SQLite Full Text Search engine (FTS3) support, including the possibility to add custom FTS3 tokenizers using .NET code (like localized stop words for example). I don't believe any other .NET wrappers do that.
  • Automatic support for Windows 'winsqlite3.dll' (only on recent Windows versions) to avoid shipping any binary dependency file. This works in Azure Web apps too!.

JPA Hibernate One-to-One relationship

You just need to add @JoinColumn(name="column_name") to Host Entity relation . column_name is the database column name in person table.

@Entity
public class Person {
    @Id
    public int id;

    @OneToOne
    @JoinColumn(name="other_info")
    public OtherInfo otherInfo;

    rest of attributes ...
}

Person has a one-to-one relationship with OtherInfo: mappedBy="var_name" var_name is variable name for otherInfo in Person class.

@Entity
public class OtherInfo {
    @Id
    @OneToOne(mappedBy="otherInfo")
    public Person person;

    rest of attributes ...
}

Getting unique items from a list

You can use the Distinct method to return an IEnumerable<T> of distinct items:

var uniqueItems = yourList.Distinct();

And if you need the sequence of unique items returned as a List<T>, you can add a call to ToList:

var uniqueItemsList = yourList.Distinct().ToList();

getting the X/Y coordinates of a mouse click on an image with jQuery

The below code works always even if any image makes the window scroll.

$(function() {
    $("#demo-box").click(function(e) {

      var offset = $(this).offset();
      var relativeX = (e.pageX - offset.left);
      var relativeY = (e.pageY - offset.top);

      alert("X: " + relativeX + "  Y: " + relativeY);

    });
});

Ref: http://css-tricks.com/snippets/jquery/get-x-y-mouse-coordinates/

In CSS what is the difference between "." and "#" when declaring a set of styles?

The # is an id selector. It matches only elements with a matching id. Next style rule will match the element that has an id attribute with a value of "green":

#green {color: green}

See http://www.w3schools.com/css/css_syntax.asp for more information

show loading icon until the page is load?

firstly, in your main page use a loading icon

then, delete your </body> and </HTML> from your main page and replace it by

<?php include('footer.php');?>

in the footer.php file type :

<?php
    $iconPath="myIcon.ico" // myIcon is the final icon
    echo '<script>changeIcon($iconPath)</script>'; // where changeIcon is a javascript function whiwh change your icon.
    echo '</body>';
    echo '</HTML>';
?>

Updating user data - ASP.NET Identity

I am using the new EF & Identity Core and I have the same issue, with the addition that I've got this error:

The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked.

With the new DI model I added the constructor's Controller the context to the DB.

I tried to see what are the conflict with _conext.ChangeTracker.Entries() and adding AsNoTracking() to my calls without success.

I only need to change the state of my object (in this case Identity)

_context.Entry(user).State = EntityState.Modified;
var result = await _userManager.UpdateAsync(user);

And worked without create another store or object and mapping.

I hope someone else is useful my two cents.

Regular expression to match DNS hostname or IP Address?

AddressRegex = "^(ftp|http|https):\/\/([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}:[0-9]{1,5})$";

HostnameRegex =  /^(ftp|http|https):\/\/([a-z0-9]+\.)?[a-z0-9][a-z0-9-]*((\.[a-z]{2,6})|(\.[a-z]{2,6})(\.[a-z]{2,6}))$/i

this re are used only for for this type validation

work only if http://www.kk.com http://www.kk.co.in

not works for

http://www.kk.com/ http://www.kk.co.in.kk

http://www.kk.com/dfas http://www.kk.co.in/

mysqldump exports only one table

In case you encounter an error like this

mysqldump: 1044 Access denied when using LOCK TABLES

A quick workaround is to pass the –-single-transaction option to mysqldump.

So your command will be like this.

mysqldump --single-transaction -u user -p DBNAME > backup.sql

How to detect internet speed in JavaScript?

Well, this is 2017 so you now have Network Information API (albeit with a limited support across browsers as of now) to get some sort of estimate downlink speed information:

navigator.connection.downlink

This is effective bandwidth estimate in Mbits per sec. The browser makes this estimate from recently observed application layer throughput across recently active connections. Needless to say, the biggest advantage of this approach is that you need not download any content just for bandwidth/ speed calculation.

You can look at this and a couple of other related attributes here

Due to it's limited support and different implementations across browsers (as of Nov 2017), would strongly recommend read this in detail

Simple Vim commands you wish you'd known earlier

:Te[xplore]

Tab & Explore (does a tabnew before generating the browser window)

How to capitalize the first character of each word in a string

String toBeCapped = "i want this sentence capitalized";

String[] tokens = toBeCapped.split("\\s");
toBeCapped = "";

for(int i = 0; i < tokens.length; i++){
    char capLetter = Character.toUpperCase(tokens[i].charAt(0));
    toBeCapped +=  " " + capLetter + tokens[i].substring(1);
}
toBeCapped = toBeCapped.trim();

How to get the return value from a thread in python?

Based of what kindall mentioned, here's the more generic solution that works with Python3.

import threading

class ThreadWithReturnValue(threading.Thread):
    def __init__(self, *init_args, **init_kwargs):
        threading.Thread.__init__(self, *init_args, **init_kwargs)
        self._return = None
    def run(self):
        self._return = self._target(*self._args, **self._kwargs)
    def join(self):
        threading.Thread.join(self)
        return self._return

Usage

        th = ThreadWithReturnValue(target=requests.get, args=('http://www.google.com',))
        th.start()
        response = th.join()
        response.status_code  # => 200

Chrome says my extension's manifest file is missing or unreadable

Mine also was funny. While copypasting " manifest.json" from the tutorial, i also managed to copy a leading space. Couldn't get why it's not finding it.

Missing .map resource?

I had similar expirience like yours. I have Denwer server. When I loaded my http://new.new local site without using via script src jquery.min.js file at index.php in Chrome I got error 500 jquery.min.map in console. I resolved this problem simply - I disabled extension Wunderlist in Chrome and voila - I never see this error more. Although, No, I found this error again - when Wunderlist have been on again. So, check your extensions and try to disable all of them or some of them or one by one. Good luck!

Python TypeError must be str not int

Python comes with numerous ways of formatting strings:

New style .format(), which supports a rich formatting mini-language:

>>> temperature = 10
>>> print("the furnace is now {} degrees!".format(temperature))
the furnace is now 10 degrees!

Old style % format specifier:

>>> print("the furnace is now %d degrees!" % temperature)
the furnace is now 10 degrees!

In Py 3.6 using the new f"" format strings:

>>> print(f"the furnace is now {temperature} degrees!")
the furnace is now 10 degrees!

Or using print()s default separator:

>>> print("the furnace is now", temperature, "degrees!")
the furnace is now 10 degrees!

And least effectively, construct a new string by casting it to a str() and concatenating:

>>> print("the furnace is now " + str(temperature) + " degrees!")
the furnace is now 10 degrees!

Or join()ing it:

>>> print(' '.join(["the furnace is now", str(temperature), "degrees!"]))
the furnace is now 10 degrees!

Convert array of strings into a string in Java

Try the Arrays.deepToString method.

Returns a string representation of the "deep contents" of the specified array. If the array contains other arrays as elements, the string representation contains their contents and so on. This method is designed for converting multidimensional arrays to strings

async for loop in node.js

I like to use the recursive pattern for this scenario. For example, something like this:

// If config is an array of queries
var config = JSON.parse(queries.querrryArray);   

// Array of results
var results;

processQueries(config);

function processQueries(queries) {
    var searchQuery;

    if (queries.length == 0) {
        // All queries complete
        res.writeHead(200, {'content-type': 'application/json'});
        res.end(JSON.stringify({results: results}));
        return;
    }

    searchQuery = queries.pop();

    search(searchQuery, function(result) {
        results.push(JSON.stringify({result: result}); 
        processQueries();            
    });

}

processQueries is a recursive function that will pull a query element out of an array of queries to process. Then the callback function calls processQueries again when the query is complete. The processQueries knows to end when there are no queries left.

It is easiest to do this using arrays, but it could be modified to work with object key/values I imagine.

UTF-8 encoding problem in Spring MVC

You need add charset in the RequestMapping annotation:

@RequestMapping(path = "/account",  produces = "application/json;charset=UTF-8")

thats all.

How can I analyze a heap dump in IntelliJ? (memory leak)

You can just run "Java VisualVM" which is located at jdk/bin/jvisualvm.exe

This will open a GUI, use the "File" menu -> "Load..." then choose your *.hprof file

That's it, you're done!

Add Favicon with React and Webpack

This worked for me:

Add this in index.html (inside src folder along with favicon.ico)

**<link rel="icon" href="/src/favicon.ico" type="image/x-icon" />**

webpack.config.js is like:

 plugins: [new HtmlWebpackPlugin({`enter code here`
        template: './src/index.html'
    })],

HTTP post XML data in C#

AlliterativeAlice's example helped me tremendously. In my case, though, the server I was talking to didn't like having single quotes around utf-8 in the content type. It failed with a generic "Server Error" and it took hours to figure out what it didn't like:

request.ContentType = "text/xml; encoding=utf-8";

How to add new column to MYSQL table?

for WORDPRESS:

global $wpdb;


$your_table  = $wpdb->prefix. 'My_Table_Name';
$your_column =                'My_Column_Name'; 

if (!in_array($your_column, $wpdb->get_col( "DESC " . $your_table, 0 ) )){  $result= $wpdb->query(
    "ALTER     TABLE $your_table     ADD $your_column     VARCHAR(100)     CHARACTER SET utf8     NOT NULL     "  //you can add positioning phraze: "AFTER My_another_column"
);}

Another Repeated column in mapping for entity error

Hope this will help!

@OneToOne(optional = false)
    @JoinColumn(name = "department_id", insertable = false, updatable = false)
    @JsonManagedReference
    private Department department;

@JsonIgnore
    public Department getDepartment() {
        return department;
    }

@OneToOne(mappedBy = "department")
private Designation designation;

@JsonIgnore
    public Designation getDesignation() {
        return designation;
    }

What does mysql error 1025 (HY000): Error on rename of './foo' (errorno: 150) mean?

I know, this is an old post, but it's the first hit on everyone's favorite search engine if you are looking for error 1025.

However, there is an easy "hack" for fixing this issue:

Before you execute your command(s) you first have to disable the foreign key constraints check using this command:

SET FOREIGN_KEY_CHECKS = 0;

Then you are able to execute your command(s).

After you are done, don't forget to enable the foreign key constraints check again, using this command:

SET FOREIGN_KEY_CHECKS = 1;

Good luck with your endeavor.

How to save all console output to file in R?

If you are able to use the bash shell, you can consider simply running the R code from within a bash script and piping the stdout and stderr streams to a file. Here is an example using a heredoc:

File: test.sh

#!/bin/bash
# this is a bash script
echo "Hello World, this is bash"

test1=$(echo "This is a test")

echo "Here is some R code:"

Rscript --slave --no-save --no-restore - "$test1" <<EOF
  ## R code
  cat("\nHello World, this is R\n")
  args <- commandArgs(TRUE)
  bash_message<-args[1]
  cat("\nThis is a message from bash:\n")
  cat("\n",paste0(bash_message),"\n")
EOF

# end of script 

Then when you run the script with both stderr and stdout piped to a log file:

$ chmod +x test.sh
$ ./test.sh
$ ./test.sh &>test.log
$ cat test.log
Hello World, this is bash
Here is some R code:

Hello World, this is R

This is a message from bash:

 This is a test

Other things to look at for this would be to try simply pipping the stdout and stderr right from the R heredoc into a log file; I haven't tried this yet but it will probably work too.

How to index characters in a Golang string?

Go doesn't really have a character type as such. byte is often used for ASCII characters, and rune is used for Unicode characters, but they are both just aliases for integer types (uint8 and int32). So if you want to force them to be printed as characters instead of numbers, you need to use Printf("%c", x). The %c format specification works for any integer type.

Bootstrap: Position of dropdown menu relative to navbar item

Even if it s late i hope i can help someone. if dropdown menu or submenu is on the right side of screen it's open on the left side, if menu or submenu is on the left it's open on the right side.

$(".dropdown-toggle").on("click", function(event){//"show.bs.dropdown"
    var liparent=$(this.parentElement);
    var ulChild=liparent.find('ul');
    var xOffset=liparent.offset().left;
    var alignRight=($(document).width()-xOffset)<xOffset;


    if (liparent.hasClass("dropdown-submenu"))
    {
        ulChild.css("left",alignRight?"-101%":"");
    }
    else
    {                
        ulChild.toggleClass("dropdown-menu-right",alignRight);
    }

});

To detect vertical position you can also add

$( document ).ready(function() {
        var liparent=$(".dropdown");
    var yOffset=liparent.offset().top;
        var toTop=($(document).height()-yOffset)<yOffset;
    liparent.toggleClass("dropup",toTop);
});

https://jsfiddle.net/jd1100/rf9zvdhg/28/

Can a local variable's memory be accessed outside its scope?

What you're doing here is simply reading and writing to memory that used to be the address of a. Now that you're outside of foo, it's just a pointer to some random memory area. It just so happens that in your example, that memory area does exist and nothing else is using it at the moment. You don't break anything by continuing to use it, and nothing else has overwritten it yet. Therefore, the 5 is still there. In a real program, that memory would be re-used almost immediately and you'd break something by doing this (though the symptoms may not appear until much later!)

When you return from foo, you tell the OS that you're no longer using that memory and it can be reassigned to something else. If you're lucky and it never does get reassigned, and the OS doesn't catch you using it again, then you'll get away with the lie. Chances are though you'll end up writing over whatever else ends up with that address.

Now if you're wondering why the compiler doesn't complain, it's probably because foo got eliminated by optimization. It usually will warn you about this sort of thing. C assumes you know what you're doing though, and technically you haven't violated scope here (there's no reference to a itself outside of foo), only memory access rules, which only triggers a warning rather than an error.

In short: this won't usually work, but sometimes will by chance.

Detect Safari using jQuery

The only way I found is check if navigator.userAgent contains iPhone or iPad word

if (navigator.userAgent.toLowerCase().match(/(ipad|iphone)/)) {
    //is safari
}

Use .htaccess to redirect HTTP to HTTPs

None if this worked for me. First of all I had to look at my provider to see how they activate SSL in .htaccess my provider gives

<IfModule mod_rewrite.c>
   RewriteEngine On
   RewriteCond %{HTTP:HTTPS} !on
   RewriteRule (.*) https://%{SERVER_NAME}/$1 [QSA,L,R=301]
</IfModule>

But what took me days of research is I had to add to wp-config.php the following lines as my provided site is behind a proxy :

/**
 * Force le SSL
 */
define('FORCE_SSL_ADMIN', true);
if (strpos($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') !== false) $_SERVER['HTTPS']='on';

How can I create a war file of my project in NetBeans?

I had to right-click the build.xml file and choose "run". Only then would the .war file be created.

Android 1.6: "android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application"

I had a similar issue where I had another class something like this:

public class Something {
  MyActivity myActivity;

  public Something(MyActivity myActivity) {
    this.myActivity=myActivity;
  }

  public void someMethod() {
   .
   .
   AlertDialog.Builder builder = new AlertDialog.Builder(myActivity);
   .
   AlertDialog alert = builder.create();
   alert.show();
  }
}

Worked fine most of the time, but sometimes it crashed with the same error. Then I realise that in MyActivity I had...

public class MyActivity extends Activity {
  public static Something something;

  public void someMethod() {
    if (something==null) {
      something=new Something(this);
    }
  }
}

Because I was holding the object as static, a second run of the code was still holding the original version of the object, and thus was still referring to the original Activity, which no long existed.

Silly stupid mistake, especially as I really didn't need to be holding the object as static in the first place...

What does request.getParameter return?

Per the Javadoc:

Returns the value of a request parameter as a String, or null if the parameter does not exist.

Do note that it is possible to submit an empty parameter - such that the parameter exists, but has no value. For example, I could include &log=&somethingElse into the URL to enable logging, without needing to specify &log=true. In this case, the value will be an empty String ("").

How do I detect what .NET Framework versions and service packs are installed?

Here is a PowerShell script to obtain installed .NET framework versions

function Get-KeyPropertyValue($key, $property)
{
    if($key.Property -contains $property)
    {
        Get-ItemProperty $key.PSPath -name $property | select -expand $property
    }
}

function Get-VersionName($key)
{
   $name = Get-KeyPropertyValue $key Version
   $sp = Get-KeyPropertyValue $key SP
   $install = Get-KeyPropertyValue $key Install
   if($sp)
   {
        "$($_.PSChildName) $name SP $sp"
   }
   else{
    "$($_.PSChildName) $name"
   }
}

function Get-FrameworkVersion{
   dir "hklm:\SOFTWARE\Microsoft\NET Framework Setup\NDP\" |? {$_.PSChildName -like "v*"} |%{
    if( $_.Property -contains "Version")
    {
        Get-VersionName $_
    }
    else{
        $parent = $_
        Get-ChildItem $_.PSPath |%{
            $versionName = Get-VersionName $_
            "$($parent.PSChildName) $versionName"
            }
        }
    }
}


$v4Directory = "hklm:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full"
if(Test-Path $v4Directory)
{
    $v4 = Get-Item $v4Directory
    $version = Get-KeyPropertyValue $v4 Release
    switch($version){
        378389 {".NET Framework 4.5"; break;}
        378675 {".NET Framework 4.5.1 installed with Windows 8.1 or Windows Server 2012 R2"; break;}
        378758 {".NET Framework 4.5.1 installed on Windows 8, Windows 7 SP1, or Windows Vista SP2"; break;}
        379893 {".NET Framework 4.5.2"; break;}
        { 393295, 393297 -contains $_} {".NET Framework 4.6"; break;}
        { 394254, 394271 -contains $_} {".NET Framework 4.6.1"; break;}
        { 394802, 394806 -contains $_} {".NET Framework 4.6.2"; break; }
    }
}

It was written based on How to: Determine Which .NET Framework Versions Are Installed. Please use THE Get-FrameworkVersion() function to get information about installed .NET framework versions.

Assigning a function to a variable

I don't know what is the value/usefulness of renaming a function and call it with the new name. But using a string as function name, e.g. obtained from the command line, has some value/usefulness:

import sys
fun = eval(sys.argv[1])
fun()

In the present case, fun = x.

git ignore exception

The solution depends on the relation between the git ignore rule and the exception rule:

  1. Files/Files at the same level: use the @Skilldrick solution.
  2. Folders/Subfolders: use the @Matiss Jurgelis solution.
  3. Files/Files in different levels or Files/Subfolders: you can do this:

    *.suo
    *.user
    *.userosscache
    *.sln.docstates
    
    # ...
    
    # Exceptions for entire subfolders
    !SetupFiles/elasticsearch-5.0.0/**/*
    !SetupFiles/filebeat-5.0.0-windows-x86_64/**/*
    
    # Exceptions for files in different levels
    !SetupFiles/kibana-5.0.0-windows-x86/**/*.suo
    !SetupFiles/logstash-5.0.0/**/*.suo
    

Parcelable encountered IOException writing serializable object getactivity()

I am also phase these error and i am little bit change in modelClass which are implemented Serializable interface like:

At that Model class also implement Parcelable interface with writeToParcel() override method

Then just got error to "create creator" so CREATOR is write and also create with modelclass contructor with arguments & without arguments..

       @Override
        public void writeToParcel(Parcel dest, int flags) {
            dest.writeString(id);
            dest.writeString(name);
        }

        protected ArtistTrackClass(Parcel in) {
            id = in.readString();
            name = in.readString();
        }

       public ArtistTrackClass() {

        }

    public static final Creator<ArtistTrackClass> CREATOR = new Creator<ArtistTrackClass>() {
        @Override
        public ArtistTrackClass createFromParcel(Parcel in) {
            return new ArtistTrackClass(in);
        }

        @Override
        public ArtistTrackClass[] newArray(int size) {
            return new ArtistTrackClass[size];
        }
    };

Here,

ArtistTrackClass -> ModelClass

Constructor with Parcel arguments "read our attributes" and writeToParcel() is "write our attributes"

What is System, out, println in System.out.println() in Java

Whenever you're confused, I would suggest consulting the Javadoc as the first place for your clarification.

From the javadoc about System, here's what the doc says:

public final class System
extends Object

The System class contains several useful class fields and methods. It cannot be instantiated.
Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.

Since:
JDK1.0

Regarding System.out

public static final PrintStream out
The "standard" output stream. This stream is already open and ready to accept output data. Typically this stream corresponds to display output or another output destination specified by the host environment or user.
For simple stand-alone Java applications, a typical way to write a line of output data is:

     System.out.println(data)

What's the difference between interface and @interface in java?

The @ symbol denotes an annotation type definition.

That means it is not really an interface, but rather a new annotation type -- to be used as a function modifier, such as @override.

See this javadocs entry on the subject.

How to print to console using swift playground?

you need to enable the Show Assistant Editor:

enter image description here

Compare two dates in Java

Date equality depends on the two dates being equal to the millisecond. Creating a new Date object using new Date() will never equal a date created in the past. Joda Time's APIs simplify working with dates; however, using the Java's SDK alone:

if (removeTime(questionDate).equals(removeTime(today)) 
  ...

public Date removeTime(Date date) {    
    Calendar cal = Calendar.getInstance();  
    cal.setTime(date);  
    cal.set(Calendar.HOUR_OF_DAY, 0);  
    cal.set(Calendar.MINUTE, 0);  
    cal.set(Calendar.SECOND, 0);  
    cal.set(Calendar.MILLISECOND, 0);  
    return cal.getTime(); 
}

Letter Count on a string

One problem is that you are using count to refer both to the position in the word that you are checking, and the number of char you have seen, and you are using char to refer both to the input character you are checking, and the current character in the string. Use separate variables instead.

Also, move the return statement outside the loop; otherwise you will always return after checking the first character.

Finally, you only need one loop to iterate over the string. Get rid of the outer while loop and you will not need to track the position in the string.

Taking these suggestions, your code would look like this:

def count_letters(word, char):
  count = 0
  for c in word:
    if char == c:
      count += 1
  return count

Get list of filenames in folder with Javascript

No, Javascript doesn't have access to the filesystem. Server side Javascript is a whole different story but I guess you don't mean that.

Renaming Column Names in Pandas Groupby function

The current (as of version 0.20) method for changing column names after a groupby operation is to chain the rename method. See this deprecation note in the documentation for more detail.

Deprecated Answer as of pandas version 0.20

This is the first result in google and although the top answer works it does not really answer the question. There is a better answer here and a long discussion on github about the full functionality of passing dictionaries to the agg method.

These answers unfortunately do not exist in the documentation but the general format for grouping, aggregating and then renaming columns uses a dictionary of dictionaries. The keys to the outer dictionary are column names that are to be aggregated. The inner dictionaries have keys that the new column names with values as the aggregating function.

Before we get there, let's create a four column DataFrame.

df = pd.DataFrame({'A' : list('wwwwxxxx'), 
                   'B':list('yyzzyyzz'), 
                   'C':np.random.rand(8), 
                   'D':np.random.rand(8)})

   A  B         C         D
0  w  y  0.643784  0.828486
1  w  y  0.308682  0.994078
2  w  z  0.518000  0.725663
3  w  z  0.486656  0.259547
4  x  y  0.089913  0.238452
5  x  y  0.688177  0.753107
6  x  z  0.955035  0.462677
7  x  z  0.892066  0.368850

Let's say we want to group by columns A, B and aggregate column C with mean and median and aggregate column D with max. The following code would do this.

df.groupby(['A', 'B']).agg({'C':['mean', 'median'], 'D':'max'})

            D         C          
          max      mean    median
A B                              
w y  0.994078  0.476233  0.476233
  z  0.725663  0.502328  0.502328
x y  0.753107  0.389045  0.389045
  z  0.462677  0.923551  0.923551

This returns a DataFrame with a hierarchical index. The original question asked about renaming the columns in the same step. This is possible using a dictionary of dictionaries:

df.groupby(['A', 'B']).agg({'C':{'C_mean': 'mean', 'C_median': 'median'}, 
                            'D':{'D_max': 'max'}})

            D         C          
        D_max    C_mean  C_median
A B                              
w y  0.994078  0.476233  0.476233
  z  0.725663  0.502328  0.502328
x y  0.753107  0.389045  0.389045
  z  0.462677  0.923551  0.923551

This renames the columns all in one go but still leaves the hierarchical index which the top level can be dropped with df.columns = df.columns.droplevel(0).

Redirect From Action Filter Attribute

Try the following snippet, it should be pretty clear:

public class AuthorizeActionFilterAttribute : ActionFilterAttribute
{
  public override void OnActionExecuting(FilterExecutingContext filterContext)
  {
    HttpSessionStateBase session = filterContext.HttpContext.Session;
    Controller controller = filterContext.Controller as Controller;

    if (controller != null)
    {
      if (session["Login"] == null)
      {
        filterContext.Cancel = true;
        controller.HttpContext.Response.Redirect("./Login");
      }
    }

    base.OnActionExecuting(filterContext);
  }
}

How to split a comma separated string and process in a loop using JavaScript

Try the following snippet:

var mystring = 'this,is,an,example';
var splits = mystring.split(",");
alert(splits[0]); // output: this

Using :focus to style outer div?

As per the spec:

The :focus pseudo-class applies while an element has the focus (accepts keyboard events or other forms of text input).

The <div> does not accept input, so it cannot have :focus. Furthermore, CSS does not allow you to set styles on an element based on targeting its descendants. So you can't really do this unless you are willing to use JavaScript.

Is it possible to install another version of Python to Virtualenv?

I have not found suitable answer, so here goes my take, which builds upon @toszter answer, but does not use system Python (and you may know, it is not always good idea to install setuptools and virtualenv at system level when dealing with many Python configurations):

#!/bin/sh

mkdir python_ve
cd python_ve

MYROOT=`pwd`
mkdir env pyenv dep

cd ${MYROOT}/dep
wget https://pypi.python.org/packages/source/s/setuptools/setuptools-15.2.tar.gz#md5=a9028a9794fc7ae02320d32e2d7e12ee
wget https://raw.github.com/pypa/virtualenv/master/virtualenv.py
wget https://www.python.org/ftp/python/2.7.9/Python-2.7.9.tar.xz
xz -d Python-2.7.9.tar.xz

cd ${MYROOT}/pyenv
tar xf ../dep/Python-2.7.9.tar
cd Python-2.7.9
./configure --prefix=${MYROOT}/pyenv && make -j 4 && make install

cd ${MYROOT}/pyenv

tar xzf ../dep/setuptools-15.2.tar.gz

cd ${MYROOT}

pyenv/bin/python dep/virtualenv.py --no-setuptools --python=${MYROOT}/pyenv/bin/python --verbose env
env/bin/python pyenv/setuptools-15.2/setup.py install
env/bin/easy_install pip

echo "virtualenv in ${MYROOT}/env"

The trick of breaking chicken-egg problem here is to make virtualenv without setuptools first, because it otherwise fails (pip can not be found). It may be possible to install pip / wheel directly, but somehow easy_install was the first thing which came to my mind. Also, the script can be improved by factoring out concrete versions.

NB. Using xz in the script.

What's the shebang/hashbang (#!) in Facebook and new Twitter URLs for?

This technique is now deprecated.

This used to tell Google how to index the page.

https://developers.google.com/webmasters/ajax-crawling/

This technique has mostly been supplanted by the ability to use the JavaScript History API that was introduced alongside HTML5. For a URL like www.example.com/ajax.html#!key=value, Google will check the URL www.example.com/ajax.html?_escaped_fragment_=key=value to fetch a non-AJAX version of the contents.

Spring - No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call

I had this issue for days and nothing I found anywhere online helped me, I'm posting my answer here in case it helps anyone else.

In my case, I was working on a microservice being called through remoting, and my @Transactional annotation at the service level was not being picked up by the remote proxy.

Adding a delegate class between the service and dao layers and marking the delegate method as transactional fixed this for me.

How to set an HTTP proxy in Python 2.7?

For installing pip with get-pip.py behind a proxy I went with the steps below. My server was even behind a jump server.

From the jump server:

ssh -R 18080:proxy-server:8080 my-python-server

On the "python-server"

export https_proxy=https://localhost:18080 ; export http_proxy=http://localhost:18080 ; export ftp_proxy=$http_proxy
python get-pip.py

Success.

Save file to specific folder with curl command

For powershell in Windows, you can add relative path + filename to --output flag:

curl -L  http://github.com/GorvGoyl/Notion-Boost-browser-extension/archive/master.zip --output build_firefox/master-repo.zip

here build_firefox is relative folder.

Get string between two strings in a string

I think this works:

   static void Main(string[] args)
    {
        String text = "One=1,Two=2,ThreeFour=34";

        Console.WriteLine(betweenStrings(text, "One=", ",")); // 1
        Console.WriteLine(betweenStrings(text, "Two=", ",")); // 2
        Console.WriteLine(betweenStrings(text, "ThreeFour=", "")); // 34

        Console.ReadKey();

    }

    public static String betweenStrings(String text, String start, String end)
    {
        int p1 = text.IndexOf(start) + start.Length;
        int p2 = text.IndexOf(end, p1);

        if (end == "") return (text.Substring(p1));
        else return text.Substring(p1, p2 - p1);                      
    }

What does MVW stand for?

MVW stands for Model-View-Whatever.

For completeness, here are all the acronyms mentioned:

MVC - Model-View-Controller

MVP - Model-View-Presenter

MVVM - Model-View-ViewModel

MVW / MV* / MVx - Model-View-Whatever

And some more:

HMVC - Hierarchical Model-View-Controller

MMV - Multiuse Model View

MVA - Model-View-Adapter

MVI - Model-View-Intent

JavaScript console.log causes error: "Synchronous XMLHttpRequest on the main thread is deprecated..."

For me, the problem was that in an OK request, I expected the ajax response to be a well formatted HTML string such as a table, but in this case, the server was experiencing a problem with the request, redirecting to an error page, and was therefore returning back the HTML code of the error page (which had a <script tag somewhere. I console logged the ajax response and that's when I realized it was not what I was expecting, then proceeded to do my debugging.

spring autowiring with unique beans: Spring expected single matching bean but found 2

If I'm not mistaken, the default bean name of a bean declared with @Component is the name of its class its first letter in lower-case. This means that

@Component
public class SuggestionService {

declares a bean of type SuggestionService, and of name suggestionService. It's equivalent to

@Component("suggestionService")
public class SuggestionService {

or to

<bean id="suggestionService" .../>

You're redefining another bean of the same type, but with a different name, in the XML:

<bean id="SuggestionService" class="com.hp.it.km.search.web.suggestion.SuggestionService">
    ...
</bean>

So, either specify the name of the bean in the annotation to be SuggestionService, or use the ID suggestionService in the XML (don't forget to also modify the <ref> element, or to remove it, since it isn't needed). In this case, the XML definition will override the annotation definition.

How to integrate Dart into a Rails app

If you run pub build --mode=debug the build directory contains the application without symlinks. The Dart code should be retained when --mode=debug is used.

Here is some discussion going on about this topic too Dart and it's place in Rails Assets Pipeline

Python Pandas - Missing required dependencies ['numpy'] 1

I had the same issue. It was because I had multiple versions of numpy installed. Remove all versions by repeatedly using:

pip uninstall numpy

Then re-install it with the command:

pip install numpy

How to sum all column values in multi-dimensional array?

For those who landed here and are searching for a solution that merges N arrays AND also sums the values of identical keys found in the N arrays, I've written this function that works recursively as well. (See: https://gist.github.com/Nickology/f700e319cbafab5eaedc)

Example:

$a = array( "A" => "bob", "sum" => 10, "C" => array("x","y","z" => 50) );
$b = array( "A" => "max", "sum" => 12, "C" => array("x","y","z" => 45) );
$c = array( "A" => "tom", "sum" =>  8, "C" => array("x","y","z" => 50, "w" => 1) );

print_r(array_merge_recursive_numeric($a,$b,$c));

Will result in:

Array
(
    [A] => tom
    [sum] => 30
    [C] => Array
        (
            [0] => x
            [1] => y
            [z] => 145
            [w] => 1
        )

)

Here's the code:

<?php 
/**
 * array_merge_recursive_numeric function.  Merges N arrays into one array AND sums the values of identical keys.
 * WARNING: If keys have values of different types, the latter values replace the previous ones.
 * 
 * Source: https://gist.github.com/Nickology/f700e319cbafab5eaedc
 * @params N arrays (all parameters must be arrays)
 * @author Nick Jouannem <[email protected]>
 * @access public
 * @return void
 */
function array_merge_recursive_numeric() {

    // Gather all arrays
    $arrays = func_get_args();

    // If there's only one array, it's already merged
    if (count($arrays)==1) {
        return $arrays[0];
    }

    // Remove any items in $arrays that are NOT arrays
    foreach($arrays as $key => $array) {
        if (!is_array($array)) {
            unset($arrays[$key]);
        }
    }

    // We start by setting the first array as our final array.
    // We will merge all other arrays with this one.
    $final = array_shift($arrays);

    foreach($arrays as $b) {

        foreach($final as $key => $value) {

            // If $key does not exist in $b, then it is unique and can be safely merged
            if (!isset($b[$key])) {

                $final[$key] = $value;

            } else {

                // If $key is present in $b, then we need to merge and sum numeric values in both
                if ( is_numeric($value) && is_numeric($b[$key]) ) {
                    // If both values for these keys are numeric, we sum them
                    $final[$key] = $value + $b[$key];
                } else if (is_array($value) && is_array($b[$key])) {
                    // If both values are arrays, we recursively call ourself
                    $final[$key] = array_merge_recursive_numeric($value, $b[$key]);
                } else {
                    // If both keys exist but differ in type, then we cannot merge them.
                    // In this scenario, we will $b's value for $key is used
                    $final[$key] = $b[$key];
                }

            }

        }

        // Finally, we need to merge any keys that exist only in $b
        foreach($b as $key => $value) {
            if (!isset($final[$key])) {
                $final[$key] = $value;
            }
        }

    }

    return $final;

}

?>

Convert integer to hexadecimal and back again

int to hex:

int a = 72;

Console.WriteLine("{0:X}", a);

hex to int:

int b = 0xB76;

Console.WriteLine(b);

Bind a function to Twitter Bootstrap Modal Close

Bootstrap 3 & 4

$('#myModal').on('hidden.bs.modal', function () {
    // do something…
});

Bootstrap 3: getbootstrap.com/javascript/#modals-events

Bootstrap 4: getbootstrap.com/docs/4.1/components/modal/#events

Bootstrap 2.3.2

$('#myModal').on('hidden', function () {
    // do something…
});

See getbootstrap.com/2.3.2/javascript.html#modals ? Events

Android: textview hyperlink

Use

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:autoLink="web"
    android:text="www.google.com" />

This flag

autolink="web"

controls whether links such as urls automatically found and converted to clickable links. The default value is "none", disabling this feature. Values: all, email, map, none, phone, web.

How do you obtain a Drawable object from a resource id in android package?

From API 21 `getDrawable(int id)` is deprecated

So now you need to use

ResourcesCompat.getDrawable(context.getResources(), R.drawable.img_user, null)

But Best way to do is :

- You should create one common class for getting drawable and colors because if in future have any deprecation then you no need to do changes everywhere in your project.You just change in this method
object ResourceUtils {
    fun getColor(context: Context, color: Int): Int {
        return ResourcesCompat.getColor(context.getResources(), color, null)
    }

    fun getDrawable(context: Context, drawable: Int): Drawable? {
        return ResourcesCompat.getDrawable(context.getResources(), drawable, null)
    }
}

use this method like :

Drawable img=ResourceUtils.getDrawable(context, R.drawable.img_user)
image.setImageDrawable(img);

Javascript Iframe innerHTML

If you take a look at JQuery, you can do something like:

<iframe id="my_iframe" ...></iframe>

$('#my_iframe').contents().find('html').html();

This is assuming that your iframe parent and child reside on the same server, due to the Same Origin Policy in Javascript.

Is there a no-duplicate List implementation out there?

There's no Java collection in the standard library to do this. LinkedHashSet<E> preserves ordering similarly to a List, though, so if you wrap your set in a List when you want to use it as a List you'll get the semantics you want.

Alternatively, the Commons Collections (or commons-collections4, for the generic version) has a List which does what you want already: SetUniqueList / SetUniqueList<E>.

How to code a BAT file to always run as admin mode?

convert your batch file into .exe with this tool: http://www.battoexeconverter.com/ then you can run it as administrator

How to obtain a Thread id in Python?

I saw examples of thread IDs like this:

class myThread(threading.Thread):
    def __init__(self, threadID, name, counter):
        self.threadID = threadID
        ...

The threading module docs lists name attribute as well:

...

A thread has a name. 
The name can be passed to the constructor, 
and read or changed through the name attribute.

...

Thread.name

A string used for identification purposes only. 
It has no semantics. Multiple threads may
be given the same name. The initial name is set by the constructor.

Reverse ip, find domain names on ip address

They're just trawling lists of web sites, and recording the resulting IP addresses in a database.

All you're seeing is the reverse mapping of that list. It's not guaranteed to be a full list (indeed more often than not it won't be) because it's impossible to learn every possible web site address.

Store a cmdlet's result value in a variable in Powershell

Just access the Priority property of the object returned from the pipeline:

$var = (Get-WSManInstance -enumerate wmicimv2/win32_process).Priority

(This won't work if Get-WSManInstance returns multiple objects.2)

For the second question: to get two properties there are several options, problably the simplest is to have have one variable* containing an object with two separate properties:

$var = (Get-WSManInstance -enumerate wmicimv2/win32_process | select -first 1 Priority, ProcessID)

and then use, assuming only one process:

$var.Priority

and

$var.ProcessID

If there are multiple processes $var will be an array which you can index, so to get the properties of the first process (using the array literal syntax @(...) so it is always a collection1):

$var = @(Get-WSManInstance -enumerate wmicimv2/win32_process | select -first 1 Priority, ProcessID)

and then use:

$var[0].Priority
$var[0].ProcessID

1 PowerShell helpfully for the command line, but not so helpfully in scripts has some extra logic when assigning the result of a pipeline to a variable: if no objects are returned then set $null, if one is returned then that object is assigned, otherwise an array is assigned. Forcing an array returns an array with zero, one or more (respectively) elements.

2 This changes in PowerShell V3 (at the time of writing in Release Candidate), using a member property on an array of objects will return an array of the value of those properties.

When do I need a fb:app_id or fb:admins?

I think the documentation is reasonably helpful!

If you read it again, it says that adding open graph elements on your website will make your website act as a facebook page and you'll get the ability to publish updates to them etc.

So I think it's up to you - you can either just have a page with no OG elements, which is less work but also less 'rewarding' for you.

If you do use og, then set type to: blog

Finally: fb:admins or fb:app_id - A comma-separated list of either the Facebook IDs of page administrators or a Facebook Platform application ID. At a minimum, include only your own Facebook ID.

So just put your own fbid in there. As a tip, you can easily get this by looking at the url of your profile photo on facebook.

When is a CDATA section necessary within a script tag?

When you are going for strict XHTML compliance, you need the CDATA so less than and ampersands are not flagged as invalid characters.

Django - limiting query results

As an addition and observation to the other useful answers, it's worth noticing that actually doing [:10] as slicing will return the first 10 elements of the list, not the last 10...

To get the last 10 you should do [-10:] instead (see here). This will help you avoid using order_by('-id') with the - to reverse the elements.

How to yum install Node.JS on Amazon Linux

The accepted answer gave me node 0.10.36 and npm 1.3.6 which are very out of date. I grabbed the latest linux-x64 tarball from the nodejs downloads page and it wasn't too difficult to install: https://nodejs.org/dist/latest/.

# start in a directory where you like to install things for the current user
(For noobs : it downloads node package as node.tgz file in your directlry)
curl (paste the link to the one you want from the downloads page) >node.tgz

Now upzip the tar you just downloaded -

tar xzf node.tgz

Run this command and then also add it to your .bashrc:

export PATH="$PATH:(your install dir)/(node dir)/bin"

(example : export PATH ="$PATH:/home/ec2-user/mydirectory/node/node4.5.0-linux-x64/bin")

And update npm (only once, don't add to .bashrc):

npm install -g npm

Note that the -g there which means global, really means global to that npm instance which is the instance we just installed and is limited to the current user. This will apply to all packages that npm installs 'globally'.

How to check if the URL contains a given string?

I like to create a boolean and then use that in a logical if.

//kick unvalidated users to the login page
var onLoginPage = (window.location.href.indexOf("login") > -1);

if (!onLoginPage) {
  console.log('redirected to login page');
  window.location = "/login";
} else {
  console.log('already on the login page');
}

Count occurrences of a char in a string using Bash

I Would suggest the following:

var="any given string"
N=${#var}
G=${var//g/}
G=${#G}
(( G = N - G ))
echo "$G"

No call to any other program

Unable to launch the IIS Express Web server, Failed to register URL, Access is denied

When using Visual Studio 2015 the solution can be a bit different to the previous answers. VS2015 creates a hidden folder .vs under the same folder as your solution file. Under this is a config folder containing applicationhost.config. Deleting this file (or the entire .vs folder) then starting VS2015 to recreate it can fix this error.

Return Boolean Value on SQL Select Statement

Given that commonly 1 = true and 0 = false, all you need to do is count the number of rows, and cast to a boolean.

Hence, your posted code only needs a COUNT() function added:

SELECT CAST(COUNT(1) AS BIT) AS Expr1
FROM [User]
WHERE (UserID = 20070022)

What's the difference between "static" and "static inline" function?

inline instructs the compiler to attempt to embed the function content into the calling code instead of executing an actual call.

For small functions that are called frequently that can make a big performance difference.

However, this is only a "hint", and the compiler may ignore it, and most compilers will try to "inline" even when the keyword is not used, as part of the optimizations, where its possible.

for example:

static int Inc(int i) {return i+1};
.... // some code
int i;
.... // some more code
for (i=0; i<999999; i = Inc(i)) {/*do something here*/};

This tight loop will perform a function call on each iteration, and the function content is actually significantly less than the code the compiler needs to put to perform the call. inline will essentially instruct the compiler to convert the code above into an equivalent of:

 int i;
 ....
 for (i=0; i<999999; i = i+1) { /* do something here */};

Skipping the actual function call and return

Obviously this is an example to show the point, not a real piece of code.

static refers to the scope. In C it means that the function/variable can only be used within the same translation unit.

Create a Path from String in Java7

You can just use the Paths class:

Path path = Paths.get(textPath);

... assuming you want to use the default file system, of course.

How to flatten only some dimensions of a numpy array

A slight generalization to Peter's answer -- you can specify a range over the original array's shape if you want to go beyond three dimensional arrays.

e.g. to flatten all but the last two dimensions:

arr = numpy.zeros((3, 4, 5, 6))
new_arr = arr.reshape(-1, *arr.shape[-2:])
new_arr.shape
# (12, 5, 6)

EDIT: A slight generalization to my earlier answer -- you can, of course, also specify a range at the beginning of the of the reshape too:

arr = numpy.zeros((3, 4, 5, 6, 7, 8))
new_arr = arr.reshape(*arr.shape[:2], -1, *arr.shape[-2:])
new_arr.shape
# (3, 4, 30, 7, 8)

Better solution without exluding fields from Binding

You should not use your domain models in your views. ViewModels are the correct way to do it.

You need to map your domain model's necessary fields to viewmodel and then use this viewmodel in your controllers. This way you will have the necessery abstraction in your application.

If you never heard of viewmodels, take a look at this.

How to use document.getElementByName and getElementByTag?

If you have given same text name for both of your Id and Name properties you can give like document.getElementByName('frmMain')[index] other wise object required error will come.And if you have only one table in your page you can use document.getElementBytag('table')[index].

EDIT:

You can replace the index according to your form, if its first form place 0 for index.

How to create a windows service from java app

If you use Gradle Build Tool you can try my windows-service-plugin, which facilitates using of Apache Commons Daemon Procrun.

To create a java windows service application with the plugin you need to go through several simple steps.

  1. Create a main service class with the appropriate method.

    public class MyService {
    
        public static void main(String[] args) {
            String command = "start";
            if (args.length > 0) {
                command = args[0];
            }
            if ("start".equals(command)) {
                // process service start function
            } else {
                // process service stop function
            }
        }
    
    }
    
  2. Include the plugin into your build.gradle file.

    buildscript {
      repositories {
        maven {
          url "https://plugins.gradle.org/m2/"
        }
      }
      dependencies {
        classpath "gradle.plugin.com.github.alexeylisyutenko:windows-service-plugin:1.1.0"
      }
    }
    
    apply plugin: "com.github.alexeylisyutenko.windows-service-plugin"
    

    The same script snippet for new, incubating, plugin mechanism introduced in Gradle 2.1:

    plugins {
      id "com.github.alexeylisyutenko.windows-service-plugin" version "1.1.0"
    }
    
  3. Configure the plugin.

    windowsService {
      architecture = 'amd64'
      displayName = 'TestService'
      description = 'Service generated with using gradle plugin'   
      startClass = 'MyService'
      startMethod = 'main'
      startParams = 'start'
      stopClass = 'MyService'
      stopMethod = 'main'
      stopParams = 'stop'
      startup = 'auto'
    }
    
  4. Run createWindowsService gradle task to create a windows service distribution.

That's all you need to do to create a simple windows service. The plugin will automatically download Apache Commons Daemon Procrun binaries, extract this binaries to the service distribution directory and create batch files for installation/uninstallation of the service.

In ${project.buildDir}/windows-service directory you will find service executables, batch scripts for installation/uninstallation of the service and all runtime libraries. To install the service run <project-name>-install.bat and if you want to uninstall the service run <project-name>-uninstall.bat. To start and stop the service use <project-name>w.exe executable.

Note that the method handling service start should create and start a separate thread to carry out the processing, and then return. The main method is called from different threads when you start and stop the service.

For more information, please read about the plugin and Apache Commons Daemon Procrun.

How to write subquery inside the OUTER JOIN Statement

You need the "correlation id" (the "AS SS" thingy) on the sub-select to reference the fields in the "ON" condition. The id's assigned inside the sub select are not usable in the join.

SELECT
       cs.CUSID
       ,dp.DEPID
FROM
    CUSTMR cs
        LEFT OUTER JOIN (
            SELECT
                    DEPID
                    ,DEPNAME
                FROM
                    DEPRMNT 
                WHERE
                    dp.DEPADDRESS = 'TOKYO'
        ) ss
            ON (
                ss.DEPID = cs.CUSID
                AND ss.DEPNAME = cs.CUSTNAME
            )
WHERE
    cs.CUSID != '' 

Draw horizontal rule in React Native

This is how i solved divider with horizontal lines and text in the midddle:

<View style={styles.divider}>
  <View style={styles.hrLine} />
  <Text style={styles.dividerText}>OR</Text>
  <View style={styles.hrLine} />
</View>

And styles for this:

import { Dimensions, StyleSheet } from 'react-native'

const { width } = Dimensions.get('window')

const styles = StyleSheet.create({
divider: {
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: 10,
  },
  hrLine: {
    width: width / 3.5,
    backgroundColor: 'white',
    height: 1,
  },
  dividerText: {
    color: 'white',
    textAlign: 'center',
    width: width / 8,
  },
})

How to get CRON to call in the correct PATHs

Set the required PATH in your cron

crontab -e

Edit: Press i

PATH=/usr/local/bin:/usr/local/:or_whatever

10 * * * * your_command

Save and exit :wq

Jenkins - Configure Jenkins to poll changes in SCM

I think your cron is not correct. According to what you described, you may need to change cron schedule to

*/5 * * * *

What you put in your schedule now mean it will poll the SCM at 5 past of every hour.

SQL LEFT JOIN Subquery Alias

You didn't select post_id in the subquery. You have to select it in the subquery like this:

SELECT wp_woocommerce_order_items.order_id As No_Commande
FROM  wp_woocommerce_order_items
LEFT JOIN 
    (
        SELECT meta_value As Prenom, post_id  -- <----- this
        FROM wp_postmeta
        WHERE meta_key = '_shipping_first_name'
    ) AS a
ON wp_woocommerce_order_items.order_id = a.post_id
WHERE  wp_woocommerce_order_items.order_id =2198 

Why do we use arrays instead of other data structures?

For O(1) random access, which can not be beaten.

Why don't self-closing script elements work?

Others have answered "how" and quoted spec. Here is the real story of "why no <script/>", after many hours digging into bug reports and mailing lists.


HTML 4

HTML 4 is based on SGML.

SGML has some shorttags, such as <BR//, <B>text</>, <B/text/, or <OL<LI>item</LI</OL>. XML takes the first form, redefines the ending as ">" (SGML is flexible), so that it becomes <BR/>.

However, HTML did not redfine, so <SCRIPT/> should mean <SCRIPT>>.
(Yes, the '>' should be part of content, and the tag is still not closed.)

Obviously, this is incompatible with XHTML and will break many sites (by the time browsers were mature enough to care about this), so nobody implemented shorttags and the specification advises against them.

Effectively, all 'working' self-ended tags are tags with prohibited end tag on technically non-conformant parsers and are in fact invalid. It was W3C which came up with this hack to help transitioning to XHTML by making it HTML-compatible.

And <script>'s end tag is not prohibited.

"Self-ending" tag is a hack in HTML 4 and is meaningless.


HTML 5

HTML5 has five types of tags and only 'void' and 'foreign' tags are allowed to be self-closing.

Because <script> is not void (it may have content) and is not foreign (like MathML or SVG), <script> cannot be self-closed, regardless of how you use it.

But why? Can't they regard it as foreign, make special case, or something?

HTML 5 aims to be backward-compatible with implementations of HTML 4 and XHTML 1. It is not based on SGML or XML; its syntax is mainly concerned with documenting and uniting the implementations. (This is why <br/> <hr/> etc. are valid HTML 5 despite being invalid HTML4.)

Self-closing <script> is one of the tags where implementations used to differ. It used to work in Chrome, Safari, and Opera; to my knowledge it never worked in Internet Explorer or Firefox.

This was discussed when HTML 5 was being drafted and got rejected because it breaks browser compatibility. Webpages that self-close script tag may not render correctly (if at all) in old browsers. There were other proposals, but they can't solve the compatibility problem either.

After the draft was released, WebKit updated the parser to be in conformance.

Self-closing <script> does not happen in HTML 5 because of backward compatibility to HTML 4 and XHTML 1.


XHTML 1 / XHTML 5

When really served as XHTML, <script/> is really closed, as other answers have stated.

Except that the spec says it should have worked when served as HTML:

XHTML Documents ... may be labeled with the Internet Media Type "text/html" [RFC2854], as they are compatible with most HTML browsers.

So, what happened?

People asked Mozilla to let Firefox parse conforming documents as XHTML regardless of the specified content header (known as content sniffing). This would have allowed self-closing scripts, and content sniffing was necessary anyway because web hosters were not mature enough to serve the correct header; IE was good at it.

If the first browser war didn't end with IE 6, XHTML may have been on the list, too. But it did end. And IE 6 has a problem with XHTML. In fact IE did not support the correct MIME type at all, forcing everyone to use text/html for XHTML because IE held major market share for a whole decade.

And also content sniffing can be really bad and people are saying it should be stopped.

Finally, it turns out that the W3C didn't mean XHTML to be sniffable: the document is both, HTML and XHTML, and Content-Type rules. One can say they were standing firm on "just follow our spec" and ignoring what was practical. A mistake that continued into later XHTML versions.

Anyway, this decision settled the matter for Firefox. It was 7 years before Chrome was born; there were no other significant browser. Thus it was decided.

Specifying the doctype alone does not trigger XML parsing because of following specifications.

What does the question mark operator mean in Ruby?

In your example it's just part of the method name. In Ruby you can also use exclamation points in method names!

Another example of question marks in Ruby would be the ternary operator.

customerName == "Fred" ? "Hello Fred" : "Who are you?"

Windows git "warning: LF will be replaced by CRLF", is that warning tail backward?

All of this assumes core.autocrlf=true

Original error:

warning: LF will be replaced by CRLF
The file will have its original line endings in your working directory.

What the error SHOULD read:

warning: LF will be replaced by CRLF in your working directory
The file will have its original LF line endings in the git repository

Explanation here:

The side-effect of this convenient conversion, and this is what the warning you're seeing is about, is that if a text file you authored originally had LF endings instead of CRLF, it will be stored with LF as usual, but when checked out later it will have CRLF endings. For normal text files this is usually just fine. The warning is a "for your information" in this case, but in case git incorrectly assesses a binary file to be a text file, it is an important warning because git would then be corrupting your binary file.

Basically, a local file that was previously LF will now have CRLF locally

Pass Javascript variable to PHP via ajax

Alternatively, try removing "data" and making the URL "logtime.php?userID="+userId

I like Brian's answer better, this answer is just because you're trying to use URL parameter syntax in "data" and I wanted to demonstrate where you can use that syntax correctly.

Jackson enum Serializing and DeSerializer

I did it like this :

// Your JSON
{"event":"forgot password"}

// Your class to map 
public class LoggingDto {
    @JsonProperty(value = "event")
    private FooEnum logType;
}

//Your enum
public enum FooEnum {

    DATA_LOG ("Dummy 1"),
    DATA2_LOG ("Dummy 2"),
    DATA3_LOG ("forgot password"),
    DATA4_LOG ("Dummy 4"),
    DATA5_LOG ("Dummy 5"),
    UNKNOWN ("");

    private String fullName;

    FooEnum(String fullName) {
        this.fullName = fullName;
    }

    public String getFullName() {
        return fullName;
    }

    @JsonCreator
    public static FooEnum getLogTypeFromFullName(String fullName) {
        for (FooEnum logType : FooEnum.values()) {
            if (logType.fullName.equals(fullName)) {
                return logType;
            }
        }
        return UNKNOWN;
    }


}

So the value of the property "logType" for class LoggingDto will be DATA3_LOG

Importing larger sql files into MySQL

I really like the BigDump to do it. It's a very simple PHP file that you edit and send with your huge file through SSH or FTP. Run and wait! It's very easy to configure character encoding, comes UTF-8 by default.

Convert date to day name e.g. Mon, Tue, Wed

You can not use strtotime as your time format is not within the supported date and time formats of PHP.

Therefor, you have to create a valid date format first making use of createFromFormat function.

//creating a valid date format
$newDate = DateTime::createFromFormat('YmdHi', $longdate);

//formating the date as we want
$finalDate = $newDate->format('D'); 

Reverse colormap in matplotlib

There is no built-in way (yet) of reversing arbitrary colormaps, but one simple solution is to actually not modify the colorbar but to create an inverting Normalize object:

from matplotlib.colors import Normalize

class InvertedNormalize(Normalize):
    def __call__(self, *args, **kwargs):
        return 1 - super(InvertedNormalize, self).__call__(*args, **kwargs)

You can then use this with plot_surface and other Matplotlib plotting functions by doing e.g.

inverted_norm = InvertedNormalize(vmin=10, vmax=100)
ax.plot_surface(..., cmap=<your colormap>, norm=inverted_norm)

This will work with any Matplotlib colormap.

What's the best way to store Phone number in Django models

This solution worked for me:

First install django-phone-field

command: pip install django-phone-field

then on models.py

from phone_field import PhoneField
...

class Client(models.Model):
    ...
    phone_number = PhoneField(blank=True, help_text='Contact phone number')

and on settings.py

INSTALLED_APPS = [...,
                  'phone_field'
]

It looks like this in the end

phone in form

Verify object attribute value with mockito

I think the easiest way for verifying an argument object is to use the refEq method:

Mockito.verify(mockedObject).someMethodOnMockedObject(ArgumentMatchers.refEq(objectToCompareWith));

It can be used even if the object doesn't implement equals(), because reflection is used. If you don't want to compare some fields, just add their names as arguments for refEq.

How to save a list to a file and read it as a list type?

What I did not like with many answers is that it makes way too many system calls by writing to the file line per line. Imho it is best to join list with '\n' (line return) and then write it only once to the file:

mylist = ["abc", "def", "ghi"]
myfile = "file.txt"
with open(myfile, 'w') as f:
    f.write("\n".join(mylist))

and then to open it and get your list again:

with open(myfile, 'r') as f:
    mystring = f.read()
my_list = mystring.split("\n")

SSRS - Checking whether the data is null

Or in your SQL query wrap that field with IsNull or Coalesce (SQL Server).

Either way works, I like to put that logic in the query so the report has to do less.

php variable in html no other way than: <?php echo $var; ?>

In a php section before the HTML section, use sprinf() to create a constant string from the variables:

$mystuff = sprinf("My name is %s and my mother's name is %s","Suzy","Caroline");

Then in the HTML section you can do whatever you like, such as:

<p>$mystuff</p> 

How to remove a TFS Workspace Mapping?

From VS:

  1. Open Team Explorer
  2. Click Source Control Explorer
  3. In the nav bar of the tool window there is a drop down labeled "Workspaces".
  4. Extend it and click on the "Workspaces..." option (yeah, a bit un-intuitive)
  5. The "Manage Workspaces" window comes up. Click edit and you can add / remove / edit your workspace

source control explorer

From VS on a different machine

You don't need VS to be on the same machine as the enlistment as you can edit remote enlistments! In the dialog that comes up when you press the "Workspaces..." item there is a check box stating "Show Remote Workspaces" - just tick that and you'll get a list of all your enlistments:

show remote workspaces

From the command line

Call "tf workspace" from a developer command prompt. It will bring up the "Manage Workspaces" directly!

Android TextView Justify Text

I write a widget base on native textview to do it.

github

How can I view live MySQL queries?

I've been looking to do the same, and have cobbled together a solution from various posts, plus created a small console app to output the live query text as it's written to the log file. This was important in my case as I'm using Entity Framework with MySQL and I need to be able to inspect the generated SQL.

Steps to create the log file (some duplication of other posts, all here for simplicity):

  1. Edit the file located at:

    C:\Program Files (x86)\MySQL\MySQL Server 5.5\my.ini
    

    Add "log=development.log" to the bottom of the file. (Note saving this file required me to run my text editor as an admin).

  2. Use MySql workbench to open a command line, enter the password.

    Run the following to turn on general logging which will record all queries ran:

    SET GLOBAL general_log = 'ON';
    
    To turn off:
    
    SET GLOBAL general_log = 'OFF';
    

    This will cause running queries to be written to a text file at the following location.

    C:\ProgramData\MySQL\MySQL Server 5.5\data\development.log
    
  3. Create / Run a console app that will output the log information in real time:

    Source available to download here

    Source:

    using System;
    using System.Configuration;
    using System.IO;
    using System.Threading;
    
    namespace LiveLogs.ConsoleApp
    {
      class Program
      {
        static void Main(string[] args)
        {
            // Console sizing can cause exceptions if you are using a 
            // small monitor. Change as required.
    
            Console.SetWindowSize(152, 58);
            Console.BufferHeight = 1500;
    
            string filePath = ConfigurationManager.AppSettings["MonitoredTextFilePath"];
    
            Console.Title = string.Format("Live Logs {0}", filePath);
    
            var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
    
            // Move to the end of the stream so we do not read in existing
            // log text, only watch for new text.
    
            fileStream.Position = fileStream.Length;
    
            StreamReader streamReader;
    
            // Commented lines are for duplicating the log output as it's written to 
            // allow verification via a diff that the contents are the same and all 
            // is being output.
    
            // var fsWrite = new FileStream(@"C:\DuplicateFile.txt", FileMode.Create);
            // var sw = new StreamWriter(fsWrite);
    
            int rowNum = 0;
    
            while (true)
            {
                streamReader = new StreamReader(fileStream);
    
                string line;
                string rowStr;
    
                while (streamReader.Peek() != -1)
                {
                    rowNum++;
    
                    line = streamReader.ReadLine();
                    rowStr = rowNum.ToString();
    
                    string output = String.Format("{0} {1}:\t{2}", rowStr.PadLeft(6, '0'), DateTime.Now.ToLongTimeString(), line);
    
                    Console.WriteLine(output);
    
                    // sw.WriteLine(output);
                }
    
                // sw.Flush();
    
                Thread.Sleep(500);
            }
        }
      }
    }
    

Restoring database from .mdf and .ldf files of SQL Server 2008

I have an answer for you Yes, It is possible.

Go to

SQL Server Management Studio > select Database > click on attach

Then select and add .mdf and .ldf file. Click on OK.

Is it possible to set a custom font for entire of application?

in api 26 with build.gradle 3.0.0 and higher you can create a font directory in res and use this line in your style

<item name="android:fontFamily">@font/your_font</item>

for change build.gradle use this in your build.gradle dependecies

classpath 'com.android.tools.build:gradle:3.0.0'

How do you stash an untracked file?

Add the file to the index:

git add path/to/untracked-file
git stash

The entire contents of the index, plus any unstaged changes to existing files, will all make it into the stash.

How to Logout of an Application Where I Used OAuth2 To Login With Google?

You can log out and rediret to your site:

var logout = function() {
    document.location.href = "https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue=http://www.example.com";
}

Getting CheckBoxList Item values

You can initialize a list of string and add those items that are selected.

Please check code, works fine for me.

List<string> modules = new List<string>();

foreach(ListItem s in chk_modules.Items)
{
    if (s.Selected)
    {
         modules.Add(s.Value);
    }
}

C# naming convention for constants?

The ALL_CAPS is taken from the C and C++ way of working I believe. This article here explains how the style differences came about.

In the new IDE's such as Visual Studio it is easy to identify the types, scope and if they are constant so it is not strictly necessary.

The FxCop and Microsoft StyleCop software will help give you guidelines and check your code so everyone works the same way.

R dplyr: Drop multiple columns

We can try

iris %>% 
      select_(.dots= setdiff(names(.),drop.cols))

Unable to resolve "unable to get local issuer certificate" using git on Windows with self-signed certificate

I've just had the same issue but using sourcetree on windows Same steps for normal GIT on Windows as well. Following the following steps I was able to solve this issue.

  1. Obtain the server certificate tree This can be done using chrome. Navigate to be server address. Click on the padlock icon and view the certificates. Export all of the certificate chain as base64 encoded files (PEM) format.
  2. Add the certificates to the trust chain of your GIT trust config file Run "git config --list". find the "http.sslcainfo" configuration this shows where the certificate trust file is located. Copy all the certificates into the trust chain file including the "- -BEGIN- -" and the "- -END- -".
  3. Make sure you add the entire certificate Chain to the certificates file

This should solve your issue with the self-signed certificates and using GIT.

I tried using the "http.sslcapath" configuration but this did not work. Also if i did not include the whole chain in the certificates file then this would also fail. If anyone has pointers on these please let me know as the above has to be repeated for a new install.

If this is the system GIT then you can use the options in TOOLS -> options GIt tab to use the system GIT and this then solves the issue in sourcetree as well.

What does $ mean before a string?

$ syntax is nice, but with one downside.

If you need something like a string template, that is declared on the class level as field...well in one place as it should be.

Then you have to declare the variables on the same level...which is not really cool.

It is much nicer to use the string.Format syntax for this kind of things

class Example1_StringFormat {
 string template = $"{0} - {1}";

 public string FormatExample1() {
   string some1 = "someone";
   return string.Format(template, some1, "inplacesomethingelse");
 }

 public string FormatExample2() {
   string some2 = "someoneelse";
   string thing2 = "somethingelse";
   return string.Format(template, some2, thing2);
 }
}

The use of globals is not really ok and besides that - it does not work with globals either

 static class Example2_Format {
 //must have declaration in same scope
 static string some = "";
 static string thing = "";
 static string template = $"{some} - {thing}";

//This returns " - " and not "someone - something" as you would maybe 
//expect
 public static string FormatExample1() {
   some = "someone";
   thing = "something";
   return template;
 }

//This returns " - " and not "someoneelse- somethingelse" as you would 
//maybe expect
 public static string FormatExample2() {
   some = "someoneelse";
   thing = "somethingelse";
   return template;
 }
}

jquery remove "selected" attribute of option?

Well, I spent a lot of time on this issue. To get an answer working with Chrome AND IE, I had to change my approach. The idea is to avoid removing the selected option (because cannot remove it properly with IE). => this implies to select option not by adding or setting the selected attribute on the option, but to choose an option at the "select" level using the selectedIndex prop.

Before :

$('#myselect option:contains("value")').attr('selected','selected');
$('#myselect option:contains("value")').removeAttr('selected'); => KO with IE

After :

$('#myselect').prop('selectedIndex', $('#myselect option:contains("value")').index());
$('#myselect').prop('selectedIndex','-1'); => OK with all browsers

Hope it will help

Rename multiple files based on pattern in Unix

This script worked for me for recursive renaming with directories/file names possibly containing white-spaces:

find . -type f -name "*\;*" | while read fname; do
    dirname=`dirname "$fname"`
    filename=`basename "$fname"`
    newname=`echo "$filename" | sed -e "s/;/ /g"`
    mv "${dirname}/$filename" "${dirname}/$newname"
done

Notice the sed expression which in this example replaces all occurrences of ; with space . This should of course be replaced according to the specific needs.

Using GZIP compression with Spring Boot/MVC/JavaConfig with RESTful

This is basically the same solution as @andy-wilkinson provided, but as of Spring Boot 1.0 the customize(...) method has a ConfigurableEmbeddedServletContainer parameter.

Another thing that is worth mentioning is that Tomcat only compresses content types of text/html, text/xml and text/plain by default. Below is an example that supports compression of application/json as well:

@Bean
public EmbeddedServletContainerCustomizer servletContainerCustomizer() {
    return new EmbeddedServletContainerCustomizer() {
        @Override
        public void customize(ConfigurableEmbeddedServletContainer servletContainer) {
            ((TomcatEmbeddedServletContainerFactory) servletContainer).addConnectorCustomizers(
                    new TomcatConnectorCustomizer() {
                        @Override
                        public void customize(Connector connector) {
                            AbstractHttp11Protocol httpProtocol = (AbstractHttp11Protocol) connector.getProtocolHandler();
                            httpProtocol.setCompression("on");
                            httpProtocol.setCompressionMinSize(256);
                            String mimeTypes = httpProtocol.getCompressableMimeTypes();
                            String mimeTypesWithJson = mimeTypes + "," + MediaType.APPLICATION_JSON_VALUE;
                            httpProtocol.setCompressableMimeTypes(mimeTypesWithJson);
                        }
                    }
            );
        }
    };
}

Using putty to scp from windows to Linux

You can use PSCP to copy files from Windows to Linux.

  1. Download PSCP from putty.org
  2. Open cmd in the directory with pscp.exe file
  3. Type command pscp source_file user@host:destination_file

Reference

How to generate Entity Relationship (ER) Diagram of a database using Microsoft SQL Server Management Studio?

From Object Explorer in SQL Server Management Studio, find your database and expand the node (click on the + sign beside your database). The first item from that expanded tree is Database Diagrams. Right-click on that and you'll see various tasks including creating a new database diagram. If you've never created one before, it'll ask if you want to install the components for creating diagrams. Click yes then proceed.

How to remove the default arrow icon from a dropdown list (select element)?

As I answered in Remove Select arrow on IE

In case you want to use the class and pseudo-class:

.simple-control is your css class

:disabled is pseudo class

select.simple-control:disabled{
         /*For FireFox*/
        -webkit-appearance: none;
        /*For Chrome*/
        -moz-appearance: none;
}

/*For IE10+*/
select:disabled.simple-control::-ms-expand {
        display: none;
}

How to set default font family in React Native?

You can override Text behaviour by adding this in any of your component using Text:

let oldRender = Text.prototype.render;
Text.prototype.render = function (...args) {
    let origin = oldRender.call(this, ...args);
    return React.cloneElement(origin, {
        style: [{color: 'red', fontFamily: 'Arial'}, origin.props.style]
    });
};

Edit: since React Native 0.56, Text.prototypeis not working anymore. You need to remove the .prototype :

let oldRender = Text.render;
Text.render = function (...args) {
    let origin = oldRender.call(this, ...args);
    return React.cloneElement(origin, {
        style: [{color: 'red', fontFamily: 'Arial'}, origin.props.style]
    });
};

Why does pycharm propose to change method to static

This error message just helped me a bunch, as I hadn't realized that I'd accidentally written my function using my testing example player

my_player.attributes[item] 

instead of the correct way

self.attributes[item]

Read response headers from API response - Angular 5 + TypeScript

You can get data from post response Headers in this way (Angular 6):

import { HttpClient, HttpHeaders, HttpResponse } from '@angular/common/http';

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
  observe: 'response' as 'response'
};

this.http.post(link,body,httpOptions).subscribe((res: HttpResponse<any>) => {
  console.log(res.headers.get('token-key-name'));
})

How to set a border for an HTML div tag

<style>
p{border: 1px solid red}
div{border: 5px solid blue}

Call me Ishmael.

Just don't call me late for dinner.

Call me Ishmael.

Just don't call me late for dinner.

Converting Varchar Value to Integer/Decimal Value in SQL Server

You can use it without casting such as:

select sum(`stuff`) as mySum from test;

Or cast it to decimal:

select sum(cast(`stuff` as decimal(4,2))) as mySum from test;

SQLFiddle

EDIT

For SQL Server, you can use:

select sum(cast(stuff as decimal(5,2))) as mySum from test;

SQLFiddle

Installing Python 2.7 on Windows 8

there is a simple procedure to do it go to controlpanel->system and security ->system->advanced system settings->advanced->environment variables then add new path enter this in your variable path and values

enter image description here

Objective-C Static Class Level variables

u can rename the class as classA.mm and add C++ features in it.

Push items into mongo array via mongoose

An easy way to do that is to use the following:

var John = people.findOne({name: "John"});
John.friends.push({firstName: "Harry", lastName: "Potter"});
John.save();

how to compare the Java Byte[] array?

have you looked at Arrays.equals()?

Edit: if, as per your comment, the issue is using a byte array as a HashMap key then see this question.

Why doesn't C++ have a garbage collector?

To add to the debate here.

There are known issues with garbage collection, and understanding them helps understanding why there is none in C++.

1. Performance ?

The first complaint is often about performance, but most people don't really realize what they are talking about. As illustrated by Martin Beckett the problem may not be performance per se, but the predictability of performance.

There are currently 2 families of GC that are widely deployed:

  • Mark-And-Sweep kind
  • Reference-Counting kind

The Mark And Sweep is faster (less impact on overall performance) but it suffers from a "freeze the world" syndrome: i.e. when the GC kicks in, everything else is stopped until the GC has made its cleanup. If you wish to build a server that answers in a few milliseconds... some transactions will not live up to your expectations :)

The problem of Reference Counting is different: reference-counting adds overhead, especially in Multi-Threading environments because you need to have an atomic count. Furthermore there is the problem of reference cycles so you need a clever algorithm to detect those cycles and eliminate them (generally implement by a "freeze the world" too, though less frequent). In general, as of today, this kind (even though normally more responsive or rather, freezing less often) is slower than the Mark And Sweep.

I have seen a paper by Eiffel implementers that were trying to implement a Reference Counting Garbage Collector that would have a similar global performance to Mark And Sweep without the "Freeze The World" aspect. It required a separate thread for the GC (typical). The algorithm was a bit frightening (at the end) but the paper made a good job of introducing the concepts one at a time and showing the evolution of the algorithm from the "simple" version to the full-fledged one. Recommended reading if only I could put my hands back on the PDF file...

2. Resources Acquisition Is Initialization (RAII)

It's a common idiom in C++ that you will wrap the ownership of resources within an object to ensure that they are properly released. It's mostly used for memory since we don't have garbage collection, but it's also useful nonetheless for many other situations:

  • locks (multi-thread, file handle, ...)
  • connections (to a database, another server, ...)

The idea is to properly control the lifetime of the object:

  • it should be alive as long as you need it
  • it should be killed when you're done with it

The problem of GC is that if it helps with the former and ultimately guarantees that later... this "ultimate" may not be sufficient. If you release a lock, you'd really like that it be released now, so that it does not block any further calls!

Languages with GC have two work arounds:

  • don't use GC when stack allocation is sufficient: it's normally for performance issues, but in our case it really helps since the scope defines the lifetime
  • using construct... but it's explicit (weak) RAII while in C++ RAII is implicit so that the user CANNOT unwittingly make the error (by omitting the using keyword)

3. Smart Pointers

Smart pointers often appear as a silver bullet to handle memory in C++. Often times I have heard: we don't need GC after all, since we have smart pointers.

One could not be more wrong.

Smart pointers do help: auto_ptr and unique_ptr use RAII concepts, extremely useful indeed. They are so simple that you can write them by yourself quite easily.

When one need to share ownership however it gets more difficult: you might share among multiple threads and there are a few subtle issues with the handling of the count. Therefore, one naturally goes toward shared_ptr.

It's great, that's what Boost for after all, but it's not a silver bullet. In fact, the main issue with shared_ptr is that it emulates a GC implemented by Reference Counting but you need to implement the cycle detection all by yourself... Urg

Of course there is this weak_ptr thingy, but I have unfortunately already seen memory leaks despite the use of shared_ptr because of those cycles... and when you are in a Multi Threaded environment, it's extremely difficult to detect!

4. What's the solution ?

There is no silver bullet, but as always, it's definitely feasible. In the absence of GC one need to be clear on ownership:

  • prefer having a single owner at one given time, if possible
  • if not, make sure that your class diagram does not have any cycle pertaining to ownership and break them with subtle application of weak_ptr

So indeed, it would be great to have a GC... however it's no trivial issue. And in the mean time, we just need to roll up our sleeves.

Android: Center an image

change layout weight according you will get....

Enter this:

 <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_weight="0.03">
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:scaleType="centerInside"
        android:layout_gravity="center"
        android:src="@drawable/logo" />

</LinearLayout>

A circular reference was detected while serializing an object of type 'SubSonic.Schema .DatabaseColumn'.

To sum things up, there are 4 solutions to this:

Solution 1: turn off ProxyCreation for the DBContext and restore it in the end.

    private DBEntities db = new DBEntities();//dbcontext

    public ActionResult Index()
    {
        bool proxyCreation = db.Configuration.ProxyCreationEnabled;
        try
        {
            //set ProxyCreation to false
            db.Configuration.ProxyCreationEnabled = false;

            var data = db.Products.ToList();

            return Json(data, JsonRequestBehavior.AllowGet);
        }
        catch (Exception ex)
        {
            Response.StatusCode = (int)HttpStatusCode.BadRequest;
            return Json(ex.Message);
        }
        finally
        {
            //restore ProxyCreation to its original state
            db.Configuration.ProxyCreationEnabled = proxyCreation;
        }
    }

Solution 2: Using JsonConvert by Setting ReferenceLoopHandling to ignore on the serializer settings.

    //using using Newtonsoft.Json;

    private DBEntities db = new DBEntities();//dbcontext

    public ActionResult Index()
    {
        try
        {
            var data = db.Products.ToList();

            JsonSerializerSettings jss = new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore };
            var result = JsonConvert.SerializeObject(data, Formatting.Indented, jss);

            return Json(result, JsonRequestBehavior.AllowGet);
        }
        catch (Exception ex)
        {
            Response.StatusCode = (int)HttpStatusCode.BadRequest;
            return Json(ex.Message);
        }
    }

Following two solutions are the same, but using a model is better because it's strong typed.

Solution 3: return a Model which includes the needed properties only.

    private DBEntities db = new DBEntities();//dbcontext

    public class ProductModel
    {
        public int Product_ID { get; set;}

        public string Product_Name { get; set;}

        public double Product_Price { get; set;}
    }

    public ActionResult Index()
    {
        try
        {
            var data = db.Products.Select(p => new ProductModel
                                                {
                                                    Product_ID = p.Product_ID,
                                                    Product_Name = p.Product_Name,
                                                    Product_Price = p.Product_Price
                                                }).ToList();

            return Json(data, JsonRequestBehavior.AllowGet);
        }
        catch (Exception ex)
        {
            Response.StatusCode = (int)HttpStatusCode.BadRequest;
            return Json(ex.Message);
        }
    }

Solution 4: return a new dynamic object which includes the needed properties only.

    private DBEntities db = new DBEntities();//dbcontext

    public ActionResult Index()
    {
        try
        {
            var data = db.Products.Select(p => new
                                                {
                                                    Product_ID = p.Product_ID,
                                                    Product_Name = p.Product_Name,
                                                    Product_Price = p.Product_Price
                                                }).ToList();

            return Json(data, JsonRequestBehavior.AllowGet);
        }
        catch (Exception ex)
        {
            Response.StatusCode = (int)HttpStatusCode.BadRequest;
            return Json(ex.Message);
        }
    }