Programs & Examples On #Usort

a function in PHP which provides means for custom collections sorting by using an user-defined comparison function to determine the order of elements

How to query as GROUP BY in django?

An easy solution, but not the proper way is to use raw SQL:

results = Members.objects.raw('SELECT * FROM myapp_members GROUP BY designation')

Another solution is to use the group_by property:

query = Members.objects.all().query
query.group_by = ['designation']
results = QuerySet(query=query, model=Members)

You can now iterate over the results variable to retrieve your results. Note that group_by is not documented and may be changed in future version of Django.

And... why do you want to use group_by? If you don't use aggregation, you can use order_by to achieve an alike result.

Set Google Maps Container DIV width and height 100%

Better late than never! I made mine a class:

.map
{
    position:absolute;
    top:64px;
    width:1100px;
    height:735px;
    overflow:hidden;
    border:1px solid rgb(211,211,211);
    border-radius:3px;
}

and then

<div id="map" class="map"></div>

Qt 5.1.1: Application failed to start because platform plugin "windows" is missing

I had this problem while using QT 5.6, Anaconda 4.3.23, python 3.5.2 and pyinstaller 3.3. I had created a python program with an interface developed using QTcreator, but had to deploy it to other computers, therefore I needed to make an executable, using pyinstaller.

I've found that the problem was solved on my computer if I set the following environment variables:

QT_QPA_PLATFORM_PLUGIN_PATH: %QTDIR%\plugins\platforms\

QTDIR: C:\Miniconda3\pkgs\qt-5.6.2-vc14_3\Library

But this solution only worked on my PC that had conda and qt installed in those folders.

To solve this and make the executable work on any computer, I've had to edit the ".spec" (file first generated by pyinstaller) to include the following line:

datas=[( 'C:\Miniconda3\pkgs\qt-5.6.2-vc14_3\Library\plugins\platforms*.dll', 'platforms' ),]

This solution is based on the answers of Jim G. and CrippledTable

How to printf a 64-bit integer as hex?

The warning from your compiler is telling you that your format specifier doesn't match the data type you're passing to it.

Try using %lx or %llx. For more portability, include inttypes.h and use the PRIx64 macro.

For example: printf("val = 0x%" PRIx64 "\n", val); (note that it's string concatenation)

Get/pick an image from Android's built-in Gallery app programmatically


Retrieve a specific type of file

This example will get a copy of the image.

static final int REQUEST_IMAGE_GET = 1;

public void selectImage() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("image/*");
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(intent, REQUEST_IMAGE_GET);
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_GET && resultCode == RESULT_OK) {
        Bitmap thumbnail = data.getParcelable("data");
        Uri fullPhotoUri = data.getData();
        // Do work with photo saved at fullPhotoUri
        ...
    }
}

Open a specific type of file

When running on 4.4 or higher, you request to open a file that's managed by another app

static final int REQUEST_IMAGE_OPEN = 1;

public void selectImage() {
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
    intent.setType("image/*");
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    // Only the system receives the ACTION_OPEN_DOCUMENT, so no need to test.
    startActivityForResult(intent, REQUEST_IMAGE_OPEN);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_OPEN && resultCode == RESULT_OK) {
        Uri fullPhotoUri = data.getData();
        // Do work with full size photo saved at fullPhotoUri
        ...
    }
}

Original source

HTTP authentication logout via PHP

There's a lot of great - complex - answers here. In my particular case i found a clean and simple fix for the logout. I have yet to test in Edge. On my page that I have logged in to, I have placed a logout link similar to this:

<a href="https://MyDomainHere.net/logout.html">logout</a>

And in the head of that logout.html page (which is also protected by the .htaccess) I have a page refresh similar to this:

<meta http-equiv="Refresh" content="0; url=https://logout:[email protected]/" />

Where you would leave the words "logout" in place to clear the username and password cached for the site.

I will admit that if multiple pages needed to be able to be directly logged in to from the beginning, each of those points of entry would need their own corresponding logout.html page. Otherwise you could centralize the logout by introducing an additional gatekeeper step into the process before the actual login prompt, requiring entry of a phrase to reach a destination of login.

How to get setuptools and easy_install?

Give this link a try --> https://pypi.python.org/pypi/setuptools

I'm assuming you're on Windows (could be wrong) but if you click the green Downloads button, it should take you to a table where you can choose to download a .exe version of setuptools appropriate for your version of Python. All that eggsetup stuff should be taken care of in the executable file.

Let me know if you need more help.

PostgreSQL return result set as JSON array?

Also if you want selected field from table and aggregated then as array .

SELECT json_agg(json_build_object('data_a',a,
                                  'data_b',b,
))  from t;

The result will come .

 [{'data_a':1,'data_b':'value1'}
  {'data_a':2,'data_b':'value2'}]

Java how to replace 2 or more spaces with single space in string and delete leading and trailing spaces

public class RemoveExtraSpacesEfficient {

    public static void main(String[] args) {

        String s = "my    name is    mr    space ";

        char[] charArray = s.toCharArray();

        char prev = s.charAt(0);

        for (int i = 0; i < charArray.length; i++) {
            char cur = charArray[i];
            if (cur == ' ' && prev == ' ') {

            } else {
                System.out.print(cur);
            }
            prev = cur;
        }
    }
}

The above solution is the algorithm with the complexity of O(n) without using any java function.

How do you round a floating point number in Perl?

Negative numbers can add some quirks that people need to be aware of.

printf-style approaches give us correct numbers, but they can result in some odd displays. We have discovered that this method (in my opinion, stupidly) puts in a - sign whether or not it should or shouldn't. For example, -0.01 rounded to one decimal place returns a -0.0, rather than just 0. If you are going to do the printf style approach, and you know you want no decimal, use %d and not %f (when you need decimals, it's when the display gets wonky).

While it's correct and for math no big deal, for display it just looks weird showing something like "-0.0".

For the int method, negative numbers can change what you want as a result (though there are some arguments that can be made they are correct).

The int + 0.5 causes real issues with -negative numbers, unless you want it to work that way, but I imagine most people don't. -0.9 should probably round to -1, not 0. If you know that you want negative to be a ceiling rather than a floor then you can do it in one-liner, otherwise, you might want to use the int method with a minor modification (this obviously only works to get back whole numbers:

my $var = -9.1;
my $tmpRounded = int( abs($var) + 0.5));
my $finalRounded = $var >= 0 ? 0 + $tmpRounded : 0 - $tmpRounded;

Dynamic classname inside ngClass in angular 2

Is basically duplication of the other answers - but I didn't get it completely. maybe someone will finally understand it with this example now.

[ngClass]="['svg-icon', 'recolor-' + recolor, size ? 'size-' + size : '']"

will result for e.g. in

class="svg-icon recolor-red size-m"

Sorting Directory.GetFiles()

A more succinct VB.Net version...is very nice. Thank you. To traverse the list in reverse order, add the reverse method...

For Each fi As IO.FileInfo In filePaths.reverse
  ' Do whatever you wish here
Next

How to calculate 1st and 3rd quartiles?

Coincidentally, this information is captured with the describe method:

df.time_diff.describe()

count    5.000000
mean     0.496667
std      0.032059
min      0.450000
25%      0.483333
50%      0.500000
75%      0.516667
max      0.533333
Name: time_diff, dtype: float64

Convert all first letter to upper case, rest lower for each word

Untested but something like this should work:

var phrase = "THIS IS MY TEXT RIGHT NOW";
var rx = new System.Text.RegularExpressions.Regex(@"(?<=\w)\w");
var newString = rx.Replace(phrase,new MatchEvaluator(m=>m.Value.ToLowerInvariant()));

Essentially it says "preform a regex match on all occurrences of an alphanumeric character that follows another alphanumeric character and then replace it with a lowercase version of itself"

What are some alternatives to ReSharper?

A comprehensive list:

  • CodeRush, by DevExpress. (Considered the main alternative) Either this or ReSharper is the way to go. You cannot go wrong with either. Both have their fans, both are powerful, both have talented teams constantly improving them. We have all benefited from the competition between these two. I won't repeat the many good discussions/comparisons about them that can be found on Stack Overflow and elsewhere. 1

  • JustCode, by Telerik. This is new, still with kinks, but initial reports are positive. An advantage could be liscensing with other Telerik products and integration with them. 1

  • Many of the new Visual Studio 2010 features. See what's been added vs. what you need, it could be that the core install takes care of what you are interested in now.

  • Visual Assist X, More than 50 features make Visual Assist X an incredible productivity tool. Pick a category and learn more, or download a free trial and discover them all. 2

  • VSCommands, VSCommands provides code navigation and generation improvements which will make your everyday coding tasks blazing fast and, together with tens of essential IDE enhancements, it will take your productivity to another level. VSCommands comes in two flavours: Lite (free) and Pro (paid). 3

  • BrockSoft VSAid, VSAid (Visual Studio Aid) is a Microsoft Visual Studio add-in available, at no cost, for both personal and commercial use. Primarily aimed at Visual C++ developers (though useful for any Visual Studio project or solution), VSAid adds a new toolbar to the IDE which adds productivity-enhancing features such as being able to find and open project files quickly and cycle through related files at the click of a mouse button (or the stroke of a key!). 4

VBA general way for pulling data out of SAP

This all depends on what sort of access you have to your SAP system. An ABAP program that exports the data and/or an RFC that your macro can call to directly get the data or have SAP create the file is probably best.

However as a general rule people looking for this sort of answer are looking for an immediate solution that does not require their IT department to spend months customizing their SAP system.

In that case you probably want to use SAP GUI Scripting. SAP GUI scripting allows you to automate the Windows SAP GUI in much the same way as you automate Excel. In fact you can call the SAP GUI directly from an Excel macro. Read up more on it here. The SAP GUI has a macro recording tool much like Excel does. It records macros in VBScript which is nearly identical to Excel VBA and can usually be copied and pasted into an Excel macro directly.

Example Code

Here is a simple example based on a SAP system I have access to.

Public Sub SimpleSAPExport()
  Set SapGuiAuto  = GetObject("SAPGUI") 'Get the SAP GUI Scripting object
  Set SAPApp = SapGuiAuto.GetScriptingEngine 'Get the currently running SAP GUI 
  Set SAPCon = SAPApp.Children(0) 'Get the first system that is currently connected
  Set session = SAPCon.Children(0) 'Get the first session (window) on that connection

  'Start the transaction to view a table
  session.StartTransaction "SE16"

  'Select table T001
  session.findById("wnd[0]/usr/ctxtDATABROWSE-TABLENAME").Text = "T001"
  session.findById("wnd[0]/tbar[1]/btn[7]").Press

  'Set our selection criteria
  session.findById("wnd[0]/usr/txtMAX_SEL").text = "2"
  session.findById("wnd[0]/tbar[1]/btn[8]").press

  'Click the export to file button
  session.findById("wnd[0]/tbar[1]/btn[45]").press

  'Choose the export format
  session.findById("wnd[1]/usr/subSUBSCREEN_STEPLOOP:SAPLSPO5:0150/sub:SAPLSPO5:0150/radSPOPLI-SELFLAG[1,0]").select
  session.findById("wnd[1]/tbar[0]/btn[0]").press

  'Choose the export filename
  session.findById("wnd[1]/usr/ctxtDY_FILENAME").text = "test.txt"
  session.findById("wnd[1]/usr/ctxtDY_PATH").text = "C:\Temp\"

  'Export the file
  session.findById("wnd[1]/tbar[0]/btn[0]").press
End Sub

Script Recording

To help find the names of elements such aswnd[1]/tbar[0]/btn[0] you can use script recording. Click the customize local layout button, it probably looks a bit like this: Customize Local Layout
Then find the Script Recording and Playback menu item.
Script Recording and Playback
Within that the More button allows you to see/change the file that the VB Script is recorded to. The output format is a bit messy, it records things like selecting text, clicking inside a text field, etc.

Edit: Early and Late binding

The provided script should work if copied directly into a VBA macro. It uses late binding, the line Set SapGuiAuto = GetObject("SAPGUI") defines the SapGuiAuto object.

If however you want to use early binding so that your VBA editor might show the properties and methods of the objects you are using, you need to add a reference to sapfewse.ocx in the SAP GUI installation folder.

MongoDB logging all queries

db.adminCommand( { getLog: "*" } )

Then

db.adminCommand( { getLog : "global" } )

pow (x,y) in Java

Additionally for what was said, if you want integer powers of two, then 1 << x (or 1L << x) is a faster way to calculate 2x than Math.pow(2,x) or a multiplication loop, and is guaranteed to give you an int (or long) result.

It only uses the lowest 5 (or 6) bits of x (i.e. x & 31 (or x & 63)), though, shifting between 0 and 31 (or 63) bits.

Spring Boot REST API - request timeout?

In Spring properties files, you can't just specify a number for this property. You also need to specify a unit. So you can say spring.mvc.async.request-timeout=5000ms or spring.mvc.async.request-timeout=5s, both of which will give you a 5-second timeout.

How to display list of repositories from subversion server

Sometimes you may wish to check on the timestamp for when the repo was updated, for getting this handy info you can use the svn -v (verbose) option as in

svn list -v svn://123.123.123.123/svn/repo/path

Ascii/Hex convert in bash

SteinAir's answer above was helpful to me -- thank you! And below is a way it inspired, to convert hex strings to ascii:

for h in $(echo "4161" | sed "s/\(..\)/\1 /g"); do printf `echo "\x$h"`;done
Aa

What is [Serializable] and when should I use it?

Some practical uses for the [Serializable] attribute:

  • Saving object state using binary serialisation; you can very easily 'save' entire object instances in your application to a file or network stream and then recreate them by deserialising - check out the BinaryFormatter class in System.Runtime.Serialization.Formatters.Binary
  • Writing classes whose object instances can be stored on the clipboard using Clipboard.SetData() - nonserialisable classes cannot be placed on the clipboard.
  • Writing classes which are compatible with .NET Remoting; generally, any class instance you pass between application domains (except those which extend from MarshalByRefObject) must be serialisable.

These are the most common usage cases that I have come across.

How to check date of last change in stored procedure or function in SQL server

SELECT name, create_date, modify_date 
FROM sys.objects
WHERE type = 'P'
ORDER BY modify_date DESC

The type for a function is FN rather than P for procedure. Or you can filter on the name column.

How to replace a character from a String in SQL?

This will replace all ? with ':

UPDATE dbo.authors    
SET    city = replace(city, '?', '''')
WHERE city LIKE '%?%'

If you need to update more than one column, you can either change city each time you execute to a different column name, or list the columns like so:

UPDATE dbo.authors    
SET    city = replace(city, '?', '''')
      ,columnA = replace(columnA, '?', '''')
WHERE city LIKE '%?%'
OR columnA LIKE '%?%'

Mips how to store user input string

# This code works fine in QtSpim simulator

.data
    buffer: .space 20
    str1:  .asciiz "Enter string"
    str2:  .asciiz "You wrote:\n"

.text

main:
    la $a0, str1    # Load and print string asking for string
    li $v0, 4
    syscall

    li $v0, 8       # take in input

    la $a0, buffer  # load byte space into address
    li $a1, 20      # allot the byte space for string

    move $t0, $a0   # save string to t0
    syscall

    la $a0, str2    # load and print "you wrote" string
    li $v0, 4
    syscall

    la $a0, buffer  # reload byte space to primary address
    move $a0, $t0   # primary address = t0 address (load pointer)
    li $v0, 4       # print string
    syscall

    li $v0, 10      # end program
    syscall

How to list all the files in a commit?

A combination of "git show --stat" (thanks Ryan) and a couple of sed commands should trim the data down for you:

git show --stat <SHA1> | sed -n "/ [\w]\*|/p" | sed "s/|.\*$//"

That will produce just the list of modified files.

Appending an id to a list if not already present in a string

What you are trying to do can almost certainly be achieved with a set.

>>> x = set([1,2,3])
>>> x.add(2)
>>> x
set([1, 2, 3])
>>> x.add(4)
>>> x.add(4)
>>> x
set([1, 2, 3, 4])
>>> 

using a set's add method you can build your unique set of ids very quickly. Or if you already have a list

unique_ids = set(id_list)

as for getting your inputs in numeric form you can do something like

>>> ids = [int(n) for n in '350882 348521 350166\r\n'.split()]
>>> ids
[350882, 348521, 350166]

Simple and fast method to compare images for similarity

If you want to compare image for similarity,I suggest you to used OpenCV. In OpenCV, there are few feature matching and template matching. For feature matching, there are SURF, SIFT, FAST and so on detector. You can use this to detect, describe and then match the image. After that, you can use the specific index to find number of match between the two images.

How to declare global variables in Android?

Create this subclass

public class MyApp extends Application {
  String foo;
}

In the AndroidManifest.xml add android:name

Example

<application android:name=".MyApp" 
       android:icon="@drawable/icon" 
       android:label="@string/app_name">

How to find the lowest common ancestor of two nodes in any binary tree?

The answers given so far uses recursion or stores, for instance, a path in memory.

Both of these approaches might fail if you have a very deep tree.

Here is my take on this question. When we check the depth (distance from the root) of both nodes, if they are equal, then we can safely move upward from both nodes towards the common ancestor. If one of the depth is bigger then we should move upward from the deeper node while staying in the other one.

Here is the code:

findLowestCommonAncestor(v,w):
  depth_vv = depth(v);
  depth_ww = depth(w);

  vv = v; 
  ww = w;

  while( depth_vv != depth_ww ) {
    if ( depth_vv > depth_ww ) {
      vv = parent(vv);
      depth_vv--;
    else {
      ww = parent(ww);
      depth_ww--;
    }
  }

  while( vv != ww ) {
    vv = parent(vv);
    ww = parent(ww);
  }

  return vv;    

The time complexity of this algorithm is: O(n). The space complexity of this algorithm is: O(1).

Regarding the computation of the depth, we can first remember the definition: If v is root, depth(v) = 0; Otherwise, depth(v) = depth(parent(v)) + 1. We can compute depth as follows:

depth(v):
  int d = 0;
  vv = v;
  while ( vv is not root ) {
    vv = parent(vv);
    d++;
  }
  return d;

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!

Displaying the Indian currency symbol on a website

WebRupee API Available Here:

<script src="http://cdn.jagansindia.in/webrupee" type="text/javascript"></script>

You can also read full details here

Set font-weight using Bootstrap classes

Create in your Site.css (or in another place) a new class named for example .font-bold and set it to your element

.font-bold {
  font-weight: bold;
}

What's "P=NP?", and why is it such a famous question?

A short summary from my humble knowledge:

There are some easy computational problems (like finding the shortest path between two points in a graph), which can be calculated pretty fast ( O(n^k), where n is the size of the input and k is a constant (in the case of graphs, it's the number of vertexes or edges)).

Other problems, like finding a path that crosses every vertex in a graph or getting the RSA private key from the public key is harder (O(e^n)).

But CS speak tells that the problem is that we cannot 'convert' a non-deterministic Turing-machine to a deterministic one, we can, however, transform non-deterministic finite automatons (like the regex parser) into deterministic ones (well, you can, but the run-time of the machine will take long). That is, we have to try every possible path (usually smart CS professors can exclude a few ones).

It's interesting because nobody even has any idea of the solution. Some say it's true, some say it's false, but there is no consensus. Another interesting thing is that a solution would be harmful for public/private key encryptions (like RSA). You could break them as easily as generating an RSA key is now.

And it's a pretty inspiring problem.

Giving height to table and row in Bootstrap

http://jsfiddle.net/isherwood/gfgux

html, body {
    height: 100%;
}
#table-row, #table-col, #table-wrapper {
    height: 80%;
}

<div id="content" class="container">
    <div id="table-row" class="row">
        <div id="table-col" class="col-md-7 col-xs-10 pull-left">
            <p>Hello</p>
            <div id="table-wrapper" class="table-responsive">
                <table class="table table-bordered ">

Pythonic way to check if a list is sorted or not

from functools import reduce

# myiterable can be of any iterable type (including list)
isSorted = reduce(lambda r, e: (r[0] and (r[1] or r[2] <= e), False, e), myiterable, (True, True, None))[0]

The derived reduction value is a 3-part tuple of (sortedSoFarFlag, firstTimeFlag, lastElementValue). It initially starts with (True, True, None), which is also used as the result for an empty list (regarded as sorted because there are no out-of-order elements). As it processes each element it calculates new values for the tuple (using previous tuple values with the next elementValue):

[0] (sortedSoFarFlag) evaluates true if: prev_0 is true and (prev_1 is true or prev_2 <= elementValue)
[1] (firstTimeFlag): False
[2] (lastElementValue): elementValue

The final result of the reduction is a tuple of:

[0]: True/False depending on whether the entire list was in sorted order
[1]: True/False depending on whether the list was empty
[2]: the last element value

The first value is the one we're interested in, so we use [0] to grab that from the reduce result.

How can I initialize C++ object member variables in the constructor?

You're trying to create a ThingOne by using operator= which isn't going to work (incorrect syntax). Also, you're using a class name as a variable name, that is, ThingOne* ThingOne. Firstly, let's fix the variable names:

private:
    ThingOne* t1;
    ThingTwo* t2;

Since these are pointers, they must point to something. If the object hasn't been constructed yet, you'll need to do so explicitly with new in your BigMommaClass constructor:

BigMommaClass::BigMommaClass(int n1, int n2)
{
    t1 = new ThingOne(100);
    t2 = new ThingTwo(n1, n2);
}

Generally initializer lists are preferred for construction however, so it will look like:

BigMommaClass::BigMommaClass(int n1, int n2)
    : t1(new ThingOne(100)), t2(new ThingTwo(n1, n2))
{ }

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

I had this error - stupid mistake was, I was using -p3307 to specify port, whereas I should have used -P3307, i.e. capital P. Small 'p' is for password arg :)

Converting Chart.js canvas chart to image using .toDataUrl() results in blank image

Chart.JS API has changed since this was posted and older examples did not seem to be working for me. here is an updated fiddle that works on the newer versions

HTML:

<body>
    <canvas id="canvas" height="450" width="600"></canvas>
    <img id="url" />
</body>

JS:

function done(){
  alert("haha");
  var url=myLine.toBase64Image();
  document.getElementById("url").src=url;
}

var options = {
  bezierCurve : false,
  animation: {
    onComplete: done
  }
};

var myLine = new 
   Chart(document.getElementById("canvas").getContext("2d"),
     {
        data:lineChartData,
        type:"line",
        options:options
      }
    );

http://jsfiddle.net/KSgV7/585/

How to set selectedIndex of select element using display text?

You can use the HTMLOptionsCollection.namedItem() That means that you have to define your select options to have a name attribute and have the value of the displayed text. e.g California

C# LINQ find duplicates in List

I created a extention to response to this you could includ it in your projects, I think this return the most case when you search for duplicates in List or Linq.

Example:

//Dummy class to compare in list
public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public Person(int id, string name, string surname)
    {
        this.Id = id;
        this.Name = name;
        this.Surname = surname;
    }
}


//The extention static class
public static class Extention
{
    public static IEnumerable<T> getMoreThanOnceRepeated<T>(this IEnumerable<T> extList, Func<T, object> groupProps) where T : class
    { //Return only the second and next reptition
        return extList
            .GroupBy(groupProps)
            .SelectMany(z => z.Skip(1)); //Skip the first occur and return all the others that repeats
    }
    public static IEnumerable<T> getAllRepeated<T>(this IEnumerable<T> extList, Func<T, object> groupProps) where T : class
    {
        //Get All the lines that has repeating
        return extList
            .GroupBy(groupProps)
            .Where(z => z.Count() > 1) //Filter only the distinct one
            .SelectMany(z => z);//All in where has to be retuned
    }
}

//how to use it:
void DuplicateExample()
{
    //Populate List
    List<Person> PersonsLst = new List<Person>(){
    new Person(1,"Ricardo","Figueiredo"), //fist Duplicate to the example
    new Person(2,"Ana","Figueiredo"),
    new Person(3,"Ricardo","Figueiredo"),//second Duplicate to the example
    new Person(4,"Margarida","Figueiredo"),
    new Person(5,"Ricardo","Figueiredo")//third Duplicate to the example
    };

    Console.WriteLine("All:");
    PersonsLst.ForEach(z => Console.WriteLine("{0} -> {1} {2}", z.Id, z.Name, z.Surname));
    /* OUTPUT:
        All:
        1 -> Ricardo Figueiredo
        2 -> Ana Figueiredo
        3 -> Ricardo Figueiredo
        4 -> Margarida Figueiredo
        5 -> Ricardo Figueiredo
        */

    Console.WriteLine("All lines with repeated data");
    PersonsLst.getAllRepeated(z => new { z.Name, z.Surname })
        .ToList()
        .ForEach(z => Console.WriteLine("{0} -> {1} {2}", z.Id, z.Name, z.Surname));
    /* OUTPUT:
        All lines with repeated data
        1 -> Ricardo Figueiredo
        3 -> Ricardo Figueiredo
        5 -> Ricardo Figueiredo
        */
    Console.WriteLine("Only Repeated more than once");
    PersonsLst.getMoreThanOnceRepeated(z => new { z.Name, z.Surname })
        .ToList()
        .ForEach(z => Console.WriteLine("{0} -> {1} {2}", z.Id, z.Name, z.Surname));
    /* OUTPUT:
        Only Repeated more than once
        3 -> Ricardo Figueiredo
        5 -> Ricardo Figueiredo
        */
}

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

For nested dialogs this issue is very common, It works when

AlertDialog.Builder mDialogBuilder = new AlertDialog.Builder(MyActivity.this);

is used instead of

mDialogBuilder = new AlertDialog.Builder(getApplicationContext);

this alternative.

phonegap open link in browser

With Cordova 5.0 and greater the plugin InAppBrowser is renamed in the Cordova plugin registry, so you should install it using

cordova plugin add cordova-plugin-inappbrowser --save

Then use

_x000D_
_x000D_
<a href="#" onclick="window.open('http://www.kidzout.com', '_system');">www.kidzout.com</a>
_x000D_
_x000D_
_x000D_

Cookie blocked/not saved in IFRAME in Internet Explorer

One possible thing to do is to add the domain to allowed sites in tools -> internet options -> privacy -> sites: somedomain.com -> allow -> OK.

Using msbuild to execute a File System Publish Profile

First check the Visual studio version of the developer PC which can publish the solution(project). as shown is for VS 2013

 /p:VisualStudioVersion=12.0

add the above command line to specify what kind of a visual studio version should build the project. As previous answers, this might happen when we are trying to publish only one project, not the whole solution.

So the complete code would be something like this

"C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe" "C:\Program Files (x86)\Jenkins\workspace\Jenkinssecondsample\MVCSampleJenkins\MVCSampleJenkins.csproj" /T:Build;Package /p:Configuration=DEBUG /p:OutputPath="obj\DEBUG" /p:DeployIisAppPath="Default Web Site/jenkinsdemoapp" /p:VisualStudioVersion=12.0

What are valid values for the id attribute in HTML?

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

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

Get webpage contents with Python?

If you ask me. try this one

import urllib2
resp = urllib2.urlopen('http://hiscore.runescape.com/index_lite.ws?player=zezima')

and read the normal way ie

page = resp.read()

Good luck though

What is the first character in the sort order used by Windows Explorer?

TLDR; technically space sorts before exclamation mar, and can be used by preceding it with ' or - (which will be ignored in sorting), but exclamation mark follows right after space, and is easier to use.

On windows 7 at least, a minus sign (-) and (') seem to be ignored in a name except for one quirk: in a name that is otherwise identical, the ' will be sorted before -, for example: (a'a) will sort above (a-a)

Empty string will sort above everything else, which means for example aa will sort above aaa because the 'empty string' after two a letters will sort before the third 'a'.

This also means that aa will be sorted above a'a because the 'empty string' between two a letters will sort above the ' mark.

What follows then is, ' alone will sort first, because technically it's an empty string. However adding for example letters behind it will sort the name as if the ' didn't exist.

Since the first 'unignored' character (as far as I know) is space, in case you want to sort 'real names' above others, the best way to go would be ' followed by space, and then the name you want to actually use. For example: (' first)

You can of course top that by using more than one space in the strong, such as (' firster) and (' firstest) with two and three blanks before the f.

While minus sign sorts below ' in otherwise similar name, there's no other difference in sorting (that I know of), and I find minus sign visually clearer, so if I want to put something on top of list, I'd use minus followed by space, then the 'actual name', for example: (- first file -)

If you are worried about using space on the filename, then exclamation mark (!) is the next best thing - and since it can appear as first character on a string, it's easier to use.

Change color of Back button in navigation bar

I prefer custom NavigationController rather than setting global ui, or put in ViewController.

Here is my solution


class AppNavigationController : UINavigationController {

  override func viewDidLoad() {
    super.viewDidLoad()
    self.delegate = self
  }

  override func viewWillAppear(_ animated: Bool) {

  }

}
extension AppNavigationController : UINavigationControllerDelegate {

  func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
    let backButtonItem = UIBarButtonItem(
      title: "   ",
      style: UIBarButtonItem.Style.plain,
      target: nil,
      action: nil)
    backButtonItem.tintColor = UIColor.gray
    viewController.navigationItem.backBarButtonItem = backButtonItem
  }

  func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {

  }

}

Also you don't need to mess with Apple Api like EKEventEditViewController,PickerViewController and so on if you use global settings ui like UIBarButtonItem.appearance().tintColor = .white

Getting files by creation date in .NET

This returns the last modified date and its age.

DateTime.Now.Subtract(System.IO.File.GetLastWriteTime(FilePathwithName).Date)

How to sleep for five seconds in a batch file/cmd

It can be done with two simple lines in a batch file: write a temporary .vbs file in the %temp% folder and call it:

echo WScript.Sleep(5000) >"%temp%\sleep.vbs"
cscript "%temp%\sleep.vbs"

Best way to check if MySQL results returned in PHP?

If you would still like to perform the action if the $result is invalid:

if(!mysql_num_rows($result))
    // Do stuff

This will account for a 0 and the false that is returned by mysql_num_rows() on failure.

How to add element into ArrayList in HashMap

First you have to add an ArrayList to the Map

ArrayList<Item> al = new ArrayList<Item>();

Items.add("theKey", al); 

then you can add an item to the ArrayLIst that is inside the Map like this:

Items.get("theKey").add(item);  // item is an object of type Item

What does the fpermissive flag do?

Right from the docs:

-fpermissive
Downgrade some diagnostics about nonconformant code from errors to warnings. Thus, using -fpermissive will allow some nonconforming code to compile.

Bottom line: don't use it unless you know what you are doing!

Android Studio and Gradle build error

I installed Android Studio on an old WinXP with only for me option. After install I did the new project wizard and when opening the new project a got some Gradle error with some failed path to my instalation dir. c:/Document"#¤!"#¤ and settins/...

The I uninstalled and did a new install with option for all users (C:/Programs/..) then I opend the previous created project with no errors.

So it might be a path problem. (Just spent 10 sec debugging, so I might be wrong but it solved my gradle error)

Generating HTML email body in C#

You might want to have a look at some of the template frameworks that are available at the moment. Some of them are spin offs as a result of MVC but that isn't required. Spark is a good one.

Calculate mean across dimension in a 2D array

a.mean() takes an axis argument:

In [1]: import numpy as np

In [2]: a = np.array([[40, 10], [50, 11]])

In [3]: a.mean(axis=1)     # to take the mean of each row
Out[3]: array([ 25. ,  30.5])

In [4]: a.mean(axis=0)     # to take the mean of each col
Out[4]: array([ 45. ,  10.5])

Or, as a standalone function:

In [5]: np.mean(a, axis=1)
Out[5]: array([ 25. ,  30.5])

The reason your slicing wasn't working is because this is the syntax for slicing:

In [6]: a[:,0].mean() # first column
Out[6]: 45.0

In [7]: a[:,1].mean() # second column
Out[7]: 10.5

Add horizontal scrollbar to html table

//Representation of table
<div class="search-table-outter">
<table class="table table-responsive search-table inner">
</table>
</div>

//Css to make Horizontal Dropdown

<style>

    .search-table{table-layout: auto; margin:40px auto 0px auto; }
    .search-table, td, th {
        border-collapse: collapse;
    }
th{padding:20px 7px; font-size:15px; color:#444;}
td{padding:5px 10px; height:35px;}
    .search-table-outter { overflow-x: scroll; }
th, td { min-width: 200px; }


</style>

How to remove illegal characters from path and filenames?

For starters, Trim only removes characters from the beginning or end of the string. Secondly, you should evaluate if you really want to remove the offensive characters, or fail fast and let the user know their filename is invalid. My choice is the latter, but my answer should at least show you how to do things the right AND wrong way:

StackOverflow question showing how to check if a given string is a valid file name. Note you can use the regex from this question to remove characters with a regular expression replacement (if you really need to do this).

checking memory_limit in PHP

Try to convert the value first (eg: 64M -> 64 * 1024 * 1024). After that, do comparison and print the result.

<?php
$memory_limit = ini_get('memory_limit');
if (preg_match('/^(\d+)(.)$/', $memory_limit, $matches)) {
    if ($matches[2] == 'M') {
        $memory_limit = $matches[1] * 1024 * 1024; // nnnM -> nnn MB
    } else if ($matches[2] == 'K') {
        $memory_limit = $matches[1] * 1024; // nnnK -> nnn KB
    }
}

$ok = ($memory_limit >= 64 * 1024 * 1024); // at least 64M?

echo '<phpmem>';
echo '<val>' . $memory_limit . '</val>';
echo '<ok>' . ($ok ? 1 : 0) . '</ok>';
echo '</phpmem>';

Please note that the above code is just an idea. Don't forget to handle -1 (no memory limit), integer-only value (value in bytes), G (value in gigabytes), k/m/g (value in kilobytes, megabytes, gigabytes because shorthand is case-insensitive), etc.

Django check for any exists for a query

Use count():

sc=scorm.objects.filter(Header__id=qp.id)

if sc.count() > 0:
   ...

The advantage over e.g. len() is, that the QuerySet is not yet evaluated:

count() performs a SELECT COUNT(*) behind the scenes, so you should always use count() rather than loading all of the record into Python objects and calling len() on the result.

Having this in mind, When QuerySets are evaluated can be worth reading.


If you use get(), e.g. scorm.objects.get(pk=someid), and the object does not exists, an ObjectDoesNotExist exception is raised:

from django.core.exceptions import ObjectDoesNotExist
try:
    sc = scorm.objects.get(pk=someid)
except ObjectDoesNotExist:
    print ...

Update: it's also possible to use exists():

if scorm.objects.filter(Header__id=qp.id).exists():
    ....

Returns True if the QuerySet contains any results, and False if not. This tries to perform the query in the simplest and fastest way possible, but it does execute nearly the same query as a normal QuerySet query.

Python strip() multiple characters?

I did a time test here, using each method 100000 times in a loop. The results surprised me. (The results still surprise me after editing them in response to valid criticism in the comments.)

Here's the script:

import timeit

bad_chars = '(){}<>'

setup = """import re
import string
s = 'Barack (of Washington)'
bad_chars = '(){}<>'
rgx = re.compile('[%s]' % bad_chars)"""

timer = timeit.Timer('o = "".join(c for c in s if c not in bad_chars)', setup=setup)
print "List comprehension: ",  timer.timeit(100000)


timer = timeit.Timer("o= rgx.sub('', s)", setup=setup)
print "Regular expression: ", timer.timeit(100000)

timer = timeit.Timer('for c in bad_chars: s = s.replace(c, "")', setup=setup)
print "Replace in loop: ", timer.timeit(100000)

timer = timeit.Timer('s.translate(string.maketrans("", "", ), bad_chars)', setup=setup)
print "string.translate: ", timer.timeit(100000)

Here are the results:

List comprehension:  0.631745100021
Regular expression:  0.155561923981
Replace in loop:  0.235936164856
string.translate:  0.0965719223022

Results on other runs follow a similar pattern. If speed is not the primary concern, however, I still think string.translate is not the most readable; the other three are more obvious, though slower to varying degrees.

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

You can just use exec to replace your current shell with a new shell:

Switch to bash:

exec bash

Switch to zsh:

exec zsh

This won't affect new terminal windows or anything, but it's convenient.

How can I add a .npmrc file?

There are a few different points here:

  1. Where is the .npmrc file created.
  2. How can you download private packages

Running npm config ls -l will show you all the implicit settings for npm, including what it thinks is the right place to put the .npmrc. But if you have never logged in (using npm login) it will be empty. Simply log in to create it.

Another thing is #2. You can actually do that by putting a .npmrc file in the NPM package's root. It will then be used by NPM when authenticating. It also supports variable interpolation from your shell so you could do stuff like this:

; Get the auth token to use for fetching private packages from our private scope
; see http://blog.npmjs.org/post/118393368555/deploying-with-npm-private-modules
; and also https://docs.npmjs.com/files/npmrc
//registry.npmjs.org/:_authToken=${NPM_TOKEN}

Pointers

How to start an Intent by passing some parameters to it?

putExtra() : This method sends the data to another activity and in parameter, we have to pass key-value pair.

Syntax: intent.putExtra("key", value);

Eg: intent.putExtra("full_name", "Vishnu Sivan");

Intent intent=getIntent() : It gets the Intent from the previous activity.

fullname = intent.getStringExtra(“full_name”) : This line gets the string form previous activity and in parameter, we have to pass the key which we have mentioned in previous activity.

Sample Code:

Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("firstName", "Vishnu");
intent.putExtra("lastName", "Sivan");
startActivity(intent);

html5 audio player - jquery toggle click play/pause?

Here is my solution using jQuery

<script type="text/javascript">
    $('#mtoogle').toggle(
        function () {
            document.getElementById('playTune').pause();
        },
        function () {
            document.getElementById('playTune').play();
        }
    );
</script>

And the working demo

http://demo.ftutorials.com/html5-audio/

Builder Pattern in Effective Java

You are trying access a non-static class in a static way. Change Builder to static class Builder and it should work.

The example usage you give fails because there is no instance of Builder present. A static class for all practical purposes is always instantiated. If you don't make it static, you'd need to say:

Widget = new Widget.Builder(10).setparm1(1).setparm2(3).build();

Because you would need to construct a new Builder every time.

read word by word from file in C++

First of all, don't loop while (!eof()), it will not work as you expect it to because the eofbit will not be set until after a failed read due to end of file.

Secondly, the normal input operator >> separates on whitespace and so can be used to read "words":

std::string word;
while (file >> word)
{
    ...
}

syntax for creating a dictionary into another dictionary in python

Do you want to insert one dictionary into the other, as one of its elements, or do you want to reference the values of one dictionary from the keys of another?

Previous answers have already covered the first case, where you are creating a dictionary within another dictionary.

To re-reference the values of one dictionary into another, you can use dict.update:

>>> d1 = {1: [1]}
>>> d2 = {2: [2]}
>>> d1.update(d2)
>>> d1
{1: [1], 2: [2]}

A change to a value that's present in both dictionaries will be visible in both:

>>> d1[2].append('appended')
>>> d1
{1: [1], 2: [2, 'appended']}
>>> d2
{2: [2, 'appended']}

This is the same as copying the value over or making a new dictionary with it, i.e.

>>> d3 = {1: d1[1]}
>>> d3[1].append('appended from d3')
>>> d1[1]
[1, 'appended from d3']

Easiest way to detect Internet connection on iOS?

I also was not happy with the Internet checking options available (Why is this not a native API?!?!)

My own issue was with 100% packet loss -- when a device is connected to the router, but the router is not connected to the Internet. Reachability and others will hang for ages. I created a utility singleton class to deal with that by adding an asynch time-out. It works fine in my app. Hope it helps. Here's the link on github:

https://github.com/fareast555/TFInternetChecker

Impersonate tag in Web.Config

The identity section goes under the system.web section, not under authentication:

<system.web>
  <authentication mode="Windows"/>
  <identity impersonate="true" userName="foo" password="bar"/>
</system.web>

What does --net=host option in Docker command really do?

After the docker installation you have 3 networks by default:

docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
f3be8b1ef7ce        bridge              bridge              local
fbff927877c1        host                host                local
023bb5940080        none                null                local

I'm trying to keep this simple. So if you start a container by default it will be created inside the bridge (docker0) network.

$ docker run -d jenkins
1498e581cdba        jenkins             "/bin/tini -- /usr..."   3 minutes ago       Up 3 minutes        8080/tcp, 50000/tcp   friendly_bell

In the dockerfile of jenkins the ports 8080 and 50000 are exposed. Those ports are opened for the container on its bridge network. So everything inside that bridge network can access the container on port 8080 and 50000. Everything in the bridge network is in the private range of "Subnet": "172.17.0.0/16", If you want to access them from the outside you have to map the ports with -p 8080:8080. This will map the port of your container to the port of your real server (the host network). So accessing your server on 8080 will route to your bridgenetwork on port 8080.

Now you also have your host network. Which does not containerize the containers networking. So if you start a container in the host network it will look like this (it's the first one):

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                 NAMES
1efd834949b2        jenkins             "/bin/tini -- /usr..."   6 minutes ago       Up 6 minutes                              eloquent_panini
1498e581cdba        jenkins             "/bin/tini -- /usr..."   10 minutes ago      Up 10 minutes       8080/tcp, 50000/tcp   friendly_bell

The difference is with the ports. Your container is now inside your host network. So if you open port 8080 on your host you will acces the container immediately.

$ sudo iptables -I INPUT 5 -p tcp -m tcp --dport 8080 -j ACCEPT

I've opened port 8080 in my firewall and when I'm now accesing my server on port 8080 I'm accessing my jenkins. I think this blog is also useful to understand it better.

SQL SELECT everything after a certain character

Try this (it should work if there are multiple '=' characters in the string):

SELECT RIGHT(supplier_reference, (CHARINDEX('=',REVERSE(supplier_reference),0))-1) FROM ps_product

Java String import

import java.lang.String;

This is an unnecessary import. java.lang classes are always implicitly imported. This means that you do not have to import them manually (explicitly).

How to check if a row exists in MySQL? (i.e. check if an email exists in MySQL)

There are multiple ways to check if a value exists in the database. Let me demonstrate how this can be done properly with PDO and mysqli.

PDO

PDO is the simpler option. To find out whether a value exists in the database you can use prepared statement and fetchColumn(). There is no need to fetch any data so we will only fetch 1 if the value exists.

<?php

// Connection code. 
$options = [
    \PDO::ATTR_ERRMODE            => \PDO::ERRMODE_EXCEPTION,
    \PDO::ATTR_EMULATE_PREPARES   => false,
];
$pdo = new \PDO('mysql:host=localhost;port=3306;dbname=test;charset=utf8mb4', 'testuser', 'password', $options);

// Prepared statement
$stmt = $pdo->prepare('SELECT 1 FROM tblUser WHERE email=?');
$stmt->execute([$_POST['email']]);
$exists = $stmt->fetchColumn(); // either 1 or null

if ($exists) {
    echo 'Email exists in the database.';
} else {
    // email doesn't exist yet
}

For more examples see: How to check if email exists in the database?

MySQLi

As always mysqli is a little more cumbersome and more restricted, but we can follow a similar approach with prepared statement.

<?php

// Connection code
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new \mysqli('localhost', 'testuser', 'password', 'test');
$mysqli->set_charset('utf8mb4');

// Prepared statement
$stmt = $mysqli->prepare('SELECT 1 FROM tblUser WHERE email=?');
$stmt->bind_param('s', $_POST['email']);
$stmt->execute();
$exists = (bool) $stmt->get_result()->fetch_row(); // Get the first row from result and cast to boolean

if ($exists) {
    echo 'Email exists in the database.';
} else {
    // email doesn't exist yet
}

Instead of casting the result row(which might not even exist) to boolean, you can also fetch COUNT(1) and read the first item from the first row using fetch_row()[0]

For more examples see: How to check whether a value exists in a database using mysqli prepared statements

Minor remarks

  • If someone suggests you to use mysqli_num_rows(), don't listen to them. This is a very bad approach and could lead to performance issues if misused.
  • Don't use real_escape_string(). This is not meant to be used as a protection against SQL injection. If you use prepared statements correctly you don't need to worry about any escaping.
  • If you want to check if a row exists in the database before you try to insert a new one, then it is better not to use this approach. It is better to create a unique key in the database and let it throw an exception if a duplicate value exists.

What is the best way to uninstall gems from a rails3 project?

I seemed to solve this by manually removing the unicorn gem via bundler ("sudo bundler exec gem uninstall unicorn"), then rebundling ("sudo bundle install").

Not sure why it happened though, although the above fix does seem to work.

Facebook API - How do I get a Facebook user's profile image through the Facebook API (without requiring the user to "Allow" the application)

To show:

50x50 pixels

<img src="//graph.facebook.com/{{fid}}/picture">

200 pixels width

<img src="//graph.facebook.com/{{fid}}/picture?type=large">

To save (using PHP)

NOTE: Don't use this. See @Foreever's comment below.

$img = file_get_contents('https://graph.facebook.com/'.$fid.'/picture?type=large');
$file = dirname(__file__).'/avatar/'.$fid.'.jpg';
file_put_contents($file, $img);

Where $fid is your user id on Facebook.

NOTE: In case of images marked as "18+" you will need a valid access_token from a 18+ user:

<img src="//graph.facebook.com/{{fid}}/picture?access_token={{access_token}}">

UPDATE 2015:

Graph API v2.0 can't be queried using usernames, you should use userId always.

Linux: command to open URL in default browser

In Java (version 6+), you can also do:

Desktop d = Desktop.getDesktop();
d.browse(uri);

Though this won't work on all Linuxes. At the time of writing, Gnome is supported, KDE isn't.

How do I get the logfile from an Android device?

I would use something of this sort :

$adb logcat -d > logcat.txt

The -d option dumps the entire circular buffer into the text file and if you are looking for a particular action/intent try

$adb logcat -d | grep 'com.whatever.you.are.looking.for' -B 100 -A 100 > shorterlog.txt

Hope this helps :)

How do I change the font color in an html table?

if you need to change specific option from the select menu you can do it like this

option[value="Basic"] {
  color:red;
 }

or you can change them all

select {
  color:red;
}

Counter exit code 139 when running, but gdb make it through

this error is also caused by null pointer reference. if you are using a pointer who is not initialized then it causes this error.

to check either a pointer is initialized or not you can try something like

Class *pointer = new Class();
if(pointer!=nullptr){
    pointer->myFunction();
}

ERROR 1130 (HY000): Host '' is not allowed to connect to this MySQL server

mysql> CREATE USER 'name'@'%' IDENTIFIED BY 'passWord'; Query OK, 0 rows affected (0.00 sec)

mysql> GRANT ALL PRIVILEGES ON . TO 'name'@'%'; Query OK, 0 rows affected (0.00 sec)

mysql> FLUSH PRIVILEGES; Query OK, 0 rows affected (0.00 sec)

mysql>

  1. Make sure you have your name and % the right way round
  2. Makes sure you have added your port 3306 to any firewall you may be running (although this will give a different error message)

hope this helps someone...

How can I install pip on Windows?

2014 UPDATE:

1) If you have installed Python 3.4 or later, pip is included with Python and should already be working on your system.

2) If you are running a version below Python 3.4 or if pip was not installed with Python 3.4 for some reason, then you'd probably use pip's official installation script get-pip.py. The pip installer now grabs setuptools for you, and works regardless of architecture (32-bit or 64-bit).

The installation instructions are detailed here and involve:

To install or upgrade pip, securely download get-pip.py.

Then run the following (which may require administrator access):

python get-pip.py

To upgrade an existing setuptools (or distribute), run pip install -U setuptools

I'll leave the two sets of old instructions below for posterity.

OLD Answers:

For Windows editions of the 64 bit variety - 64-bit Windows + Python used to require a separate installation method due to ez_setup, but I've tested the new distribute method on 64-bit Windows running 32-bit Python and 64-bit Python, and you can now use the same method for all versions of Windows/Python 2.7X:

OLD Method 2 using distribute:

  1. Download distribute - I threw mine in C:\Python27\Scripts (feel free to create a Scripts directory if it doesn't exist.
  2. Open up a command prompt (on Windows you should check out conemu2 if you don't use PowerShell) and change (cd) to the directory you've downloaded distribute_setup.py to.
  3. Run distribute_setup: python distribute_setup.py (This will not work if your python installation directory is not added to your path - go here for help)
  4. Change the current directory to the Scripts directory for your Python installation (C:\Python27\Scripts) or add that directory, as well as the Python base installation directory to your %PATH% environment variable.
  5. Install pip using the newly installed setuptools: easy_install pip

The last step will not work unless you're either in the directory easy_install.exe is located in (C:\Python27\Scripts would be the default for Python 2.7), or you have that directory added to your path.

OLD Method 1 using ez_setup:

from the setuptools page --

Download ez_setup.py and run it; it will download the appropriate .egg file and install it for you. (Currently, the provided .exe installer does not support 64-bit versions of Python for Windows, due to a distutils installer compatibility issue.

After this, you may continue with:

  1. Add c:\Python2x\Scripts to the Windows path (replace the x in Python2x with the actual version number you have installed)
  2. Open a new (!) DOS prompt. From there run easy_install pip

Python name 'os' is not defined

Just add:

import os

in the beginning, before:

from settings import PROJECT_ROOT

This will import the python's module os, which apparently is used later in the code of your module without being imported.

How to get the size of a string in Python?

If you are talking about the length of the string, you can use len():

>>> s = 'please answer my question'
>>> len(s)  # number of characters in s
25

If you need the size of the string in bytes, you need sys.getsizeof():

>>> import sys
>>> sys.getsizeof(s)
58

Also, don't call your string variable str. It shadows the built-in str() function.

Default fetch type for one-to-one, many-to-one and one-to-many in Hibernate

For Single valued associations, i.e.-One-to-One and Many-to-One:-
Default Lazy=proxy
Proxy lazy loading:- This implies a proxy object of your associated entity is loaded. This means that only the id connecting the two entities is loaded for the proxy object of associated entity.
Eg: A and B are two entities with Many to one association. ie: There may be multiple A's for every B. Every object of A will contain a reference of B.
`

public class A{
    int aid;
    //some other A parameters;
    B b;
}
public class B{
    int bid;
     //some other B parameters;
}

`
The relation A will contain columns(aid,bid,...other columns of entity A).
The relation B will contain columns(bid,...other columns of entity B)

Proxy implies when A is fetched, only id is fetched for B and stored into a proxy object of B which contains only id. Proxy object of B is a an object of a proxy-class which is a subclass of B with only minimal fields. Since bid is already part of relation A, it is not necessary to fire a query to get bid from the relation B. Other attributes of entity B are lazily loaded only when a field other than bid is accessed.

For Collections, i.e.-Many-to-Many and One-to-Many:-
Default Lazy=true


Please also note that the fetch strategy(select,join etc) can override lazy. ie: If lazy='true' and fetch='join', fetching of A will also fetch B or Bs(In case of collections). You can get the reason if you think about it.
Default fetch for single valued association is "join".
Default fetch for collections is "select". Please verify the last two lines. I have deduced that logically.

How to select first parent DIV using jQuery?

Use .closest() to traverse up the DOM tree up to the specified selector.

var classes = $(this).parent().closest('div').attr('class').split(' '); // this gets the parent classes.

How do I print a list of "Build Settings" in Xcode project?

UPDATE: This list is getting a little out dated (it was generated with Xcode 4.1). You should run the command suggested by dunedin15.

dunedin15's answer can give inaccurate results for some edge-cases, such as when debugging build settings of a static lib for an Archive build, see Slipp D. Thompson's answer for a more robust output.

Original Answer

Variable                                  Example
PATH                                      "/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
LANG                                      en_US.US-ASCII
IPHONEOS_DEPLOYMENT_TARGET                4.1
ACTION                                    build
AD_HOC_CODE_SIGNING_ALLOWED               NO
ALTERNATE_GROUP                           staff
ALTERNATE_MODE                            u+w,go-w,a+rX
ALTERNATE_OWNER                           username
ALWAYS_SEARCH_USER_PATHS                  YES
APPLE_INTERNAL_DEVELOPER_DIR              /AppleInternal/Developer
APPLE_INTERNAL_DIR                        /AppleInternal
APPLE_INTERNAL_DOCUMENTATION_DIR          /AppleInternal/Documentation
APPLE_INTERNAL_LIBRARY_DIR                /AppleInternal/Library
APPLE_INTERNAL_TOOLS                      /AppleInternal/Developer/Tools
APPLY_RULES_IN_COPY_FILES                 NO
ARCHS                                     "armv6 armv7"
ARCHS_STANDARD_32_64_BIT                  "armv6 armv7"
ARCHS_STANDARD_32_BIT                     "armv6 armv7"
ARCHS_UNIVERSAL_IPHONE_OS                 armv7
AVAILABLE_PLATFORMS                       "iphonesimulator macosx iphoneos"
BUILD_COMPONENTS                          "headers build"
BUILD_DIR                                 "/Users/username/Library/Developer/Xcode/DerivedData/project-dxdgjvgsvvbhowgjqouevhmvgxgf/ArchiveIntermediates/Project Distribution/BuildProductsPath"
BUILD_ROOT                                "/Users/username/Library/Developer/Xcode/DerivedData/project-dxdgjvgsvvbhowgjqouevhmvgxgf/ArchiveIntermediates/Project Distribution/BuildProductsPath"
BUILD_STYLE                    
BUILD_VARIANTS                             normal
BUILT_PRODUCTS_DIR                         "/Users/username/Library/Developer/Xcode/DerivedData/project-dxdgjvgsvvbhowgjqouevhmvgxgf/ArchiveIntermediates/Project Distribution/BuildProductsPath/Distribution-iphoneos"
CACHE_ROOT                                 /var/folders/2x/rvb2r9s16mq6r318zxvn0lk80000gn/C/com.apple.Xcode.501
CCHROOT                                    /var/folders/2x/rvb2r9s16mq6r318zxvn0lk80000gn/C/com.apple.Xcode.501
CHMOD                                      /bin/chmod
CHOWN                                      /usr/sbin/chown
CLASS_FILE_DIR                             "/Users/username/Library/Developer/Xcode/DerivedData/project-dxdgjvgsvvbhowgjqouevhmvgxgf/ArchiveIntermediates/Project Distribution/IntermediateBuildFilesPath/project.build/Distribution-iphoneos/Project.build/JavaClasses"
CLEAN_PRECOMPS                             YES
CLONE_HEADERS                              NO
CODESIGNING_FOLDER_PATH                    "/Users/username/Library/Developer/Xcode/DerivedData/project-dxdgjvgsvvbhowgjqouevhmvgxgf/ArchiveIntermediates/Project Distribution/InstallationBuildProductsLocation/Applications/project.app"
CODE_SIGNING_ALLOWED                       YES
CODE_SIGNING_REQUIRED                      YES
CODE_SIGN_CONTEXT_CLASS                    XCiPhoneOSCodeSignContext
CODE_SIGN_IDENTITY                         "iPhone Distribution"
COMBINE_HIDPI_IMAGES                       NO
COMPOSITE_SDK_DIRS                         /var/folders/2x/rvb2r9s16mq6r318zxvn0lk80000gn/C/com.apple.Xcode.501/CompositeSDKs
COMPRESS_PNG_FILES                         YES
CONFIGURATION                              Distribution
CONFIGURATION_BUILD_DIR                    "/Users/username/Library/Developer/Xcode/DerivedData/project-dxdgjvgsvvbhowgjqouevhmvgxgf/ArchiveIntermediates/Project Distribution/BuildProductsPath/Distribution-iphoneos"
CONFIGURATION_TEMP_DIR                     "/Users/username/Library/Developer/Xcode/DerivedData/project-dxdgjvgsvvbhowgjqouevhmvgxgf/ArchiveIntermediates/Project Distribution/IntermediateBuildFilesPath/project.build/Distribution-iphoneos"
CONTENTS_FOLDER_PATH                       project.app/Contents
COPYING_PRESERVES_HFS_DATA                 NO
COPY_PHASE_STRIP                           YES
COPY_RESOURCES_FROM_STATIC_FRAMEWORKS      YES
CP                                         /bin/cp
CURRENT_ARCH                               armv7
CURRENT_VARIANT                            normal
DEAD_CODE_STRIPPING                        YES
DEBUGGING_SYMBOLS                          YES
DEBUG_INFORMATION_FORMAT                   dwarf-with-dsym
DEPLOYMENT_LOCATION                        YES
DEPLOYMENT_POSTPROCESSING                  YES
DERIVED_FILES_DIR                          "/Users/username/Library/Developer/Xcode/DerivedData/project-dxdgjvgsvvbhowgjqouevhmvgxgf/ArchiveIntermediates/Project Distribution/IntermediateBuildFilesPath/project.build/Distribution-iphoneos/Project.build/DerivedSources"
DERIVED_FILE_DIR                           "/Users/username/Library/Developer/Xcode/DerivedData/project-dxdgjvgsvvbhowgjqouevhmvgxgf/ArchiveIntermediates/Project Distribution/IntermediateBuildFilesPath/project.build/Distribution-iphoneos/Project.build/DerivedSources"
DERIVED_SOURCES_DIR                        "/Users/username/Library/Developer/Xcode/DerivedData/project-dxdgjvgsvvbhowgjqouevhmvgxgf/ArchiveIntermediates/Project Distribution/IntermediateBuildFilesPath/project.build/Distribution-iphoneos/Project.build/DerivedSources"
DEVELOPER_APPLICATIONS_DIR                 /Developer/Applications
DEVELOPER_BIN_DIR                          /Developer/usr/bin
DEVELOPER_DIR                              /Developer
DEVELOPER_FRAMEWORKS_DIR                   /Developer/Library/Frameworks
DEVELOPER_FRAMEWORKS_DIR_QUOTED            "\"/Developer/Library/Frameworks\""
DEVELOPER_LIBRARY_DIR                      /Developer/Library
DEVELOPER_SDK_DIR                          /Developer/SDKs
DEVELOPER_TOOLS_DIR                        /Developer/Tools
DEVELOPER_USR_DIR                          /Developer/usr
DEVELOPMENT_LANGUAGE                       English
DOCUMENTATION_FOLDER_PATH                  project.app/English.lproj/Documentation
DO_HEADER_SCANNING_IN_JAM                  NO
DSTROOT                                    "/Users/username/Library/Developer/Xcode/DerivedData/project-dxdgjvgsvvbhowgjqouevhmvgxgf/ArchiveIntermediates/Project Distribution/InstallationBuildProductsLocation"
DWARF_DSYM_FILE_NAME                       project.app.dSYM
DWARF_DSYM_FILE_SHOULD_ACCOMPANY_PRODUCT   NO
DWARF_DSYM_FOLDER_PATH                    "/Users/username/Library/Developer/Xcode/DerivedData/project-dxdgjvgsvvbhowgjqouevhmvgxgf/ArchiveIntermediates/Project Distribution/BuildProductsPath/Distribution-iphoneos"
EFFECTIVE_PLATFORM_NAME                    -iphoneos
EMBEDDED_PROFILE_NAME                      embedded.mobileprovision
ENABLE_HEADER_DEPENDENCIES                 YES
ENABLE_OPENMP_SUPPORT                      NO
ENTITLEMENTS_ALLOWED                       YES
ENTITLEMENTS_REQUIRED                      YES
EXCLUDED_INSTALLSRC_SUBDIRECTORY_PATTERNS  ".svn CVS"
EXECUTABLES_FOLDER_PATH                    project.app/Executables
EXECUTABLE_FOLDER_PATH                     project.app
EXECUTABLE_NAME                            project
EXECUTABLE_PATH                            project.app/project
FILE_LIST                                  "/Users/username/Library/Developer/Xcode/DerivedData/project-dxdgjvgsvvbhowgjqouevhmvgxgf/ArchiveIntermediates/Project Distribution/IntermediateBuildFilesPath/project.build/Distribution-iphoneos/Project.build/Objects/LinkFileList"
FIXED_FILES_DIR                            "/Users/username/Library/Developer/Xcode/DerivedData/project-dxdgjvgsvvbhowgjqouevhmvgxgf/ArchiveIntermediates/Project Distribution/IntermediateBuildFilesPath/project.build/Distribution-iphoneos/Project.build/FixedFiles"
FRAMEWORKS_FOLDER_PATH                     project.app/Frameworks
FRAMEWORK_FLAG_PREFIX                      -framework
FRAMEWORK_SEARCH_PATHS                     "\"/Users/username/Library/Developer/Xcode/DerivedData/project-dxdgjvgsvvbhowgjqouevhmvgxgf/ArchiveIntermediates/Project Distribution/BuildProductsPath/Distribution-iphoneos\" "
FRAMEWORK_VERSION                          A
FULL_PRODUCT_NAME                          project.app
GCC3_VERSION                               3.3
GCC_C_LANGUAGE_STANDARD                    gnu99
GCC_INLINES_ARE_PRIVATE_EXTERN             YES
GCC_PFE_FILE_C_DIALECTS                    "c objective-c c++ objective-c++"
GCC_PRECOMPILE_PREFIX_HEADER               YES
GCC_PREFIX_HEADER                          project/Prefix.pch
GCC_PREPROCESSOR_DEFINITIONS               "NDEBUG DISTRIBUTION_BUILD=1 KK_TARGET=0x000F0"
GCC_SYMBOLS_PRIVATE_EXTERN                 YES
GCC_THUMB_SUPPORT                          YES
GCC_TREAT_WARNINGS_AS_ERRORS               NO
GCC_VERSION                                com.apple.compilers.llvm.clang.1_0
GCC_VERSION_IDENTIFIER                     com_apple_compilers_llvm_clang_1_0
GCC_WARN_ABOUT_RETURN_TYPE                 YES
GCC_WARN_UNUSED_FUNCTION                   YES
GCC_WARN_UNUSED_VARIABLE                   YES
GENERATE_MASTER_OBJECT_FILE                NO
GENERATE_PKGINFO_FILE                      YES
GENERATE_PROFILING_CODE                    NO
GID                                        20
GROUP                                      staff
INPUT_FILE_BASE             Default
INPUT_FILE_DIR              "/Volumes/Development/Project Game/Project-v1/images"
INPUT_FILE_NAME             Default.png
INPUT_FILE_PATH             "/Volumes/Development/Project Game/Project-v1/images/Default.png"
SCRIPT_INPUT_FILE           "/Volumes/Development/Project Game/Project-v1/images/Default.png"
SCRIPT_OUTPUT_FILE_0        "/Users/username/Library/Developer/Xcode/DerivedData/project-dxdgjvgsvvbhowgjqouevhmvgxgf/ArchiveIntermediates/Project Distribution/IntermediateBuildFilesPath/project.build/Distribution-iphoneos/Project.build/DerivedSources/Default.png"

EXCLUDED_RECURSIVE_SEARCH_PATH_SUBDIRECTORIES              "*.nib *.lproj *.framework *.gch (*) CVS .svn .git *.xcodeproj *.xcode *.pbproj *.pbxproj"
HEADERMAP_INCLUDES_FLAT_ENTRIES_FOR_TARGET_BEING_BUILT     YES
HEADERMAP_INCLUDES_FRAMEWORK_ENTRIES_FOR_ALL_PRODUCT_TYPES YES
HEADERMAP_INCLUDES_NONPUBLIC_NONPRIVATE_HEADERS            YES
HEADERMAP_INCLUDES_PROJECT_HEADERS                         YES
HEADER_SEARCH_PATHS                  "\"/Users/username/Library/Developer/Xcode/DerivedData/project-dxdgjvgsvvbhowgjqouevhmvgxgf/ArchiveIntermediates/Project Distribution/BuildProductsPath/Distribution-iphoneos/include\" "
ICONV                                /usr/bin/iconv
INFOPLIST_EXPAND_BUILD_SETTINGS      YES
INFOPLIST_FILE                       project/Resources/Info.plist
INFOPLIST_OUTPUT_FORMAT              binary
INFOPLIST_PATH                       project.app/Info.plist
INFOPLIST_PREPROCESS                 NO
INFOSTRINGS_PATH                     project.app/English.lproj/InfoPlist.strings
INPUT_FILE_REGION_PATH_COMPONENT                    
INPUT_FILE_SUFFIX                    .png
INSTALL_DIR                          "/Users/username/Library/Developer/Xcode/DerivedData/project-dxdgjvgsvvbhowgjqouevhmvgxgf/ArchiveIntermediates/Project Distribution/InstallationBuildProductsLocation/Applications"
INSTALL_GROUP                        staff
INSTALL_MODE_FLAG                    u+w,go-w,a+rX
INSTALL_OWNER                        username
INSTALL_PATH                         /Applications
INSTALL_ROOT                         "/Users/username/Library/Developer/Xcode/DerivedData/project-dxdgjvgsvvbhowgjqouevhmvgxgf/ArchiveIntermediates/Project Distribution/InstallationBuildProductsLocation"
JAVAC_DEFAULT_FLAGS                  "-J-Xms64m -J-XX:NewSize=4M -J-Dfile.encoding=UTF8"
JAVA_APP_STUB                        /System/Library/Frameworks/JavaVM.framework/Resources/MacOS/JavaApplicationStub
JAVA_ARCHIVE_CLASSES                 YES
JAVA_ARCHIVE_TYPE                    JAR
JAVA_COMPILER                        /usr/bin/javac
JAVA_FOLDER_PATH                     project.app/Java
JAVA_FRAMEWORK_RESOURCES_DIRS        Resources
JAVA_JAR_FLAGS                       cv
JAVA_SOURCE_SUBDIR                   .
JAVA_USE_DEPENDENCIES                YES
JAVA_ZIP_FLAGS                       -urg
JIKES_DEFAULT_FLAGS                  "+E +OLDCSO"
KEEP_PRIVATE_EXTERNS                 NO
LD_GENERATE_MAP_FILE                 NO
LD_MAP_FILE_PATH                     "/Users/username/Library/Developer/Xcode/DerivedData/project-dxdgjvgsvvbhowgjqouevhmvgxgf/ArchiveIntermediates/Project Distribution/IntermediateBuildFilesPath/project.build/Distribution-iphoneos/Project.build/project-LinkMap-normal-armv7.txt"
LD_NO_PIE                            NO
LD_OPENMP_FLAGS                      -fopenmp
LEGACY_DEVELOPER_DIR                 /Developer/Library/Xcode/PrivatePlugIns/Xcode3Core.ideplugin/Contents/SharedSupport/Developer
LEX                                  /Developer/usr/bin/lex
LIBRARY_FLAG_NOSPACE                 YES
LIBRARY_FLAG_PREFIX                  -l
LIBRARY_SEARCH_PATHS                 "\"/Users/username/Library/Developer/Xcode/DerivedData/project-dxdgjvgsvvbhowgjqouevhmvgxgf/ArchiveIntermediates/Project Distribution/BuildProductsPath/Distribution-iphoneos\"  \"/Volumes/Development/Project Game/Project-v1/FlurryLib\""
LINKER_DISPLAYS_MANGLED_NAMES        NO
LINK_FILE_LIST_normal_armv6          "/Users/username/Library/Developer/Xcode/DerivedData/project-dxdgjvgsvvbhowgjqouevhmvgxgf/ArchiveIntermediates/Project Distribution/IntermediateBuildFilesPath/project.build/Distribution-iphoneos/Project.build/Objects-normal/armv6/project.LinkFileList"
LINK_FILE_LIST_normal_armv7          "/Users/username/Library/Developer/Xcode/DerivedData/project-dxdgjvgsvvbhowgjqouevhmvgxgf/ArchiveIntermediates/Project Distribution/IntermediateBuildFilesPath/project.build/Distribution-iphoneos/Project.build/Objects-normal/armv7/project.LinkFileList"
LINK_WITH_STANDARD_LIBRARIES         YES
LOCALIZED_RESOURCES_FOLDER_PATH      project.app/English.lproj
LOCAL_ADMIN_APPS_DIR                 /Applications/Utilities
LOCAL_APPS_DIR                       /Applications
LOCAL_DEVELOPER_DIR                  /Library/Developer
LOCAL_LIBRARY_DIR                    /Library
MACH_O_TYPE                          mh_execute
MAC_OS_X_PRODUCT_BUILD_VERSION       11A511
MAC_OS_X_VERSION_ACTUAL              1070
MAC_OS_X_VERSION_MAJOR               1070
MAC_OS_X_VERSION_MINOR               0700
NATIVE_ARCH                          armv6
NATIVE_ARCH_32_BIT                   i386
NATIVE_ARCH_64_BIT                   x86_64
NATIVE_ARCH_ACTUAL                   x86_64
NO_COMMON                            YES
OBJECT_FILE_DIR                      "/Users/username/Library/Developer/Xcode/DerivedData/project-dxdgjvgsvvbhowgjqouevhmvgxgf/ArchiveIntermediates/Project Distribution/IntermediateBuildFilesPath/project.build/Distribution-iphoneos/Project.build/Objects"
OBJECT_FILE_DIR_normal               "/Users/username/Library/Developer/Xcode/DerivedData/project-dxdgjvgsvvbhowgjqouevhmvgxgf/ArchiveIntermediates/Project Distribution/IntermediateBuildFilesPath/project.build/Distribution-iphoneos/Project.build/Objects-normal"
OBJROOT                              "/Users/username/Library/Developer/Xcode/DerivedData/project-dxdgjvgsvvbhowgjqouevhmvgxgf/ArchiveIntermediates/Project Distribution/IntermediateBuildFilesPath"
ONLY_ACTIVE_ARCH                     NO
OPTIMIZATION_LEVEL                   0
OS                                   MACOS
OSAC                                 /usr/bin/osacompile
OTHER_CFLAGS                         -DNS_BLOCK_ASSERTIONS=1
OTHER_CPLUSPLUSFLAGS                 -DNS_BLOCK_ASSERTIONS=1
OTHER_INPUT_FILE_FLAGS                    
OTHER_LDFLAGS                        -lz
PACKAGE_TYPE                         com.apple.package-type.wrapper.application
PASCAL_STRINGS                       YES
PATH_PREFIXES_EXCLUDED_FROM_HEADER_DEPENDENCIES  "/usr/include /usr/local/include /System/Library/Frameworks /System/Library/PrivateFrameworks /Developer/Headers /Developer/SDKs /Developer/Platforms"
PBDEVELOPMENTPLIST_PATH              project.app/pbdevelopment.plist
PFE_FILE_C_DIALECTS                  "c objective-c c++ objective-c++"
PKGINFO_FILE_PATH                    "/Users/username/Library/Developer/Xcode/DerivedData/project-dxdgjvgsvvbhowgjqouevhmvgxgf/ArchiveIntermediates/Project Distribution/IntermediateBuildFilesPath/project.build/Distribution-iphoneos/Project.build/PkgInfo"
PKGINFO_PATH                         project.app/PkgInfo
PLATFORM_DEVELOPER_APPLICATIONS_DIR  /Developer/Platforms/iPhoneOS.platform/Developer/Applications
PLATFORM_DEVELOPER_BIN_DIR           /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin
PLATFORM_DEVELOPER_LIBRARY_DIR       /Developer/Library/Xcode/PrivatePlugIns/Xcode3Core.ideplugin/Contents/SharedSupport/Developer/Library
PLATFORM_DEVELOPER_SDK_DIR           /Developer/Platforms/iPhoneOS.platform/Developer/SDKs
PLATFORM_DEVELOPER_TOOLS_DIR         /Developer/Platforms/iPhoneOS.platform/Developer/Tools
PLATFORM_DEVELOPER_USR_DIR           /Developer/Platforms/iPhoneOS.platform/Developer/usr
PLATFORM_DIR                         /Developer/Platforms/iPhoneOS.platform
PLATFORM_NAME                        iphoneos
PLATFORM_PREFERRED_ARCH              i386
PLATFORM_PRODUCT_BUILD_VERSION       8H7
PLIST_FILE_OUTPUT_FORMAT             binary
PLUGINS_FOLDER_PATH                  project.app/PlugIns
PRECOMPS_INCLUDE_HEADERS_FROM_BUILT_PRODUCTS_DIR                    YES
PRECOMP_DESTINATION_DIR              "/Users/username/Library/Developer/Xcode/DerivedData/project-dxdgjvgsvvbhowgjqouevhmvgxgf/ArchiveIntermediates/Project Distribution/IntermediateBuildFilesPath/project.build/Distribution-iphoneos/Project.build/PrefixHeaders"
PRESERVE_DEAD_CODE_INITS_AND_TERMS   NO
PRIVATE_HEADERS_FOLDER_PATH          project.app/PrivateHeaders
PRODUCT_NAME                         project
PRODUCT_SETTINGS_PATH                "/Volumes/Development/Project Game/Project-v1/project/Resources/Info.plist"
PRODUCT_TYPE                         com.apple.product-type.application
PROFILING_CODE                       NO
PROJECT                              project
PROJECT_DERIVED_FILE_DIR             "/Users/username/Library/Developer/Xcode/DerivedData/project-dxdgjvgsvvbhowgjqouevhmvgxgf/ArchiveIntermediates/Project Distribution/IntermediateBuildFilesPath/project.build/DerivedSources"
PROJECT_DIR                          "/Volumes/Development/Project Game/Project-v1"
PROJECT_FILE_PATH                    "/Volumes/Development/Project Game/Project-v1/project.xcodeproj"
PROJECT_NAME                         project
PROJECT_TEMP_DIR                     "/Users/username/Library/Developer/Xcode/DerivedData/project-dxdgjvgsvvbhowgjqouevhmvgxgf/ArchiveIntermediates/Project Distribution/IntermediateBuildFilesPath/project.build"
PROVISIONING_PROFILE_REQUIRED        YES
PUBLIC_HEADERS_FOLDER_PATH           project.app/Headers
RECURSIVE_SEARCH_PATHS_FOLLOW_SYMLINKS   YES
REMOVE_CVS_FROM_RESOURCES            YES
REMOVE_GIT_FROM_RESOURCES            YES
REMOVE_SVN_FROM_RESOURCES            YES
RESOURCE_RULES_REQUIRED              YES
REZ_COLLECTOR_DIR                    "/Users/username/Library/Developer/Xcode/DerivedData/project-dxdgjvgsvvbhowgjqouevhmvgxgf/ArchiveIntermediates/Project Distribution/IntermediateBuildFilesPath/project.build/Distribution-iphoneos/Project.build/ResourceManagerResources"
REZ_OBJECTS_DIR                      "/Users/username/Library/Developer/Xcode/DerivedData/project-dxdgjvgsvvbhowgjqouevhmvgxgf/ArchiveIntermediates/Project Distribution/IntermediateBuildFilesPath/project.build/Distribution-iphoneos/Project.build/ResourceManagerResources/Objects"
REZ_SEARCH_PATHS                     "\"/Users/username/Library/Developer/Xcode/DerivedData/project-dxdgjvgsvvbhowgjqouevhmvgxgf/ArchiveIntermediates/Project Distribution/BuildProductsPath/Distribution-iphoneos\" "
RUN_CLANG_STATIC_ANALYZER            NO
SCAN_ALL_SOURCE_FILES_FOR_INCLUDES   NO
SCRIPTS_FOLDER_PATH                  project.app/Scripts
SCRIPT_INPUT_FILE                    "/Volumes/Development/Project Game/Project-v1/fonts/helvetica-black-hd.png"
SCRIPT_OUTPUT_FILE_0                 "/Users/username/Library/Developer/Xcode/DerivedData/project-dxdgjvgsvvbhowgjqouevhmvgxgf/ArchiveIntermediates/Project Distribution/IntermediateBuildFilesPath/project.build/Distribution-iphoneos/Project.build/DerivedSources/helvetica-black-hd.png"
SCRIPT_OUTPUT_FILE_COUNT             1
SDKROOT                              /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.3.sdk
SDK_DIR                              /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.3.sdk
SDK_NAME                             iphoneos4.3
SDK_PRODUCT_BUILD_VERSION            8H7
SED                                  /usr/bin/sed
SEPARATE_STRIP                       NO
SEPARATE_SYMBOL_EDIT                 NO
SET_DIR_MODE_OWNER_GROUP            YES
SET_FILE_MODE_OWNER_GROUP           NO
SHALLOW_BUNDLE                      YES
SHARED_DERIVED_FILE_DIR             "/Users/username/Library/Developer/Xcode/DerivedData/project-dxdgjvgsvvbhowgjqouevhmvgxgf/ArchiveIntermediates/Project Distribution/BuildProductsPath/Distribution-iphoneos/DerivedSources"
SHARED_FRAMEWORKS_FOLDER_PATH       project.app/SharedFrameworks
SHARED_PRECOMPS_DIR                 /Users/username/Library/Developer/Xcode/DerivedData/project-dxdgjvgsvvbhowgjqouevhmvgxgf/Build/PrecompiledHeaders
SHARED_SUPPORT_FOLDER_PATH          project.app/SharedSupport
SKIP_INSTALL                        NO
SOURCE_ROOT                         "/Volumes/Development/Project Game/Project-v1"
SRCROOT                             "/Volumes/Development/Project Game/Project-v1"
STRINGS_FILE_OUTPUT_ENCODING        binary
STRIP_INSTALLED_PRODUCT             YES
STRIP_STYLE                         all
SUPPORTED_DEVICE_FAMILIES           1,2
SUPPORTED_PLATFORMS                 "iphonesimulator iphoneos"
SYMROOT                             "/Users/username/Library/Developer/Xcode/DerivedData/project-dxdgjvgsvvbhowgjqouevhmvgxgf/ArchiveIntermediates/Project Distribution/BuildProductsPath"
SYSTEM_ADMIN_APPS_DIR               /Applications/Utilities
SYSTEM_APPS_DIR                     /Applications
SYSTEM_CORE_SERVICES_DIR            /System/Library/CoreServices
SYSTEM_DEMOS_DIR                    /Applications/Extras
SYSTEM_DEVELOPER_APPS_DIR           /Developer/Applications
SYSTEM_DEVELOPER_BIN_DIR            /Developer/usr/bin
SYSTEM_DEVELOPER_DEMOS_DIR          "/Developer/Applications/Utilities/Built Examples"
SYSTEM_DEVELOPER_DIR                /Developer
SYSTEM_DEVELOPER_DOC_DIR            "/Developer/ADC Reference Library"
SYSTEM_DEVELOPER_GRAPHICS_TOOLS_DIR "/Developer/Applications/Graphics Tools"
SYSTEM_DEVELOPER_JAVA_TOOLS_DIR     "/Developer/Applications/Java Tools"
SYSTEM_DEVELOPER_PERFORMANCE_TOOLS_DIR   "/Developer/Applications/Performance Tools"
SYSTEM_DEVELOPER_RELEASENOTES_DIR   "/Developer/ADC Reference Library/releasenotes"
SYSTEM_DEVELOPER_TOOLS              /Developer/Tools
SYSTEM_DEVELOPER_TOOLS_DOC_DIR      "/Developer/ADC Reference Library/documentation/DeveloperTools"
SYSTEM_DEVELOPER_TOOLS_RELEASENOTES_DIR   "/Developer/ADC Reference Library/releasenotes/DeveloperTools"
SYSTEM_DEVELOPER_USR_DIR            /Developer/usr
SYSTEM_DEVELOPER_UTILITIES_DIR      /Developer/Applications/Utilities
SYSTEM_DOCUMENTATION_DIR            /Library/Documentation
SYSTEM_LIBRARY_DIR                  /System/Library
TARGETED_DEVICE_FAMILY              1
TARGETNAME                          Project
TARGET_BUILD_DIR                    "/Users/username/Library/Developer/Xcode/DerivedData/project-dxdgjvgsvvbhowgjqouevhmvgxgf/ArchiveIntermediates/Project Distribution/InstallationBuildProductsLocation/Applications"
TARGET_NAME                         Project
TARGET_TEMP_DIR                     "/Users/username/Library/Developer/Xcode/DerivedData/project-dxdgjvgsvvbhowgjqouevhmvgxgf/ArchiveIntermediates/Project Distribution/IntermediateBuildFilesPath/project.build/Distribution-iphoneos/Project.build"
TEMP_DIR                            "/Users/username/Library/Developer/Xcode/DerivedData/project-dxdgjvgsvvbhowgjqouevhmvgxgf/ArchiveIntermediates/Project Distribution/IntermediateBuildFilesPath/project.build/Distribution-iphoneos/Project.build"
TEMP_FILES_DIR                      "/Users/username/Library/Developer/Xcode/DerivedData/project-dxdgjvgsvvbhowgjqouevhmvgxgf/ArchiveIntermediates/Project Distribution/IntermediateBuildFilesPath/project.build/Distribution-iphoneos/Project.build"
TEMP_FILE_DIR                       "/Users/username/Library/Developer/Xcode/DerivedData/project-dxdgjvgsvvbhowgjqouevhmvgxgf/ArchiveIntermediates/Project Distribution/IntermediateBuildFilesPath/project.build/Distribution-iphoneos/Project.build"
TEMP_ROOT                           "/Users/username/Library/Developer/Xcode/DerivedData/project-dxdgjvgsvvbhowgjqouevhmvgxgf/ArchiveIntermediates/Project Distribution/IntermediateBuildFilesPath"
TEST_AFTER_BUILD                    NO
UID                                 501
UNLOCALIZED_RESOURCES_FOLDER_PATH   project.app    UNSTRIPPED_PRODUCT           NO
USER                         username
USER_APPS_DIR                /Users/username/Applications
USER_HEADER_SEARCH_PATHS     project/libs
USER_LIBRARY_DIR             /Users/username/Library
USE_DYNAMIC_NO_PIC           YES
USE_HEADERMAP                YES
USE_HEADER_SYMLINKS          NO
VALIDATE_PRODUCT             YES
VALID_ARCHS                  "armv6 armv7"
VERBOSE_PBXCP                NO
VERSIONPLIST_PATH            project.app/version.plist
VERSION_INFO_BUILDER         username
VERSION_INFO_FILE            project_vers.c
VERSION_INFO_STRING          "\"@(#)PROGRAM:project  PROJECT:project-\""
WRAPPER_EXTENSION            app
WRAPPER_NAME                 project.app
WRAPPER_SUFFIX               .app
XCODE_APP_SUPPORT_DIR        /Developer/Library/Xcode
XCODE_PRODUCT_BUILD_VERSION  4B110
XCODE_VERSION_ACTUAL         0410
XCODE_VERSION_MAJOR          0400
XCODE_VERSION_MINOR          0410
YACC                        /Developer/usr/bin/yacc

Entity Framework - Generating Classes

EDMX model won't work with EF7 but I've found a Community/Professional product which seems to be very powerfull : http://www.devart.com/entitydeveloper/editions.html

Accessing items in an collections.OrderedDict by index

This community wiki attempts to collect existing answers.

Python 2.7

In python 2, the keys(), values(), and items() functions of OrderedDict return lists. Using values as an example, the simplest way is

d.values()[0]  # "python"
d.values()[1]  # "spam"

For large collections where you only care about a single index, you can avoid creating the full list using the generator versions, iterkeys, itervalues and iteritems:

import itertools
next(itertools.islice(d.itervalues(), 0, 1))  # "python"
next(itertools.islice(d.itervalues(), 1, 2))  # "spam"

The indexed.py package provides IndexedOrderedDict, which is designed for this use case and will be the fastest option.

from indexed import IndexedOrderedDict
d = IndexedOrderedDict({'foo':'python','bar':'spam'})
d.values()[0]  # "python"
d.values()[1]  # "spam"

Using itervalues can be considerably faster for large dictionaries with random access:

$ python2 -m timeit -s 'from collections import OrderedDict; from random import randint; size = 1000;   d = OrderedDict({i:i for i in range(size)})'  'i = randint(0, size-1); d.values()[i:i+1]'
1000 loops, best of 3: 259 usec per loop
$ python2 -m timeit -s 'from collections import OrderedDict; from random import randint; size = 10000;  d = OrderedDict({i:i for i in range(size)})' 'i = randint(0, size-1); d.values()[i:i+1]'
100 loops, best of 3: 2.3 msec per loop
$ python2 -m timeit -s 'from collections import OrderedDict; from random import randint; size = 100000; d = OrderedDict({i:i for i in range(size)})' 'i = randint(0, size-1); d.values()[i:i+1]'
10 loops, best of 3: 24.5 msec per loop

$ python2 -m timeit -s 'from collections import OrderedDict; from random import randint; size = 1000;   d = OrderedDict({i:i for i in range(size)})' 'i = randint(0, size-1); next(itertools.islice(d.itervalues(), i, i+1))'
10000 loops, best of 3: 118 usec per loop
$ python2 -m timeit -s 'from collections import OrderedDict; from random import randint; size = 10000;  d = OrderedDict({i:i for i in range(size)})' 'i = randint(0, size-1); next(itertools.islice(d.itervalues(), i, i+1))'
1000 loops, best of 3: 1.26 msec per loop
$ python2 -m timeit -s 'from collections import OrderedDict; from random import randint; size = 100000; d = OrderedDict({i:i for i in range(size)})' 'i = randint(0, size-1); next(itertools.islice(d.itervalues(), i, i+1))'
100 loops, best of 3: 10.9 msec per loop

$ python2 -m timeit -s 'from indexed import IndexedOrderedDict; from random import randint; size = 1000;   d = IndexedOrderedDict({i:i for i in range(size)})' 'i = randint(0, size-1); d.values()[i]'
100000 loops, best of 3: 2.19 usec per loop
$ python2 -m timeit -s 'from indexed import IndexedOrderedDict; from random import randint; size = 10000;  d = IndexedOrderedDict({i:i for i in range(size)})' 'i = randint(0, size-1); d.values()[i]'
100000 loops, best of 3: 2.24 usec per loop
$ python2 -m timeit -s 'from indexed import IndexedOrderedDict; from random import randint; size = 100000; d = IndexedOrderedDict({i:i for i in range(size)})' 'i = randint(0, size-1); d.values()[i]'
100000 loops, best of 3: 2.61 usec per loop

+--------+-----------+----------------+---------+
|  size  | list (ms) | generator (ms) | indexed |
+--------+-----------+----------------+---------+
|   1000 | .259      | .118           | .00219  |
|  10000 | 2.3       | 1.26           | .00224  |
| 100000 | 24.5      | 10.9           | .00261  |
+--------+-----------+----------------+---------+

Python 3.6

Python 3 has the same two basic options (list vs generator), but the dict methods return generators by default.

List method:

list(d.values())[0]  # "python"
list(d.values())[1]  # "spam"

Generator method:

import itertools
next(itertools.islice(d.values(), 0, 1))  # "python"
next(itertools.islice(d.values(), 1, 2))  # "spam"

Python 3 dictionaries are an order of magnitude faster than python 2 and have similar speedups for using generators.

+--------+-----------+----------------+---------+
|  size  | list (ms) | generator (ms) | indexed |
+--------+-----------+----------------+---------+
|   1000 | .0316     | .0165          | .00262  |
|  10000 | .288      | .166           | .00294  |
| 100000 | 3.53      | 1.48           | .00332  |
+--------+-----------+----------------+---------+

Can I obtain method parameter name using Java reflection?

To summarize:

  • getting parameter names is possible if debug information is included during compilation. See this answer for more details
  • otherwise getting parameter names is not possible
  • getting parameter type is possible, using method.getParameterTypes()

For the sake of writing autocomplete functionality for an editor (as you stated in one of the comments) there are a few options:

  • use arg0, arg1, arg2 etc.
  • use intParam, stringParam, objectTypeParam, etc.
  • use a combination of the above - the former for non-primitive types, and the latter for primitive types.
  • don't show argument names at all - just the types.

How to navigate through a vector using iterators? (C++)

You need to make use of the begin and end method of the vector class, which return the iterator referring to the first and the last element respectively.

using namespace std;  

vector<string> myvector;  // a vector of stings.


// push some strings in the vector.
myvector.push_back("a");
myvector.push_back("b");
myvector.push_back("c");
myvector.push_back("d");


vector<string>::iterator it;  // declare an iterator to a vector of strings
int n = 3;  // nth element to be found.
int i = 0;  // counter.

// now start at from the beginning
// and keep iterating over the element till you find
// nth element...or reach the end of vector.
for(it = myvector.begin(); it != myvector.end(); it++,i++ )    {
    // found nth element..print and break.
    if(i == n) {
        cout<< *it << endl;  // prints d.
        break;
    }
}

// other easier ways of doing the same.
// using operator[]
cout<<myvector[n]<<endl;  // prints d.

// using the at method
cout << myvector.at(n) << endl;  // prints d.

Are there any Java method ordering conventions?

Some conventions list all the public methods first, and then all the private ones - that means it's easy to separate the API from the implementation, even when there's no interface involved, if you see what I mean.

Another idea is to group related methods together - this makes it easier to spot seams where you could split your existing large class into several smaller, more targeted ones.

How do I restrict an input to only accept numbers?

DECIMAL

directive('decimal', function() {
                return {
                    require: 'ngModel',
                    restrict: 'A',
                    link: function(scope, element, attr, ctrl) {
                        function inputValue(val) {
                            if (val) {
                                var digits = val.replace(/[^0-9.]/g, '');

                                if (digits.split('.').length > 2) {
                                    digits = digits.substring(0, digits.length - 1);
                                }

                                if (digits !== val) {
                                    ctrl.$setViewValue(digits);
                                    ctrl.$render();
                                }
                                return parseFloat(digits);
                            }
                            return "";
                        }
                        ctrl.$parsers.push(inputValue);
                    }
                };
            });

DIGITS

directive('entero', function() {
            return {
                require: 'ngModel',
                restrict: 'A',
                link: function(scope, element, attr, ctrl) {
                    function inputValue(val) {
                        if (val) {
                            var value = val + ''; //convert to string
                            var digits = value.replace(/[^0-9]/g, '');

                            if (digits !== value) {
                                ctrl.$setViewValue(digits);
                                ctrl.$render();
                            }
                            return parseInt(digits);
                        }
                        return "";
                    }
                    ctrl.$parsers.push(inputValue);
                }
            };
        });

angular directives for validate numbers

fatal: The current branch master has no upstream branch

I had the same problem

enter image description here

I resolved it that used below command

$ git branch --set-upstream develop origin/develop

and it will add a config in the config file in the .git folder.

enter image description here

How to revert a merge commit that's already pushed to remote branch?

I found creating a reverse patch between two know end-points and applying that patch would work. This presumes that you have created snapshots (tags) off of your master branch or even a back up of your master branch say master_bk_01012017.

Say the code branch you merged into master was mycodebranch.

  1. Checkout master.
  2. Create a full binary reverse patch between master and your backup. git diff --binary master..master_bk_01012017 > ~/myrevert.patch
  3. Check your patch git apply --check myrevert.patch
  4. Apply patch with sign-off git am --signoff < myrevert.patch
  5. If you will need to bring in this code again once it is fixed, you will need to branch off the reverted master and checkout the fix branch git branch mycodebranch_fix git checkout mycodebranch_fix
  6. Here you need to find the SHA key for the revert and revert the revert git revert [SHA]
  7. Now you can use your mycodebranch_fix to fix the issues, commit and re-merge into master once done.

Using sudo with Python script

Please try module pexpect. Here is my code:

import pexpect
remove = pexpect.spawn('sudo dpkg --purge mytool.deb')
remove.logfile = open('log/expect-uninstall-deb.log', 'w')
remove.logfile.write('try to dpkg --purge mytool\n')
if remove.expect(['(?i)password.*']) == 0:
    # print "successfull"
    remove.sendline('mypassword')
    time.sleep(2)
    remove.expect(pexpect.EOF,5)
else:
    raise AssertionError("Fail to Uninstall deb package !")

Drop all the tables, stored procedures, triggers, constraints and all the dependencies in one sql statement

Another alternative if you are developing, would be:

DROP SCHEMA public CASCADE;
CREATE SCHEMA public;

How to get the name of the current method from code

Does this not work?

System.Reflection.MethodBase.GetCurrentMethod()

Returns a MethodBase object representing the currently executing method.

Namespace: System.Reflection

Assembly: mscorlib (in mscorlib.dll)

http://msdn.microsoft.com/en-us/library/system.reflection.methodbase.getcurrentmethod.aspx

How to set Angular 4 background image?

Below answer worked for angular 4/5.

In app.component.css

.image{
     height:40em; background-size:cover; width:auto;
     background-image:url('copied image address');
     background-position:50% 50%;
   }

Also in app.component.html simply add as below

<div class="image">
Your content
</div>

This way I was able to set background image in Angular 4/5.

A div with auto resize when changing window width\height

  <!DOCTYPE html>
    <html>
  <head>
  <style> 
   div {

   padding: 20px; 

   resize: both;
  overflow: auto;
   }
    img{
   height: 100%;
    width: 100%;
 object-fit: contain;
 }
 </style>
  </head>
  <body>
 <h1>The resize Property</h1>

 <div>
 <p>Let the user resize both the height and the width of this 1234567891011 div 
   element. 
  </p>
 <p>To resize: Click and drag the bottom right corner of this div element.</p>
  <img src="images/scenery.jpg" alt="Italian ">
  </div>

   <p><b>Note:</b> Internet Explorer does not support the resize property.</p>

 </body>
 </html>

How to get a Docker container's IP address from the host

docker inspect <container id> | grep -i "ipaddress"

How return error message in spring mvc @Controller

return new ResponseEntity<>(GenericResponseBean.newGenericError("Error during the calling the service", -1L), HttpStatus.EXPECTATION_FAILED);

How to write MySQL query where A contains ( "a" or "b" )

I user for searching the size of motorcycle :

For example : Data = "Tire cycle size 70 / 90 - 16"

i can search with "70 90 16"

$searchTerms = preg_split("/[\s,-\/?!]+/", $itemName);

foreach ($searchTerms as $term) {
        $term = trim($term);
            if (!empty($term)) {
            $searchTermBits[] = "name LIKE '%$term%'";
            }
        }

$query = "SELECT * FROM item WHERE " .implode(' AND ', $searchTermBits);

How to maximize a plt.show() window using Python

I usually use

mng = plt.get_current_fig_manager()
mng.frame.Maximize(True)

before the call to plt.show(), and I get a maximized window. This works for the 'wx' backend only.

EDIT:

for Qt4Agg backend, see kwerenda's answer.

Removing "http://" from a string

Try this out:

$url = 'http://techcrunch.com/startups/'; $url = str_replace(array('http://', 'https://'), '', $url); 

EDIT:

Or, a simple way to always remove the protocol:

$url = 'https://www.google.com/'; $url = preg_replace('@^.+?\:\/\/@', '', $url); 

How to type in textbox using Selenium WebDriver (Selenium 2) with Java?

Another way to solve this using xpath

WebDriver driver =  new FirefoxDriver();
driver.get("https://www.facebook.com/");
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.findElement(By.xpath(//*[@id='email'])).sendKeys("[email protected]");

Hope that will help. :)

Convert a date format in PHP

Given below is PHP code to generate tomorrow's date using mktime() and change its format to dd/mm/yyyy format and then print it using echo.

$tomorrow = mktime(0, 0, 0, date("m"), date("d") + 1, date("Y"));
echo date("d", $tomorrow) . "/" . date("m", $tomorrow). "/" . date("Y", $tomorrow);

Java: Best way to iterate through a Collection (here ArrayList)

There is additionally collections’ stream() util with Java 8

collection.forEach((temp) -> {
            System.out.println(temp);
});

or

collection.forEach(System.out::println);

More information about Java 8 stream and collections for wonderers link

How to add row of data to Jtable from values received from jtextfield and comboboxes

String[] tblHead={"Item Name","Price","Qty","Discount"};
DefaultTableModel dtm=new DefaultTableModel(tblHead,0);
JTable tbl=new JTable(dtm);
String[] item={"A","B","C","D"};
dtm.addRow(item);

Here;this is the solution.

Why does MSBuild look in C:\ for Microsoft.Cpp.Default.props instead of c:\Program Files (x86)\MSBuild? ( error MSB4019)

Installing Microsoft Visual C++ 2010 Service Pack 1 Compiler Update for the Windows SDK 7.1 fixed the MSB4019 errors that I was getting building on Windows7 x64.

The readme of that update states that the recommended order is

  1. Visual Studio 2010
  2. Windows SDK 7.1
  3. Visual Studio 2010 SP1
  4. Visual C++ 2010 SP1 Compiler Update for the Windows SDK 7.1

Modulo operation with negative numbers

Based on the C99 Specification: a == (a / b) * b + a % b

We can write a function to calculate (a % b) == a - (a / b) * b!

int remainder(int a, int b)
{
    return a - (a / b) * b;
}

For modulo operation, we can have the following function (assuming b > 0)

int mod(int a, int b)
{
    int r = a % b;
    return r < 0 ? r + b : r;
}

My conclusion is that a % b in C is a remainder operation and NOT a modulo operation.

Insert data into hive table

If table is without partition then code will be,

Insert into table table_name select col_a,col_b,col_c from another_table(source table)

--here any condition can be applied such as limit, group by, order by etc...

If table is with partitions then code will be,

set hive.exec.dynamic.partition=true;
set hive.exec.dynamic.partition.mode=nonstrict;

insert into table table_name partition(partition_col1, paritition_col2) select col_a,col_b,col_c,partition_col1,partition_col2 from another_table(source table)

--here any condition can be applied such as limit, group by, order by etc...

Angularjs loading screen on ajax request

using pendingRequests is not correct because as mentioned in Angular documentation, this property is primarily meant to be used for debugging purposes.

What I recommend is to use an interceptor to know if there is any active Async call.

module.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.interceptors.push(function ($q, $rootScope) {
        if ($rootScope.activeCalls == undefined) {
            $rootScope.activeCalls = 0;
        }

        return {
            request: function (config) {
                $rootScope.activeCalls += 1;
                return config;
            },
            requestError: function (rejection) {
                $rootScope.activeCalls -= 1;
                return rejection;
            },
            response: function (response) {
                $rootScope.activeCalls -= 1;
                return response;
            },
            responseError: function (rejection) {
                $rootScope.activeCalls -= 1;
                return rejection;
            }
        };
    });
}]);

and then check whether activeCalls is zero or not in the directive through a $watch.

module.directive('loadingSpinner', function ($http) {
    return {
        restrict: 'A',
        replace: true,
        template: '<div class="loader unixloader" data-initialize="loader" data-delay="500"></div>',
        link: function (scope, element, attrs) {

            scope.$watch('activeCalls', function (newVal, oldVal) {
                if (newVal == 0) {
                    $(element).hide();
                }
                else {
                    $(element).show();
                }
            });
        }
    };
});

How to make a edittext box in a dialog

Wasim's answer lead me in the right direction but I had to make some changes to get it working for my current project. I am using this function in a fragment and calling it on button click.

fun showPostDialog(title: String) {
        val alert =  AlertDialog.Builder(activity)

        val edittext = EditText(activity)
        edittext.hint = "Enter Name"
        edittext.maxLines = 1

        var layout = activity?.let { FrameLayout(it) }

        //set padding in parent layout
//        layout.isPaddingRelative(45,15,45,0)
        layout?.setPadding(45,15,45,0)

        alert.setTitle(title)

        layout?.addView(edittext)

        alert.setView(layout)

        alert.setPositiveButton(getString(R.string.label_save), DialogInterface.OnClickListener {

                dialog, which ->
            run {

                val qName = edittext.text.toString()

                showToast("Posted to leaderboard successfully")

                view?.hideKeyboard()

            }

        })
        alert.setNegativeButton(getString(R.string.label_cancel), DialogInterface.OnClickListener {

                dialog, which ->
            run {
                dialog.dismiss()
            }

        })

        alert.show()
    }

    fun View.hideKeyboard() {
        val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(windowToken, 0)
    }

    fun showToast(message: String) {
        Toast.makeText(activity, message, Toast.LENGTH_LONG).show()
    }

I hope it helps someone else in the near future. Happy coding!

Export to csv/excel from kibana

To export data to csv/excel from Kibana follow the following steps:-

  1. Click on Visualize Tab & select a visualization (if created). If not created create a visualziation.

  2. Click on caret symbol (^) which is present at the bottom of the visualization.

  3. Then you will get an option of Export:Raw Formatted as the bottom of the page.

Please find below attached image showing Export option after clicking on caret symbol.

Please find below attached image showing Export option after clicking on caret symbol.

AttributeError: Module Pip has no attribute 'main'

It works well:

 py -m pip install --user --upgrade pip==9.0.3

How to put labels over geom_bar in R with ggplot2

Another solution is to use stat_count() when dealing with discrete variables (and stat_bin() with continuous ones).

ggplot(data = df, aes(x = x)) +
geom_bar(stat = "count") + 
stat_count(geom = "text", colour = "white", size = 3.5,
aes(label = ..count..),position=position_stack(vjust=0.5))

enter image description here

How can I convert an image into a Base64 string?

Below is the pseudocode that may help you:

public  String getBase64FromFile(String path)
{
    Bitmap bmp = null;
    ByteArrayOutputStream baos = null;
    byte[] baat = null;
    String encodeString = null;
    try
    {
        bmp = BitmapFactory.decodeFile(path);
        baos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        baat = baos.toByteArray();
        encodeString = Base64.encodeToString(baat, Base64.DEFAULT);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

   return encodeString;
}

What is the difference between Sublime text and Github's Atom

  1. How is Atom different from Sublime?
    • Atom is an open source text editor/IDE, built on JavaScript/HTML/CSS.
    • Sublime Text is a commercial product, built on C/C++ and Python.
    • Comparable to Atom is Adobe Brackets, another open source text editor/IDE built on JavaScript/HTML/CSS. Be minded that this makes Brackets more oriented towards Web development, specially in the front end.
    • Advantages of open source projects are faster rate of development and, of course, price.
  2. Does it include IDE features like build tools, function definition jumps, documentations, etc.?
    • The short answer is yes, yes, and yes. The app is completely modular. Open source will give people the freedom to fill the gaps on several of these features.
  3. Has anyone using Sublime got a Beta invitation to point out the differences?
    • Advantages of Atom is entry-level hackability, since it's built on the same code that powers Web sites.
    • Advantages of Sublime Text is performance, as it doesn't need to run on top of Node.js, and it's a more mature product, about to reach a stable version 3.
    • There are a long list of minor differences that can be included in the comments (I wish this markdown could be able to draw a table for comparisons, but that's another issue).
    • Because of Atom's rapid turnout, I am afraid some of differences I list here will become outdated over time. Per example, at the time of this writing, Atom is only available on the Macintosh while Sublime Text is already multiplatform.
  4. Can I use the themes, schemes and packages from Sublime as is, like Sublime could do with text mate.
    • The short answer is no, but because of Atom's hackability, it will be easy to retool packages from other editors to Atom.

Is there a kind of Firebug or JavaScript console debug for Android?

I have recently written a tool for showing console logs in a movable/resizable "window" (actually a div). It provides similar functionality to Firebug's console but you can see it over your page on a tablet. Tablet/Smartphone/Phablet Debug Console

Where can I find the Java SDK in Linux after installing it?

$ which java 

should give you something like

/usr/bin/java

What is the difference between a stored procedure and a view?

Mahesh is not quite correct when he suggests that you can't alter the data in a view. So with patrick's view

CREATE View vw_user_profile AS 
Select A.user_id, B.profile_description
FROM tbl_user A left join tbl_profile B on A.user_id = b.user_id

I CAN update the data ... as an example I can do either of these ...

Update vw_user_profile Set profile_description='Manager' where user_id=4

or

Update tbl_profile Set profile_description='Manager' where user_id=4

You can't INSERT to this view as not all of the fields in all of the table are present and I'm assuming that PROFILE_ID is the primary key and can't be NULL. However you can sometimes INSERT into a view ...

I created a view on an existing table using ...

Create View Junk as SELECT * from [TableName]

THEN

Insert into junk (Code,name) values 
('glyn','Glyn Roberts'),
('Mary','Maryann Roberts')

and

DELETE from Junk Where ID>4

Both the INSERT and the DELETE worked in this case

Obviously you can't update any fields which are aggregated or calculated but any view which is just a straight view should be updateable.

If the view contains more than one table then you can't insert or delete but if the view is a subset of one table only then you usually can.

How to clear cache of Eclipse Indigo

Instructions

  1. Open Eclipse and navigate to the Window > Preferences.
  2. Scroll down the left-hand panel in the Preferences window and click the Remote Systems drop-down root menu. Select File Cache.
  3. Click the Clear Cached Files button in the File Cache window. Note that this will automatically close any open remote files on your computer.
  4. Press Apply and OK to save your changes and exit out of the Preferences window.

Java 8 stream map to list of keys sorted by values

You say you want to sort by value, but you don't have that in your code. Pass a lambda (or method reference) to sorted to tell it how you want to sort.

And you want to get the keys; use map to transform entries to keys.

List<Type> types = countByType.entrySet().stream()
        .sorted(Comparator.comparing(Map.Entry::getValue))
        .map(Map.Entry::getKey)
        .collect(Collectors.toList());

Could not load file or assembly ... An attempt was made to load a program with an incorrect format (System.BadImageFormatException)

Shoot! I knew about this problem. I thought I was doing everything right until I accidentally saw 'x86' in the VS output window and that's when I got hold of the cause. Wasted a few mins on it today.

The configuration under 'Publish' window was set to 'x86'; whereas, everywhere else, it was 'x64'.

Please make sure it's in-sync across configuration manager, publish settings, solution configurations, and IIS settings (if that's your web server).

Also, please keep in mind - VS is a 32-bit app and IIS is 64 bit. 32-bit apps are disabled by default in IIS.

enter image description here

fork and exec in bash

Use the ampersand just like you would from the shell.

#!/usr/bin/bash
function_to_fork() {
   ...
}

function_to_fork &
# ... execution continues in parent process ...

Add Favicon to Website

  1. This is not done in PHP. It's part of the <head> tags in a HTML page.
  2. That icon is called a favicon. According to Wikipedia:

    A favicon (short for favorites icon), also known as a shortcut icon, website icon, URL icon, or bookmark icon is a 16×16 or 32×32 pixel square icon associated with a particular website or webpage.

  3. Adding it is easy. Just add an .ico image file that is either 16x16 pixels or 32x32 pixels. Then, in the web pages, add <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"> to the <head> element.
  4. You can easily generate favicons here.

what's the differences between r and rb in fopen

On most POSIX systems, it is ignored. But, check your system to be sure.

XNU

The mode string can also include the letter 'b' either as last character or as a character between the characters in any of the two-character strings described above. This is strictly for compatibility with ISO/IEC 9899:1990 ('ISO C90') and has no effect; the 'b' is ignored.

Linux

The mode string can also include the letter 'b' either as a last character or as a character between the characters in any of the two- character strings described above. This is strictly for compatibility with C89 and has no effect; the 'b' is ignored on all POSIX conforming systems, including Linux. (Other systems may treat text files and binary files differently, and adding the 'b' may be a good idea if you do I/O to a binary file and expect that your program may be ported to non-UNIX environments.)

How to execute an Oracle stored procedure via a database link

for me, this worked

exec utl_mail.send@myotherdb(
  sender => '[email protected]',recipients => '[email protected], 
  cc => null, subject => 'my subject', message => 'my message'
); 

What does %>% function mean in R?

%...% operators

%>% has no builtin meaning but the user (or a package) is free to define operators of the form %whatever% in any way they like. For example, this function will return a string consisting of its left argument followed by a comma and space and then it's right argument.

"%,%" <- function(x, y) paste0(x, ", ", y)

# test run

"Hello" %,% "World"
## [1] "Hello, World"

The base of R provides %*% (matrix mulitiplication), %/% (integer division), %in% (is lhs a component of the rhs?), %o% (outer product) and %x% (kronecker product). It is not clear whether %% falls in this category or not but it represents modulo.

expm The R package, expm, defines a matrix power operator %^%. For an example see Matrix power in R .

operators The operators R package has defined a large number of such operators such as %!in% (for not %in%). See http://cran.r-project.org/web/packages/operators/operators.pdf

igraph This package defines %--% , %->% and %<-% to select edges.

lubridate This package defines %m+% and %m-% to add and subtract months and %--% to define an interval. igraph also defines %--% .

Pipes

magrittr In the case of %>% the magrittr R package has defined it as discussed in the magrittr vignette. See http://cran.r-project.org/web/packages/magrittr/vignettes/magrittr.html

magittr has also defined a number of other such operators too. See the Additional Pipe Operators section of the prior link which discusses %T>%, %<>% and %$% and http://cran.r-project.org/web/packages/magrittr/magrittr.pdf for even more details.

dplyr The dplyr R package used to define a %.% operator which is similar; however, it has been deprecated and dplyr now recommends that users use %>% which dplyr imports from magrittr and makes available to the dplyr user. As David Arenburg has mentioned in the comments this SO question discusses the differences between it and magrittr's %>% : Differences between %.% (dplyr) and %>% (magrittr)

pipeR The R package, pipeR, defines a %>>% operator that is similar to magrittr's %>% and can be used as an alternative to it. See http://renkun.me/pipeR-tutorial/

The pipeR package also has defined a number of other such operators too. See: http://cran.r-project.org/web/packages/pipeR/pipeR.pdf

postlogic The postlogic package defined %if% and %unless% operators.

wrapr The R package, wrapr, defines a dot pipe %.>% that is an explicit version of %>% in that it does not do implicit insertion of arguments but only substitutes explicit uses of dot on the right hand side. This can be considered as another alternative to %>%. See https://winvector.github.io/wrapr/articles/dot_pipe.html

Bizarro pipe. This is not really a pipe but rather some clever base syntax to work in a way similar to pipes without actually using pipes. It is discussed in http://www.win-vector.com/blog/2017/01/using-the-bizarro-pipe-to-debug-magrittr-pipelines-in-r/ The idea is that instead of writing:

1:8 %>% sum %>% sqrt
## [1] 6

one writes the following. In this case we explicitly use dot rather than eliding the dot argument and end each component of the pipeline with an assignment to the variable whose name is dot (.) . We follow that with a semicolon.

1:8 ->.; sum(.) ->.; sqrt(.)
## [1] 6

Update Added info on expm package and simplified example at top. Added postlogic package.

Can I load a .NET assembly at runtime and instantiate a type knowing only the name?

Depending how intrinsic this kind of functionality is to your project, you might want to consider something like MEF which will take care of the loading and tying together of components for you.

split string in two on given index and return both parts

function splitText(value, index) {
  if (value.length < index) {return value;} 
  return [value.substring(0, index)].concat(splitText(value.substring(index), index));
}
console.log(splitText('this is a testing peace of text',10));
// ["this is a ", "testing pe", "ace of tex", "t"] 

For those who want to split a text into array using the index.

psql - save results of command to a file

\copy which is a postgres command can work for any user. Don't know if it works for \dt or not, but general syntax is reproduced from the following link Postgres SQL copy syntax

\copy (select * from tempTable limit 100) to 'filenameinquotes' with header delimiter as ','

The above will save the output of the select query in the filename provided as a csv file

EDIT:

For my psql server the following command works this is an older version v8.5

copy (select * from table1) to 'full_path_filename' csv header;

unexpected T_VARIABLE, expecting T_FUNCTION

You can not put

$connection = sqlite_open("[path]/data/users.sqlite", 0666);

outside the class construction. You have to put that line inside a function or the constructor but you can not place it where you have now.

PHP executable not found. Install PHP 7 and add it to your PATH or set the php.executablePath setting

After adding php directory in User Settings,

{
    "php.validate.executablePath": "C:/phpdirectory/php7.1.8/php.exe",
    "php.executablePath": "C:/phpdirectory/php7.1.8/php.exe"
}

If you still have this error, please verify you have installed :

To test if you PHP exe is ok, open cmd.exe :

c:/prog/php-7.1.8-Win32-VC14-x64/php.exe --version

If PHP fails, a message will be prompted with the error (missing dll for example).

Trouble setting up git with my GitHub Account error: could not lock config file

I rename the .gitconfig file as xyz.gitconfig, then git will generate a new .gitconfig file, that wokrd

Webdriver findElements By xpath

Instead of

css=#container

use

css=div.container:nth-of-type(1),css=div.container:nth-of-type(2)

Parse Json string in C#

Instead of an arraylist or dictionary you can also use a dynamic. Most of the time I use EasyHttp for this, but sure there will by other projects that do the same. An example below:

var http = new HttpClient();
http.Request.Accept = HttpContentTypes.ApplicationJson;
var response = http.Get("url");
var body = response.DynamicBody;
Console.WriteLine("Name {0}", body.AppName.Description);
Console.WriteLine("Name {0}", body.AppName.Value);

On NuGet: EasyHttp

Finding longest string in array

var arr = [ 'fdgdfgdfg', 'gdfgf', 'gdfgdfhawsdgd', 'gdf', 'gdfhdfhjurvweadsd' ];
arr.sort(function (a, b) { return b.length - a.length })[0];

Regular expression to match numbers with or without commas and decimals in text

\d+(,\d+)*(\.\d+)?

This assumes that there is always at least one digit before or after any comma or decimal and also assumes that there is at most one decimal and that all the commas precede the decimal.

How do I get an Excel range using row and column numbers in VSTO / C#?

The given answer will throw an error if used in Microsoft Excel 14.0 Object Library. Object does not contain a definition for get_range. Instead use

int countRows = xlWorkSheetData.UsedRange.Rows.Count;
int countColumns = xlWorkSheetData.UsedRange.Columns.Count;
object[,] data = xlWorkSheetData.Range[xlWorkSheetData.Cells[1, 1], xlWorkSheetData.Cells[countRows, countColumns]].Cells.Value2;

How can I write a heredoc to a file in Bash script?

Instead of using cat and I/O redirection it might be useful to use tee instead:

tee newfile <<EOF
line 1
line 2
line 3
EOF

It's more concise, plus unlike the redirect operator it can be combined with sudo if you need to write to files with root permissions.

How to use awk sort by column 3

  1. Use awk to put the user ID in front.
  2. Sort
  3. Use sed to remove the duplicate user ID, assuming user IDs do not contain any spaces.

    awk -F, '{ print $3, $0 }' user.csv | sort | sed 's/^.* //'
    

What is the default encoding of the JVM?

To get default java settings just use :

java -XshowSettings 

How to set calculation mode to manual when opening an excel file?

The best way around this would be to create an Excel called 'launcher.xlsm' in the same folder as the file you wish to open. In the 'launcher' file put the following code in the 'Workbook' object, but set the constant TargetWBName to be the name of the file you wish to open.

Private Const TargetWBName As String = "myworkbook.xlsx"

'// First, a function to tell us if the workbook is already open...
Function WorkbookOpen(WorkBookName As String) As Boolean
' returns TRUE if the workbook is open
    WorkbookOpen = False
    On Error GoTo WorkBookNotOpen
    If Len(Application.Workbooks(WorkBookName).Name) > 0 Then
        WorkbookOpen = True
        Exit Function
    End If
WorkBookNotOpen:
End Function

Private Sub Workbook_Open()
    'Check if our target workbook is open
    If WorkbookOpen(TargetWBName) = False Then
        'set calculation to manual
        Application.Calculation = xlCalculationManual
        Workbooks.Open ThisWorkbook.Path & "\" & TargetWBName
        DoEvents
        Me.Close False
    End If
End Sub

Set the constant 'TargetWBName' to be the name of the workbook that you wish to open. This code will simply switch calculation to manual, then open the file. The launcher file will then automatically close itself. *NOTE: If you do not wish to be prompted to 'Enable Content' every time you open this file (depending on your security settings) you should temporarily remove the 'me.close' to prevent it from closing itself, save the file and set it to be trusted, and then re-enable the 'me.close' call before saving again. Alternatively, you could just set the False to True after Me.Close

How to calculate modulus of large numbers?

/* The algorithm is from the book "Discrete Mathematics and Its
   Applications 5th Edition" by Kenneth H. Rosen.
   (base^exp)%mod
*/

int modular(int base, unsigned int exp, unsigned int mod)
{
    int x = 1;
    int power = base % mod;

    for (int i = 0; i < sizeof(int) * 8; i++) {
        int least_sig_bit = 0x00000001 & (exp >> i);
        if (least_sig_bit)
            x = (x * power) % mod;
        power = (power * power) % mod;
    }

    return x;
}

Configure hibernate to connect to database via JNDI Datasource

I was getting the same error in my IBM Websphere with c3p0 jar files. I have Oracle 10g database. I simply added the oraclejdbc.jar files in the Application server JVM in IBM Classpath using Websphere Console and the error was resolved.

The oraclejdbc.jar should be set with your C3P0 jar files in your Server Class path whatever it be tomcat, glassfish of IBM.

Force overwrite of local file with what's in origin repo?

If you want to overwrite only one file:

git fetch
git checkout origin/master <filepath>

If you want to overwrite all changed files:

git fetch
git reset --hard origin/master

(This assumes that you're working on master locally and you want the changes on the origin's master - if you're on a branch, substitute that in instead.)

Converting a byte array to PNG/JPG

There are two problems with this question:

Assuming you have a gray scale bitmap, you have two factors to consider:

  1. For JPGS... what loss of quality is tolerable?
  2. For pngs... what level of compression is tolerable? (Although for most things I've seen, you don't have that much of a choice, so this choice might be negligible.) For anybody thinking this question doesn't make sense: yes, you can change the amount of compression/number of passes attempted to compress; check out either Ifranview or some of it's plugins.

Answer those questions, and then you might be able to find your original answer.

"Android library projects cannot be launched"?

Through the following steps you can do it .

In Eclipse window , Right Click on your Project from Package Explorer. 1. Select Properties, 2. Select Android from Properties, 3. Check "Is Library" check box, 4. If it is checked then Unchecked "Is Library" check box. 5. Click Apply and than OK.

Java: convert seconds to minutes, hours and days

Have a look at the class

org.joda.time.DateTime

This allows you to do things like:

old = new DateTime();
new = old.plusSeconds(500000);
System.out.println("Hours: " + (new.Hours() - old.Hours()));

However, your solution probably can be simpler:

You need to work out how many seconds in a day, divide your input by the result to get the days, and subtract it from the input to keep the remainder. You then need to work out how many hours in the remainder, followed by the minutes, and the final remainder is the seconds.

This is the analysis done for you, now you can focus on the code.

You need to ask what s/he means by "no hard coding", generally it means pass parameters, rather than fixing the input values. There are many ways to do this, depending on how you run your code. Properties are a common way in java.

How to validate email id in angularJs using ng-pattern

I tried @Joanna's method and tested on the following websites and it didn't work.

  1. https://regex101.com/
  2. https://www.regextester.com/
  3. https://regexr.com/

I then modified it to and it worked.

/([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)\S+

What do the icons in Eclipse mean?

This is a fairly comprehensive list from the Eclipse documentation. If anyone knows of another list — maybe with more details, or just the most common icons — feel free to add it.

Latest: JDT Icons

2019-06: JDT Icons

2019-03: JDT Icons

2018-12: JDT Icons

2018-09: JDT Icons

Photon: JDT Icons

Oxygen: JDT Icons

Neon: JDT Icons

Mars: JDT Icons

Luna: JDT Icons

Kepler: JDT Icons

Juno: JDT Icons

Indigo: JDT Icons

Helios: JDT Icons

There are also some CDT icons at the bottom of this help page.

If you're a Subversion user, the icons you're looking for may actually belong to Subclipse; see this excellent answer for more on those.

Response to preflight request doesn't pass access control check

For anyone using Api Gateway's HTTP API and the proxy route ANY /{proxy+}

You will need to explicitly define your route methods in order for CORS to work.

enter image description here

Wish this was more explicit in the AWS Docs for Configuring CORS for an HTTP API

Was on a 2 hour call with AWS Support and they looped in one of their senior HTTP API developers, who made this recommendation.

Hopefully this post can save some time and effort for those who are working with Api Gateway HTTP API.

How to change default timezone for Active Record in Rails?

If you want local time to set, add the following text in application.rb

config.time_zone = 'Chennai'

# WARNING: This changes the way times are stored in the database (not recommended)
config.active_record.default_timezone = :local

Then restart your server

Rails 2.3.4 Persisting Model on Validation Failure

In your controller, render the new action from your create action if validation fails, with an instance variable, @car populated from the user input (i.e., the params hash). Then, in your view, add a logic check (either an if block around the form or a ternary on the helpers, your choice) that automatically sets the value of the form fields to the params values passed in to @car if car exists. That way, the form will be blank on first visit and in theory only be populated on re-render in the case of error. In any case, they will not be populated unless @car is set.

How to get the current logged in user Id in ASP.NET Core

in the APiController

User.FindFirst(ClaimTypes.NameIdentifier).Value

Something like this you will get the claims

How do you set a default value for a MySQL Datetime column?

IMPORTANT EDIT: It is now possible to achieve this with DATETIME fields since MySQL 5.6.5, take a look at the other post below...

Previous versions can't do that with DATETIME...

But you can do it with TIMESTAMP:

mysql> create table test (str varchar(32), ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP);
Query OK, 0 rows affected (0.00 sec)

mysql> desc test;
+-------+-------------+------+-----+-------------------+-------+
| Field | Type        | Null | Key | Default           | Extra |
+-------+-------------+------+-----+-------------------+-------+
| str   | varchar(32) | YES  |     | NULL              |       | 
| ts    | timestamp   | NO   |     | CURRENT_TIMESTAMP |       | 
+-------+-------------+------+-----+-------------------+-------+
2 rows in set (0.00 sec)

mysql> insert into test (str) values ("demo");
Query OK, 1 row affected (0.00 sec)

mysql> select * from test;
+------+---------------------+
| str  | ts                  |
+------+---------------------+
| demo | 2008-10-03 22:59:52 | 
+------+---------------------+
1 row in set (0.00 sec)

mysql>

CAVEAT: IF you define a column with CURRENT_TIMESTAMP ON as default, you will need to ALWAYS specify a value for this column or the value will automatically reset itself to "now()" on update. This means that if you do not want the value to change, your UPDATE statement must contain "[your column name] = [your column name]" (or some other value) or the value will become "now()". Weird, but true. I hope this helps. I am using 5.5.56-MariaDB

How do I install g++ on MacOS X?

Download Xcode, which is free with an ADC online membership (also free):

http://developer.apple.com/technology/xcode.html

How do I convert a calendar week into a date in Excel?

If you are looking for the opposite to get a date from a weeknumber i found a solution online and changed it slightly:

Function fnDateFromWeek(iYear As Integer, iWeek As Integer, iWeekDday As Integer)
  ' get the date from a certain day in a certain week in a certain year
  fnDateFromWeek = DateSerial(iYear, 1, (iWeek * 7) _
          + iWeekDday - Weekday(DateSerial(iYear, 1, 1)) + 1)
End Function

I took the formular from asap-utilities.com/ and changed

DateSerial(iYear, 1, ((iWeek - 1) * 7) 

to

DateSerial(iYear, 1, (iWeek * 7)

Update

It seems that at least for germany the formular works not as expected for the leap year 2016 so i changed it to this

Function fnDateFromWeek(iYear As Integer, iWeek As Integer, iWeekDday As Integer)
' get the date from a certain day in a certain week in a certain year
  
    If isLeapYear(iYear) Then
        curDate = DateSerial(iYear, 1, ((iWeek) * 7) _
          + iWeekDday - Weekday(DateSerial(iYear, 1, 1)) + 1)
    Else
        curDate = DateSerial(iYear, 1, ((iWeek - 1) * 7) _
          + iWeekDday - Weekday(DateSerial(iYear, 1, 1)) + 1)
    End If
    fnDateFromWeek = curDate
End Function

Since 2016 hardcoded is not ideal you could check if a year is a leap year with this function

Function isLeapYear(iYear As Integer) As Boolean

    If (Month(DateSerial(iYear, 2, 29)) = 2) Then
        isLeapYear = True
    Else
        isLeapYear = False
    End If
    
End Function

For a non-leap-year DateSerial(iYear,2 ,29) returns 1st of march

This may still be wrong but my limited test gave the expected results:

Sub TestExample()
   Debug.Print Format(fnDateFromWeek(2014, 48, 2), "ddd dd mmm yyyy") ' mo 24 Nov 2014
   Debug.Print Format(fnDateFromWeek(2015, 11, 6), "ddd dd-mmm-yyyy") ' fr 13 Mar 2015
   Debug.Print Format(fnDateFromWeek(2016, 36, 2), "ddd dd-mmm-yyyy") ' Mo 05 Sep 2015
End Sub

Tomcat 7.0.43 "INFO: Error parsing HTTP request header"

If you don't want to upgrade your tomcat, Add this line in your catalina.properties

tomcat.util.http.parser.HttpParser.requestTargetAllow=|{}

It works for me http://www.zhoulujun.cn/zhoulujun/html/java/tomcat/2018_0508_8109.html

Why does background-color have no effect on this DIV?

Change it to:

<div style="background-color:black; overflow:hidden;" onmouseover="this.bgColor='white'">
<div style="float:left">hello</div>
<div style="float:right">world</div>
</div>

Basically the outer div only contains floats. Floats are removed from the normal flow. As such the outer div really contains nothing and thus has no height. It really is black but you just can't see it.

The overflow:hidden property basically makes the outer div enclose the floats. The other way to do this is:

<div style="background-color:black" onmouseover="this.bgColor='white'">
<div style="float:left">hello</div>
<div style="float:right">world</div>
<div style="clear:both></div>
</div>

Oh and just for completeness, you should really prefer classes to direct CSS styles.

How to save python screen output to a text file

This is very simple, just make use of this example

import sys
with open("test.txt", 'w') as sys.stdout:
    print("hello")

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

If you want to check or set the user name and email you can use the below command

Check user name

git config user.name

Set user name

git config user.name "your_name"

Check your email

git config user.email

Set/change your email

git config user.email "[email protected]"

List/see all configuration

git config --list

Which is fastest? SELECT SQL_CALC_FOUND_ROWS FROM `table`, or SELECT COUNT(*)

When choosing the "best" approach, a more important consideration than speed might be the maintainability and correctness of your code. If so, SQL_CALC_FOUND_ROWS is preferable because you only need to maintain a single query. Using a single query completely precludes the possibility of a subtle difference between the main and count queries, which may lead to an inaccurate COUNT.

Adding a y-axis label to secondary y-axis in matplotlib

For everyone stumbling upon this post because pandas gets mentioned, you now have the very elegant and straighforward option of directly accessing the secondary_y axis in pandas with ax.right_ax

So paraphrasing the example initially posted, you would write:

table = sql.read_frame(query,connection)

ax = table[[0, 1]].plot(ylim=(0,100), secondary_y=table[1])
ax.set_ylabel('$')
ax.right_ax.set_ylabel('Your second Y-Axis Label goes here!')

(this is already mentioned in these posts as well: 1 2)

How to make an Android Spinner with initial text "Select One"?

For those using Xamarin, here is the C# equivalent to aaronvargas's answer above.

using Android.Content;
using Android.Database;
using Android.Views;
using Android.Widget;
using Java.Lang;

namespace MyNamespace.Droid
{ 
  public class NothingSelectedSpinnerAdapter : BaseAdapter, ISpinnerAdapter, IListAdapter
  {
    protected static readonly int EXTRA = 1;
    protected ISpinnerAdapter adapter;
    protected Context context;
    protected int nothingSelectedLayout;
    protected int nothingSelectedDropdownLayout;
    protected LayoutInflater layoutInflater;

    public NothingSelectedSpinnerAdapter(ISpinnerAdapter spinnerAdapter, int nothingSelectedLayout, Context context) : this(spinnerAdapter, nothingSelectedLayout, -1, context)
    {
    }

    public NothingSelectedSpinnerAdapter(ISpinnerAdapter spinnerAdapter, int nothingSelectedLayout, int nothingSelectedDropdownLayout, Context context)
    {
      this.adapter = spinnerAdapter;
      this.context = context;
      this.nothingSelectedLayout = nothingSelectedLayout;
      this.nothingSelectedDropdownLayout = nothingSelectedDropdownLayout;
      layoutInflater = LayoutInflater.From(context);
    }

    protected View GetNothingSelectedView(ViewGroup parent)
    {
      return layoutInflater.Inflate(nothingSelectedLayout, parent, false);
    }

    protected View GetNothingSelectedDropdownView(ViewGroup parent)
    {
      return layoutInflater.Inflate(nothingSelectedDropdownLayout, parent, false);
    }

    public override Object GetItem(int position)
    {
      return position == 0 ? null : adapter.GetItem(position - EXTRA);
    }

    public override long GetItemId(int position)
    {
      return position >= EXTRA ? adapter.GetItemId(position - EXTRA) : position - EXTRA;
    }

    public override View GetView(int position, View convertView, ViewGroup parent)
    {
      // This provides the View for the Selected Item in the Spinner, not
      // the dropdown (unless dropdownView is not set).
      if (position == 0)
      {
        return GetNothingSelectedView(parent);
      }

      // Could re-use the convertView if possible.
      return this.adapter.GetView(position - EXTRA, null, parent);
    }

    public override int Count
    {
      get
      {
        int count = this.adapter.Count;
        return count == 0 ? 0 : count + EXTRA;
      }
    }

    public override View GetDropDownView(int position, View convertView, ViewGroup parent)
    {
      // Android BUG! http://code.google.com/p/android/issues/detail?id=17128 -
      // Spinner does not support multiple view types
      if (position == 0)
      {
        return nothingSelectedDropdownLayout == -1 ?
          new View(context) :
          GetNothingSelectedDropdownView(parent);
      }

      // Could re-use the convertView if possible, use setTag...
      return adapter.GetDropDownView(position - EXTRA, null, parent);
    }

    public override int GetItemViewType(int position)
    {
      return 0;
    }

    public override int ViewTypeCount => 1;

    public override bool HasStableIds => this.adapter.HasStableIds;

    public override bool IsEmpty => this.adapter.IsEmpty;

    public override void RegisterDataSetObserver(DataSetObserver observer)
    {
      adapter.RegisterDataSetObserver(observer);
    }

    public override void UnregisterDataSetObserver(DataSetObserver observer)
    {
      adapter.UnregisterDataSetObserver(observer);
    }

    public override bool AreAllItemsEnabled()
    {
      return false;
    }

    public override bool IsEnabled(int position)
    {
      return position > 0;
    }
  }
}

Phone validation regex

/^[0-9\+]{1,}[0-9\-]{3,15}$/

so first is a digit or a +, then some digits or -

How do I do top 1 in Oracle?

To select the first row from a table and to select one row from a table are two different tasks and need a different query. There are many possible ways to do so. Four of them are:

First

select  max(Fname) from MyTbl;

Second

select  min(Fname) from MyTbl;

Third

select  Fname from MyTbl  where rownum = 1;

Fourth

select  max(Fname) from MyTbl where rowid=(select  max(rowid) from MyTbl)

Make HTML5 video poster be same size as video itself

I came up with this idea and it works perfectly. Okay so basically we want to get rid of the videos first frame from the display and then resize the poster to the videos actual size. If we then set the dimensions we have completed one of these tasks. Then only one remains. So now, the only way I know to get rid of the first frame is to actually define a poster. However we are going to give the video a faked one, one that doesn't exist. This will result in a blank display with the background transparent. I.e. our parent div's background will be visible.

Simple to use, however it might not work with all web browsers if you want to resize the dimension of the background of the div to the dimension of the video since my code is using "background-size".

HTML/HTML5:

<div class="video_poster">
    <video poster="dasdsadsakaslmklda.jpg" controls>
        <source src="videos/myvideo.mp4" type="video/mp4">
        Your browser does not support the video tag.
    </video>
<div>

CSS:

video{
    width:694px;
    height:390px;
}
.video_poster{
    width:694px;
    height:390px;
    background-size:694px 390px;
    background-image:url(images/myvideo_poster.jpg);
}

How to go up a level in the src path of a URL in HTML?

Here is all you need to know about relative file paths:

  • Starting with / returns to the root directory and starts there

  • Starting with ../ moves one directory backward and starts there

  • Starting with ../../ moves two directories backward and starts there (and so on...)

  • To move forward, just start with the first sub directory and keep moving forward.

Click here for more details!

Monitor the Graphics card usage

If you develop in Visual Studio 2013 and 2015 versions, you can use their GPU Usage tool:

Screenshot from MSDN: enter image description here

Moreover, it seems you can diagnose any application with it, not only Visual Studio Projects:

In addition to Visual Studio projects you can also collect GPU usage data on any loose .exe applications that you have sitting around. Just open the executable as a solution in Visual Studio and then start up a diagnostics session and you can target it with GPU usage. This way if you are using some type of engine or alternative development environment you can still collect data on it as long as you end up with an executable.

Source: http://blogs.msdn.com/b/ianhu/archive/2014/12/16/gpu-usage-for-directx-in-visual-studio.aspx

How to parse JSON without JSON.NET library?

You can use DataContractJsonSerializer. See this link for more details.

Spring JPA @Query with LIKE

Try to use the following approach (it works for me):

@Query("SELECT u.username FROM User u WHERE u.username LIKE CONCAT('%',:username,'%')")
List<String> findUsersWithPartOfName(@Param("username") String username);

Notice: The table name in JPQL must start with a capital letter.

How do you append to an already existing string?

#!/bin/bash
message="some text"
message="$message add some more"

echo $message

some text add some more

Binding select element to object in Angular

You can do this too without the need to use [(ngModel)] in your <select> tag

Declare a variable in your ts file

toStr = JSON.stringify;

and in you template do this

 <option *ngFor="let v of values;" [value]="toStr(v)">
      {{v}}
 </option>

and then use

let value=JSON.parse(event.target.value)

to parse the string back into a valid JavaScript object

How do you set the startup page for debugging in an ASP.NET MVC application?

If you want to start at the "application root" as you describe right click on the top level Default.aspx page and choose set as start page. Hit F5 and you're done.

If you want to start at a different controller action see Mark's answer.

Can I force a page break in HTML printing?

_x000D_
_x000D_
First page (scroll down to see the second page)_x000D_
<div style="break-after:page"></div>_x000D_
Second page_x000D_
<br>_x000D_
<br>_x000D_
<button onclick="window.print();return false;" />Print (to see the result) </button>
_x000D_
_x000D_
_x000D_

Just add this where you need the page to go to the next one (the text "page 1" will be on page 1 and the text "page 2" will be on the second page).

Page 1
<div style='page-break-after:always'></div>
Page 2

This works too:

First page (there is a break after this)
<div style="break-after:page"></div>
Second page (This will be printed in the second page)

Simple PHP calculator

<?php
$cal1= $_GET['cal1'];
$cal2= $_GET['cal2'];
$symbol =$_GET['symbol'];


if($symbol == '+')
{
    $add = $cal1 + $cal2;
    echo "Addition is:".$add;
}

else if($symbol == '-')
{
    $subs = $cal1 - $cal2;
    echo "Substraction is:".$subs;
}

 else if($symbol == '*')
{
    $mul = $cal1 * $cal2;
    echo "Multiply is:".$mul;
}

else if($symbol == '/')
{
    $div = $cal1 / $cal2;
    echo "Division is:".$div;
}

  else
{

    echo "Oops ,something wrong in your code son";
}


?>

Using atan2 to find angle between two vectors

Here a little program in Python that uses the angle between vectors to determine if a point is inside or outside a certain polygon

import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from shapely.geometry import Point, Polygon
from pprint import pprint

# Plot variables
x_min, x_max = -6, 12
y_min, y_max = -3, 8
tick_interval = 1
FIG_SIZE = (10, 10)
DELTA_ERROR = 0.00001
IN_BOX_COLOR = 'yellow'
OUT_BOX_COLOR = 'black'


def angle_between(v1, v2):
    """ Returns the angle in radians between vectors 'v1' and 'v2'
        The sign of the angle is dependent on the order of v1 and v2
        so acos(norm(dot(v1, v2))) does not work and atan2 has to be used, see:
        https://stackoverflow.com/questions/21483999/using-atan2-to-find-angle-between-two-vectors
    """
    arg1 = np.cross(v1, v2)
    arg2 = np.dot(v1, v2)
    angle = np.arctan2(arg1, arg2)
    return angle


def point_inside(point, border):
    """ Returns True if point is inside border polygon and False if not
        Arguments:
        :point: x, y in shapely.geometry.Point type
        :border: [x1 y1, x2 y2, ... , xn yn] in shapely.geomettry.Polygon type
    """    
    assert len(border.exterior.coords) > 2,\
        'number of points in the polygon must be > 2'

    point = np.array(point)
    side1 = np.array(border.exterior.coords[0]) - point
    sum_angles = 0
    for border_point in border.exterior.coords[1:]:
        side2 = np.array(border_point) - point
        angle = angle_between(side1, side2)
        sum_angles += angle
        side1 = side2

    # if wn is 1 then the point is inside
    wn = sum_angles / 2 / np.pi
    if abs(wn - 1) < DELTA_ERROR:
        return True
    else:
        return False


class MainMap():

    @classmethod
    def settings(cls, fig_size):
        # set the plot outline, including axes going through the origin
        cls.fig, cls.ax = plt.subplots(figsize=fig_size)
        cls.ax.set_xlim(-x_min, x_max)
        cls.ax.set_ylim(-y_min, y_max)
        cls.ax.set_aspect(1)
        tick_range_x = np.arange(round(x_min + (10*(x_max - x_min) % tick_interval)/10, 1),
            x_max + 0.1, step=tick_interval)
        tick_range_y = np.arange(round(y_min + (10*(y_max - y_min) % tick_interval)/10, 1), 
            y_max + 0.1, step=tick_interval)
        cls.ax.set_xticks(tick_range_x)
        cls.ax.set_yticks(tick_range_y)
        cls.ax.tick_params(axis='both', which='major', labelsize=6)
        cls.ax.spines['left'].set_position('zero')
        cls.ax.spines['right'].set_color('none')
        cls.ax.spines['bottom'].set_position('zero')
        cls.ax.spines['top'].set_color('none')

    @classmethod
    def get_ax(cls):
        return cls.ax

    @staticmethod
    def plot():
        plt.tight_layout()
        plt.show()


class PlotPointandRectangle(MainMap):

    def __init__(self, start_point, rectangle_polygon, tolerance=0):

        self.current_object = None
        self.currently_dragging = False
        self.fig.canvas.mpl_connect('key_press_event', self.on_key)
        self.plot_types = ['o', 'o-']
        self.plot_type = 1
        self.rectangle = rectangle_polygon

        # define a point that can be moved around
        self.point = patches.Circle((start_point.x, start_point.y), 0.10,
            alpha=1)
        if point_inside(start_point, self.rectangle):
            _color = IN_BOX_COLOR
        else:
            _color = OUT_BOX_COLOR
        self.point.set_color(_color)
        self.ax.add_patch(self.point)
        self.point.set_picker(tolerance)
        cv_point = self.point.figure.canvas
        cv_point.mpl_connect('button_release_event', self.on_release)
        cv_point.mpl_connect('pick_event', self.on_pick)
        cv_point.mpl_connect('motion_notify_event', self.on_motion)

        self.plot_rectangle()

    def plot_rectangle(self):
        x = [point[0] for point in self.rectangle.exterior.coords]
        y = [point[1] for point in self.rectangle.exterior.coords]
        # y = self.rectangle.y
        self.rectangle_plot, = self.ax.plot(x, y,
            self.plot_types[self.plot_type], color='r', lw=0.4, markersize=2)

    def on_release(self, event):
        self.current_object = None
        self.currently_dragging = False

    def on_pick(self, event):
        self.currently_dragging = True
        self.current_object = event.artist

    def on_motion(self, event):
        if not self.currently_dragging:
            return
        if self.current_object == None:
            return

        point = Point(event.xdata, event.ydata)
        self.current_object.center = point.x, point.y
        if point_inside(point, self.rectangle):
            _color = IN_BOX_COLOR
        else:
            _color = OUT_BOX_COLOR
        self.current_object.set_color(_color)

        self.point.figure.canvas.draw()

    def remove_rectangle_from_plot(self):
        try:
            self.rectangle_plot.remove()
        except ValueError:
            pass

    def on_key(self, event):
        # with 'space' toggle between just points or points connected with
        # lines
        if event.key == ' ':
            self.plot_type = (self.plot_type + 1) % 2
            self.remove_rectangle_from_plot()
            self.plot_rectangle()
            self.point.figure.canvas.draw()


def main(start_point, rectangle):

    MainMap.settings(FIG_SIZE)
    plt_me = PlotPointandRectangle(start_point, rectangle)  #pylint: disable=unused-variable
    MainMap.plot()

if __name__ == "__main__":
    try:
        start_point = Point([float(val) for val in sys.argv[1].split()])
    except IndexError:
        start_point= Point(0, 0)

    border_points = [(-2, -2),
                     (1, 1),
                     (3, -1),
                     (3, 3.5),
                     (4, 1),
                     (5, 1),
                     (4, 3.5),
                     (5, 6),
                     (3, 4),
                     (3, 5),
                     (-0.5, 1),
                     (-3, 1),
                     (-1, -0.5),
                    ]               

    border_points_polygon = Polygon(border_points)
    main(start_point, border_points_polygon)

How to get value at a specific index of array In JavaScript?

You can just use []:

var valueAtIndex1 = myValues[1];

MySQL Orderby a number, Nulls last

You can swap out instances of NULL with a different value to sort them first (like 0 or -1) or last (a large number or a letter)...

SELECT field1, IF(field2 IS NULL, 9999, field2) as ordered_field2
  FROM tablename
 WHERE visible = 1
 ORDER BY ordered_field2 ASC, id DESC

Android on-screen keyboard auto popping up

Add this in parent layout of the XML.

android:focusable="true" 
android:focusableInTouchMode="true"

It ensures the focus isn't on the editText when the Activity starts.

Default values and initialization in Java

In the first code sample, a is a main method local variable. Method local variables need to be initialized before using them.

In the second code sample, a is class member variable, hence it will be initialized to the default value.

Execute a command line binary with Node.js

If you want something that closely resembles the top answer but is also synchronous then this will work.

var execSync = require('child_process').execSync;
var cmd = "echo 'hello world'";

var options = {
  encoding: 'utf8'
};

console.log(execSync(cmd, options));

How to Convert datetime value to yyyymmddhhmmss in SQL server?

also this works too

SELECT replace(replace(replace(convert(varchar, getdate(), 120),':',''),'-',''),' ','')

JavaScript: client-side vs. server-side validation

Client side should use a basic validation via HTML5 input types and pattern attributes and as these are only used for progressive enhancements for better user experience (Even if they are not supported on < IE9 and safari, but we don't rely on them). But the main validation should happen on the server side..

Your password does not satisfy the current policy requirements

For Laravel users having this issue with MySQL 8.0.x, add

'modes'=> [
             'ONLY_FULL_GROUP_BY',
             'STRICT_TRANS_TABLES',
             'NO_ZERO_IN_DATE',
             'NO_ZERO_DATE',
             'ERROR_FOR_DIVISION_BY_ZERO',
             'NO_ENGINE_SUBSTITUTION',
            ],

to your database.php file as below:

// database.php

    'connections' => [

        'mysql' => [
            'driver'      => 'mysql',
            'host'        => env( 'DB_HOST', '127.0.0.1' ),
            'port'        => env( 'DB_PORT', '3306' ),
            'database'    => env( 'DB_DATABASE', 'forge' ),
            'username'    => env( 'DB_USERNAME', 'forge' ),
            'password'    => env( 'DB_PASSWORD', '' ),
            'unix_socket' => env( 'DB_SOCKET', '' ),
            'charset'     => 'utf8mb4',
            'collation'   => 'utf8mb4_unicode_ci',
            'prefix'      => '',
            'strict'      => true,
            'engine'      => null,
            'modes'       => [
                'ONLY_FULL_GROUP_BY',
                'STRICT_TRANS_TABLES',
                'NO_ZERO_IN_DATE',
                'NO_ZERO_DATE',
                'ERROR_FOR_DIVISION_BY_ZERO',
                'NO_ENGINE_SUBSTITUTION',
            ],
        ],
    ],

It fixed it for me.

Increase max_execution_time in PHP?

Is very easy, this work for me:

PHP:

set_time_limit(300); // Time in seconds, max_execution_time

Here is the PHP documentation

How to filter input type="file" dialog by specific file type?

Add a custom attribute to <input type="file" file-accept="jpg gif jpeg png bmp"> and read the filenames within javascript that matches the extension provided by the attribute file-accept. This will be kind of bogus, as a text file with any of the above extension will erroneously deteted as image.

Format specifier %02x

Your string is wider than your format width of 2. So there's no padding to be done.

How to extract numbers from a string in Python?

Since none of these dealt with real world financial numbers in excel and word docs that I needed to find, here is my variation. It handles ints, floats, negative numbers, currency numbers (because it doesn't reply on split), and has the option to drop the decimal part and just return ints, or return everything.

It also handles Indian Laks number system where commas appear irregularly, not every 3 numbers apart.

It does not handle scientific notation or negative numbers put inside parentheses in budgets -- will appear positive.

It also does not extract dates. There are better ways for finding dates in strings.

import re
def find_numbers(string, ints=True):            
    numexp = re.compile(r'[-]?\d[\d,]*[\.]?[\d{2}]*') #optional - in front
    numbers = numexp.findall(string)    
    numbers = [x.replace(',','') for x in numbers]
    if ints is True:
        return [int(x.replace(',','').split('.')[0]) for x in numbers]            
    else:
        return numbers

How can I selectively merge or pick changes from another branch in Git?

There is another way to go:

git checkout -p

It is a mix between git checkout and git add -p and might quite be exactly what you are looking for:

   -p, --patch
       Interactively select hunks in the difference between the <tree-ish>
       (or the index, if unspecified) and the working tree. The chosen
       hunks are then applied in reverse to the working tree (and if a
       <tree-ish> was specified, the index).

       This means that you can use git checkout -p to selectively discard
       edits from your current working tree. See the “Interactive Mode”
       section of git-add(1) to learn how to operate the --patch mode.

change Oracle user account status from EXPIRE(GRACE) to OPEN

set long 9999999
set lin 400
select DBMS_METADATA.GET_DDL('USER','YOUR_USER_NAME') from dual;

This will output something like this:

SQL> select DBMS_METADATA.GET_DDL('USER','WILIAM') from dual;

DBMS_METADATA.GET_DDL('USER','WILIAM')
--------------------------------------------------------------------------------

   CREATE USER "WILIAM" IDENTIFIED BY VALUES 'S:6680C1468F5F3B36B726CE7620F
FD9657F0E0E49AE56AAACE847BA368CEB;120F24A4C2554B4F'
      DEFAULT TABLESPACE "USER"
      TEMPORARY TABLESPACE "TEMP"
      PASSWORD EXPIRE

Just use the first piece of that with alter user instead:

ALTER USER "WILIAM" IDENTIFIED BY VALUES 'S:6680C1468F5F3B36B726CE7620F
FD9657F0E0E49AE56AAACE847BA368CEB;120F24A4C2554B4F';

This will put the account back in to OPEN status without changing the password (as long as you cut and paste correctly the hash value from the output of DBMS_METADATA.GET_DDL) and you don't even need to know what the password is.

UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 1

I was getting the same type of error, and I found that the console is not capable of displaying the string in another language. Hence I made the below code changes to set default_charset as UTF-8.

data_head = [('\x81\xa1\x8fo\x89\xef\x82\xa2\x95\xdb\x8f\xd8\x90\xa7\x93x\x81\xcb3\x8c\x8e\x8cp\x91\xb1\x92\x86(\x81\x86\x81\xde\x81\x85)\x81\xa1\x8f\x89\x89\xf1\x88\xc8\x8aO\x81A\x82\xa8\x8b\xe0\x82\xcc\x90S\x94z\x82\xcd\x88\xea\x90\xd8\x95s\x97v\x81\xa1\x83}\x83b\x83v\x82\xcc\x82\xa8\x8e\x8e\x82\xb5\x95\xdb\x8c\xaf\x82\xc5\x8fo\x89\xef\x82\xa2\x8am\x92\xe8\x81\xa1', 'shift_jis')]
default_charset = 'UTF-8' #can also try 'ascii' or other unicode type
print ''.join([ unicode(lin[0], lin[1] or default_charset) for lin in data_head ])