Programs & Examples On #Units of measurement

Units of Measure are compile-time attributes that can be associated with numeric values, typically used to indicate length, volume, mass, and so on.

Converting bytes to megabytes

Divide by 2 to the power of 20, (1024*1024) bytes = 1 megabyte

1024*1024 = 1,048,576   
2^20 = 1,048,576
1,048,576/1,048,576 = 1  

It is the same thing.

What is the difference between "px", "dip", "dp" and "sp"?

SDP - a scalable size unit - basically it is not a unit, but dimension resources for different screen size.

Try the sdp library from Intuit. It's very handy to solve unit problems, and you can quickly support multiple screens.

Usage

android:paddingBottom="@dimen/_15sdp" for positive and android:layout_marginTop="@dimen/_minus10sdp" for negative sdp sdp

It has equivalent value in dp for each size in values-sw<N>dp folders (sw = smallestWidth).

Attention

Use it carefully! In most cases you still need to design a different layout for tablets.

Example

<LinearLayout
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_marginTop="@dimen/_minus10sdp"
          android:paddingBottom="@dimen/_15sdp"
          android:orientation="horizontal" >

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:includeFontPadding="false"
                    android:text="?"
                    android:textColor="#ED6C27"
                    android:textSize="@dimen/_70sdp"
                    android:textStyle="bold" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:includeFontPadding="false"
                    android:text="U"
                    android:textColor="@android:color/black"
                    android:textSize="@dimen/_70sdp" />
            </LinearLayout>

You can use db for text size, but I prefer ssp for text size.

For more details, check the library GitHub page.

Should I use px or rem value units in my CSS?

TL;DR: use px.

The Facts

  • First, it's extremely important to know that per spec, the CSS px unit does not equal one physical display pixel. This has always been true – even in the 1996 CSS 1 spec.

    CSS defines the reference pixel, which measures the size of a pixel on a 96 dpi display. On a display that has a dpi substantially different than 96dpi (like Retina displays), the user agent rescales the px unit so that its size matches that of a reference pixel. In other words, this rescaling is exactly why 1 CSS pixel equals 2 physical Retina display pixels.

    That said, up until 2010 (and the mobile zoom situation notwithstanding), the px almost always did equal one physical pixel, because all widely available displays were around 96dpi.

  • Sizes specified in ems are relative to the parent element. This leads to the em's "compounding problem" where nested elements get progressively larger or smaller. For example:

    body { font-size:20px; } 
    div { font-size:0.5em; }
    

    Gives us:

    <body> - 20px
        <div> - 10px
            <div> - 5px
                <div> - 2.5px
                    <div> - 1.25px
    
  • The CSS3 rem, which is always relative only to the root html element, is now supported on 96% of all browsers in use.

The Opinion

I think everyone agrees that it's good to design your pages to be accommodating to everyone, and to make consideration for the visually impaired. One such consideration (but not the only one!) is allowing users to make the text of your site bigger, so that it's easier to read.

In the beginning, the only way to provide users a way to scale text size was by using relative size units (such as ems). This is because the browser's font size menu simply changed the root font size. Thus, if you specified font sizes in px, they wouldn't scale when changing the browser's font size option.

Modern browsers (and even the not-so-modern IE7) all changed the default scaling method to simply zooming in on everything, including images and box sizes. Essentially, they make the reference pixel larger or smaller.

Yes, someone could still change their browser default stylesheet to tweak the default font size (the equivalent of the old-style font size option), but that's a very esoteric way of going about it and I'd wager nobody1 does it. (In Chrome, it's buried under the advanced settings, Web content, Font Sizes. In IE9, it's even more hidden. You have to press Alt, and go to View, Text Size.) It's much easier to just select the Zoom option in the browser's main menu (or use Ctrl++/-/mouse wheel).

1 - within statistical error, naturally

If we assume most users scale pages using the zoom option, I find relative units mostly irrelevant. It's much easier to develop your page when everything is specified in the same unit (images are all dealt with in pixels), and you don't have to worry about compounding. ("I was told there would be no math" – there's dealing with having to calculate what 1.5em actually works out to.)

One other potential problem of using only relative units for font sizes is that user-resized fonts may break assumptions your layout makes. For example, this might lead to text getting clipped or running too long. If you use absolute units, you don't have to worry about unexpected font sizes from breaking your layout.

So my answer is use pixel units. I use px for everything. Of course, your situation may vary, and if you must support IE6 (may the gods of the RFCs have mercy on you), you'll have to use ems anyway.

Why em instead of px?

The general consensus is to use percentages for font sizing, because it's more consistent across browsers/platforms.

It's funny though, I always used to use pt for font sizing and I assumed all sites used that. You don't normally use px sizes in other apps (eg Word). I guess it's because they're for printing - but the size is the same in a web browser as in Word...

Get an object attribute

You can do the following:

class User(object):
    fullName = "John Doe"

    def __init__(self, name):
        self.SName = name

    def print_names(self):
        print "Names: full name: '%s', name: '%s'" % (self.fullName, self.SName)

user = User('Test Name')

user.fullName # "John Doe"
user.SName # 'Test Name'
user.print_names() # will print you Names: full name: 'John Doe', name: 'Test Name'

E.g any object attributes could be retrieved using istance.

Create Git branch with current changes

Like stated in this question: Git: Create a branch from unstagged/uncommited changes on master: stash is not necessary.

Just use:

git checkout -b topic/newbranch

Any uncommitted work will be taken along to the new branch.

If you try to push you will get the following message

fatal: The current branch feature/NEWBRANCH has no upstream branch. To push the current branch and set the remote as upstream, use

git push --set-upstream origin feature/feature/NEWBRANCH

Just do as suggested to create the branch remotely:

git push --set-upstream origin feature/feature/NEWBRANCH

What is SOA "in plain english"?

I would suggest you read articles by Thomas Erl and Roger Sessions, this will give you a firm handle on what SOA is all about. These are also good resources, look at the SOA explained for your boss one for a layman explanation

Building a SOA

SOA Design Pattern

Achieving integrity in a SOA

Why your SOA should be like a VW Beetle

SOA explained for your boss

WCF Service Performance

Accessing the last entry in a Map

move does not make sense for a hashmap since its a dictionary with a hashcode for bucketing based on key and then a linked list for colliding hashcodes resolved via equals. Use a TreeMap for sorted maps and then pass in a custom comparator.

write a shell script to ssh to a remote machine and execute commands

There are multiple remote linux machines, and I need to write a shell script which will execute the same set of commands in each machine. (Including some sudo operations). How can this be done using shell scripting?

You can do this with ssh, for example:

#!/bin/bash
USERNAME=someUser
HOSTS="host1 host2 host3"
SCRIPT="pwd; ls"
for HOSTNAME in ${HOSTS} ; do
    ssh -l ${USERNAME} ${HOSTNAME} "${SCRIPT}"
done

When ssh'ing to the remote machine, how to handle when it prompts for RSA fingerprint authentication.

You can add the StrictHostKeyChecking=no option to ssh:

ssh -o StrictHostKeyChecking=no -l username hostname "pwd; ls"

This will disable the host key check and automatically add the host key to the list of known hosts. If you do not want to have the host added to the known hosts file, add the option -o UserKnownHostsFile=/dev/null.

Note that this disables certain security checks, for example protection against man-in-the-middle attack. It should therefore not be applied in a security sensitive environment.

How to convert a Collection to List?

Something like this should work, calling the ArrayList constructor that takes a Collection:

List theList = new ArrayList(coll);

Android Emulator sdcard push error: Read-only file system

mount -o remount, rw /sdcard

this is the correct way to remount your sdcard using your emulator.

addClass - can add multiple classes on same div?

You code is ok only except that you can't add same class test1.

$('.page-address-edit').addClass('test1').addClass('test2'); //this will add test1 and test2

And you could also do

$('.page-address-edit').addClass('test1 test2');

Create a zip file and download it

One of the error could be that the file is not read as 'archive' format. check out ZipArchive not opening file - Error Code: 19. Open the downloaded file in text editor, if you have any html tags or debug statements at the starting, clear the buffer before reading the file.

ob_clean();
flush();
readfile("$archive_file_name");

How to subtract 30 days from the current date using SQL Server

TRY THIS:

Cast your VARCHAR value to DATETIME and add -30 for subtraction. Also, In sql-server the format Fri, 14 Nov 2014 23:03:35 GMT was not converted to DATETIME. Try substring for it:

SELECT DATEADD(dd, -30, 
       CAST(SUBSTRING ('Fri, 14 Nov 2014 23:03:35 GMT', 6, 21) 
       AS DATETIME))

Entity Framework rollback and remove bad migration

As the question indicates this applies to a migration in a development type environment that has not yet been released.

This issue can be solved in these steps: restore your database to the last good migration, delete the bad migration from your Entity Framework project, generate a new migration and apply it to the database. Note: Judging from the comments these exact commands may no longer be applicable if you are using EF Core.

Step 1: Restore to a previous migration

If you haven't yet applied your migration you can skip this part. To restore your database schema to a previous point issue the Update-Database command with -TargetMigration option specify the last good migration. If your entity framework code resides in a different project in your solution, you may need to use the '-Project' option or switch the default project in the package manager console.

Update-Database –TargetMigration: <name of last good migration>

To get the name of the last good migration use the 'Get-Migrations' command to retrieve a list of the migration names that have been applied to your database.

PM> Get-Migrations
Retrieving migrations that have been applied to the target database.
201508242303096_Bad_Migration
201508211842590_The_Migration_applied_before_it
201508211440252_And_another

This list shows the most recent applied migrations first. Pick the migration that occurs in the list after the one you want to downgrade to, ie the one applied before the one you want to downgrade. Now issue an Update-Database.

Update-Database –TargetMigration: "<the migration applied before it>"

All migrations applied after the one specified will be down-graded in order starting with the latest migration applied first.

Step 2: Delete your migration from the project

remove-migration name_of_bad_migration

If the remove-migration command is not available in your version of Entity Framework, delete the files of the unwanted migration your EF project 'Migrations' folder manually. At this point, you are free to create a new migration and apply it to the database.

Step 3: Add your new migration

add-migration my_new_migration

Step 4: Apply your migration to the database

update-database

How to compile without warnings being treated as errors?

Remove -Werror from your Make or CMake files, as suggested in this post

MAVEN_HOME, MVN_HOME or M2_HOME

Here is my Maven setup. You can use it as an example. You don't need anything else in order to use Maven.

M2_HOME is used for both Maven 2 and 3

export M2_HOME=/Users/xxx/sdk/apache-maven-3.0.5
export M2=$M2_HOME/bin
export MAVEN_OPTS="-Xmx1048m -Xms256m -XX:MaxPermSize=312M"
export PATH=$M2:$PATH

ClassCastException, casting Integer to Double

specify your marks:

List<Double> marks = new ArrayList<Double>();

This is called generics.

Git: list only "untracked" files (also, custom commands)

I think this will do the same thing as the original poster intended:

git add .

Adding some caveats:

  • You have run git status and confirmed your local directories are clean
  • You have run git diff on each file reported in git status, and confirmed your changes are clean
  • Your changes are covered with automated unit testing
  • Your changes are covered with automated integration testing
  • You have run the integration tests through a debugger, verifying the new behavior by white box observing the new code in action
  • You have run all linting / code convention rules and they pass
  • You have run all unit tests and they pass
  • You have run all local integration tests, and they pass
  • You have deployed your changes to an app review environment and manually tested them end to end in isolation from other changes
  • You have merged latest from main branch and re-run all automated unit and integration testing, fixing any merge conflicts and test failures

Now, my friend, you are ready to git add . with impunity.

Postgresql Windows, is there a default password?

Try this:

Open PgAdmin -> Files -> Open pgpass.conf

You would get the path of pgpass.conf at the bottom of the window. Go to that location and open this file, you can find your password there.

Reference

If the above does not work, you may consider trying this:

 1. edit pg_hba.conf to allow trust authorization temporarily
 2. Reload the config file (pg_ctl reload)
 3. Connect and issue ALTER ROLE / PASSWORD to set the new password
 4. edit pg_hba.conf again and restore the previous settings
 5. Reload the config file again

jquery drop down menu closing by clicking outside

how to have a click event outside of the dropdown menu so that it close the dropdown menu ? Heres the code

$(document).click(function (e) {
    e.stopPropagation();
    var container = $(".dropDown");

    //check if the clicked area is dropDown or not
    if (container.has(e.target).length === 0) {
        $('.subMenu').hide();
    }
})

How to return a boolean method in java?

public boolean verifyPwd(){
        if (!(pword.equals(pwdRetypePwd.getText()))){
                  txtaError.setEditable(true);
                  txtaError.setText("*Password didn't match!");
                  txtaError.setForeground(Color.red);
                  txtaError.setEditable(false);
                  return false;
           }
        else {
            addNewUser();
            return true;
        }
}

When do I need to use a semicolon vs a slash in Oracle SQL?

I wanted to clarify some more use between the ; and the /

In SQLPLUS:

  1. ; means "terminate the current statement, execute it and store it to the SQLPLUS buffer"
  2. <newline> after a D.M.L. (SELECT, UPDATE, INSERT,...) statement or some types of D.D.L (Creating Tables and Views) statements (that contain no ;), it means, store the statement to the buffer but do not run it.
  3. / after entering a statement into the buffer (with a blank <newline>) means "run the D.M.L. or D.D.L. or PL/SQL in the buffer.
  4. RUN or R is a sqlsplus command to show/output the SQL in the buffer and run it. It will not terminate a SQL Statement.
  5. / during the entering of a D.M.L. or D.D.L. or PL/SQL means "terminate the current statement, execute it and store it to the SQLPLUS buffer"

NOTE: Because ; are used for PL/SQL to end a statement ; cannot be used by SQLPLUS to mean "terminate the current statement, execute it and store it to the SQLPLUS buffer" because we want the whole PL/SQL block to be completely in the buffer, then execute it. PL/SQL blocks must end with:

END;
/

What is the equivalent of Java static methods in Kotlin?

Use object to represent val/var/method to make static. You can use object instead of singleton class also. You can use companion if you wanted to make static inside of a class

object Abc{
     fun sum(a: Int, b: Int): Int = a + b
    }

If you need to call it from Java:

int z = Abc.INSTANCE.sum(x,y);

In Kotlin, ignore INSTANCE.

Matplotlib transparent line plots

After I plotted all the lines, I was able to set the transparency of all of them as follows:

for l in fig_field.gca().lines:
    l.set_alpha(.7)

EDIT: please see Joe's answer in the comments.

Remove duplicates from dataframe, based on two columns A,B, keeping row with max value in another column C

You can do this simply by using pandas drop duplicates function

df.drop_duplicates(['A','B'],keep= 'last')

How to discard local commits in Git?

git reset --hard origin/master

will remove all commits not in origin/master where origin is the repo name and master is the name of the branch.

How to loop through Excel files and load them into a database using SSIS package?

I ran into an article that illustrates a method where the data from the same excel sheet can be imported in the selected table until there is no modifications in excel with data types.

If the data is inserted or overwritten with new ones, importing process will be successfully accomplished, and the data will be added to the table in SQL database.

The article may be found here: http://www.sqlshack.com/using-ssis-packages-import-ms-excel-data-database/

Hope it helps.

How can I refresh c# dataGridView after update ?

You can use the DataGridView refresh method. But... in a lot of cases you have to refresh the DataGridView from methods running on a different thread than the one where the DataGridView is running. In order to do that you should implement the following method and call it rather than directly typing DataGridView.Refresh():

    private void RefreshGridView()
    {
        if (dataGridView1.InvokeRequired)
        {
            dataGridView1.Invoke((MethodInvoker)delegate ()
            {
                RefreshGridView();
            });
        }
        else
            dataGridView1.Refresh();
    }  

Bootstrap carousel width and height

I recommend the following for Bootstrap 3

.carousel-inner > .item > img,
.carousel-inner > .item > a > img {
  min-height: 500px;    /* Set slide height here */

}

Twitter Bootstrap 3 Sticky Footer

To Summarize all of these, just keep one thing in your mind that everything except footer should have min-height: 100% or little less.

Converting HTML to Excel?

We copy/paste html pages from our ERP to Excel using "paste special.. as html/unicode" and it works quite well with tables.

How to change Git log date formats

git log -n1 --format="Last committed item in this release was by %an, `git log -n1 --format=%at | awk '{print strftime("%y%m%d%H%M",$1)}'`, message: %s (%h) [%d]"

View the change history of a file using Git versioning

I wrote git-playback for this exact purpose

pip install git-playback
git playback [filename]

This has the benefit of both displaying the results in the command line (like git log -p) while also letting you step through each commit using the arrow keys (like gitk).

show more/Less text with just HTML and JavaScript

I'm not an expert, but I did a lot of looking to implement this for myself. I found something different, but modified it to accomplish this. It's really quite simple:

The function takes two arguments, a div containing only the words "show more" [or whatever] and a div containing the originally hidden text and the words "show less." The function displays the one div and hides the other.

NOTE: If more than one show/hide on page, assign different ids to divs Colors can be changed

<p>Here is text that is originally displayed</p>

<div id="div1">
<p style="color:red;" onclick="showFunction('div2','div1')">show more</p></div>
<div id="div2" style="display:none">

<p>Put expanded text here</p>

<p style="color:red;" onclick="showFunction('div1','div2')">show less</p></div>

<p>more text</p>

Here is the Script:

<script>
function showFunction(diva, divb) {
    var x = document.getElementById(diva);
    var y = document.getElementById(divb);
          x.style.display = 'block';
          y.style.display = 'none';
}
</script>

Evaluating string "3*(4+2)" yield int 18

Using the compiler to do implies memory leaks as the generated assemblies are loaded and never released. It's also less performant than using a real expression interpreter. For this purpose you can use Ncalc which is an open-source framework with this solely intent. You can also define your own variables and custom functions if the ones already included aren't enough.

Example:

Expression e = new Expression("2 + 3 * 5");
Debug.Assert(17 == e.Evaluate());

Access the css ":after" selector with jQuery

You can't manipulate :after, because it's not technically part of the DOM and therefore is inaccessible by any JavaScript. But you can add a new class with a new :after specified.

CSS:

.pageMenu .active.changed:after { 
/* this selector is more specific, so it takes precedence over the other :after */
    border-top-width: 22px;
    border-left-width: 22px;
    border-right-width: 22px;
}

JS:

$('.pageMenu .active').toggleClass('changed');

UPDATE: while it's impossible to directly modify the :after content, there are ways to read and/or override it using JavaScript. See "Manipulating CSS pseudo-elements using jQuery (e.g. :before and :after)" for a comprehensive list of techniques.

Android emulator failed to allocate memory 8

This following solution worked for me. In the following configuration file:

C:\Users\<user>\.android\avd\<avd-profile-name>.avd\config.ini

Replace

hw.ramSize=1024

by

hw.ramSize=1024MB

How to make a view with rounded corners?

The tutorial link you provided seems to suggest that you need to set the layout_width and layout_height properties, of your child elements to match_parent.

<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent">

How can I check if a program exists from a Bash script?

hash foo 2>/dev/null: works with Z shell (Zsh), Bash, Dash and ash.

type -p foo: it appears to work with Z shell, Bash and ash (BusyBox), but not Dash (it interprets -p as an argument).

command -v foo: works with Z shell, Bash, Dash, but not ash (BusyBox) (-ash: command: not found).

Also note that builtin is not available with ash and Dash.

$.focus() not working

if you use bootstrap + modal, this worked for me :

  $(myModal).modal('toggle');
  $(myModal).on('shown.bs.modal', function() {
    $('#modalSearchBox').focus()
  });

How to verify element present or visible in selenium 2 (Selenium WebDriver)

You could try something like:

    WebElement rxBtn = driver.findElement(By.className("icon-rx"));
    WebElement otcBtn = driver.findElement(By.className("icon-otc"));
    WebElement herbBtn = driver.findElement(By.className("icon-herb"));

    Assert.assertEquals(true, rxBtn.isDisplayed());
    Assert.assertEquals(true, otcBtn.isDisplayed());
    Assert.assertEquals(true, herbBtn.isDisplayed());

This is just an example. Basically you declare and define the WebElement variables you wish to use and then Assert whether or not they are displayed. This is using TestNG Assertions.

Parsing JSON using C

I used JSON-C for a work project and would recommend it. Lightweight and is released with open licensing.

Documentation is included in the distribution. You basically have *_add functions to create JSON objects, equivalent *_put functions to release their memory, and utility functions that convert types and output objects in string representation.

The licensing allows inclusion with your project. We used it in this way, compiling JSON-C as a static library that is linked in with the main build. That way, we don't have to worry about dependencies (other than installing Xcode).

JSON-C also built for us under OS X (x86 Intel) and Linux (x86 Intel) without incident. If your project needs to be portable, this is a good start.

Environment.GetFolderPath(...CommonApplicationData) is still returning "C:\Documents and Settings\" on Vista

Output on Windows 7 (64-bit)

SpecialFolder.CommonApplicationData: C:\ProgramData 
SpecialFolder.CommonDesktopDirectory: C:\Users\Public\Desktop
SpecialFolder.CommonStartMenu: C:\ProgramData\Microsoft\Windows\Start Menu
SpecialFolder.CommonPrograms: C:\ProgramData\Microsoft\Windows\Start Menu\Programs
SpecialFolder.CommonProgramFiles: C:\Program Files\Common Files
SpecialFolder.CommonProgramFilesX86: C:\Program Files (x86)\Common Files
SpecialFolder.CommonStartup: C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup
SpecialFolder.ProgramFiles: C:\Program Files
SpecialFolder.ProgramFilesX86: C:\Program Files (x86)
SpecialFolder.System: C:\Windows\system32
SpecialFolder.SystemX86: C:\Windows\SysWOW64

Output on Windows XP

SpecialFolder.CommonApplicationData: C:\Documents and Settings\All Users\Application Data
SpecialFolder.CommonDesktopDirectory: C:\Documents and Settings\All Users\Desktop
SpecialFolder.CommonPrograms: C:\Documents and Settings\All Users\Start Menu\Programs
SpecialFolder.CommonProgramFiles: C:\Program Files\Common Files
SpecialFolder.CommonProgramFilesX86:
SpecialFolder.CommonStartMenu: C:\Documents and Settings\All Users\Start Menu
SpecialFolder.CommonStartup: C:\Documents and Settings\All Users\Start Menu\Programs\Startup
SpecialFolder.ProgramFiles: C:\Program Files
SpecialFolder.ProgramFilesX86:
SpecialFolder.System: C:\WINDOWS\system32
SpecialFolder.SystemX86: C:\WINDOWS\system32

Reading e-mails from Outlook with Python through MAPI

I have created my own iterator to iterate over Outlook objects via python. The issue is that python tries to iterates starting with Index[0], but outlook expects for first item Index[1]... To make it more Ruby simple, there is below a helper class Oli with following methods:

.items() - yields a tuple(index, Item)...

.prop() - helping to introspect outlook object exposing available properties (methods and attributes)

from win32com.client import constants
from win32com.client.gencache import EnsureDispatch as Dispatch

outlook = Dispatch("Outlook.Application")
mapi = outlook.GetNamespace("MAPI")

class Oli():
    def __init__(self, outlook_object):
        self._obj = outlook_object

    def items(self):
        array_size = self._obj.Count
        for item_index in xrange(1,array_size+1):
            yield (item_index, self._obj[item_index])

    def prop(self):
        return sorted( self._obj._prop_map_get_.keys() )

for inx, folder in Oli(mapi.Folders).items():
    # iterate all Outlook folders (top level)
    print "-"*70
    print folder.Name

    for inx,subfolder in Oli(folder.Folders).items():
        print "(%i)" % inx, subfolder.Name,"=> ", subfolder

npm ERR cb() never called

For anyone who has upgraded recently from 6.x to 6.7.0.

Deleting the /Users/{YOUR USERNAME}/.npm folder solved my issues with npm install.

I also, ran some of these commands suggested by https://npm.community/t/crash-npm-err-cb-never-called/858/93?u=jasonfoglia

sudo npm cache clean -f
sudo npm install -g n

But I'm not sure which actually worked until I deleted the folder. So if you experience this issue and just delete the .npm folder fixing your issue please note that in the comments.

Remove the complete styling of an HTML button/submit

I think it's the button "active" state.

How to force cp to overwrite without confirmation

So I run into this a lot because I keep cp aliased to cp -iv, and I found a neat trick. It turns out that while -i and -n both cancel previous overwrite directives, -f does not. However, if you use -nf it adds the ability to clear the -i. So:

cp -f /foo/* /bar  <-- Prompt
cp -nf /foo/* /bar <-- No Prompt

Pretty neat huh? /necropost

Calling another different view from the controller using ASP.NET MVC 4

You have to specify the name of the custom view and its related model in Controller Action method.

public ActionResult About()
{            
   return View("NameOfViewYouWantToReturn",Model); 
}

Boxplot in R showing the mean

With ggplot2:

p<-qplot(spray,count,data=InsectSprays,geom='boxplot')
p<-p+stat_summary(fun.y=mean,shape=1,col='red',geom='point')
print(p)

Get only filename from url in php without any variable values which exist in the url

This should work:

echo basename($_SERVER['REQUEST_URI'], '?' . $_SERVER['QUERY_STRING']);

But beware of any malicious parts in your URL.

Bootstrap: wider input field

In bootstrap 4, they have designed a bigger input file.

A simple solution to increase the size input file is to use font-size:

Add you style, for example:

input[type="file"] {
  font-size:35px
}

Otherwise, you can make one custom class and add to input control.

What is the difference between the HashMap and Map objects in Java?

I was just going to do this as a comment on the accepted answer but it got too funky (I hate not having line breaks)

ah, so the difference is that in general, Map has certain methods associated with it. but there are different ways or creating a map, such as a HashMap, and these different ways provide unique methods that not all maps have.

Exactly--and you always want to use the most general interface you possibly can. Consider ArrayList vs LinkedList. Huge difference in how you use them, but if you use "List" you can switch between them readily.

In fact, you can replace the right-hand side of the initializer with a more dynamic statement. how about something like this:

List collection;
if(keepSorted)
    collection=new LinkedList();
else
    collection=new ArrayList();

This way if you are going to fill in the collection with an insertion sort, you would use a linked list (an insertion sort into an array list is criminal.) But if you don't need to keep it sorted and are just appending, you use an ArrayList (More efficient for other operations).

This is a pretty big stretch here because collections aren't the best example, but in OO design one of the most important concepts is using the interface facade to access different objects with the exact same code.

Edit responding to comment:

As for your map comment below, Yes using the "Map" interface restricts you to only those methods unless you cast the collection back from Map to HashMap (which COMPLETELY defeats the purpose).

Often what you will do is create an object and fill it in using it's specific type (HashMap), in some kind of "create" or "initialize" method, but that method will return a "Map" that doesn't need to be manipulated as a HashMap any more.

If you ever have to cast by the way, you are probably using the wrong interface or your code isn't structured well enough. Note that it is acceptable to have one section of your code treat it as a "HashMap" while the other treats it as a "Map", but this should flow "down". so that you are never casting.

Also notice the semi-neat aspect of roles indicated by interfaces. A LinkedList makes a good stack or queue, an ArrayList makes a good stack but a horrific queue (again, a remove would cause a shift of the entire list) so LinkedList implements the Queue interface, ArrayList does not.

Add a custom attribute to a Laravel / Eloquent model on load?

The problem is caused by the fact that the Model's toArray() method ignores any accessors which do not directly relate to a column in the underlying table.

As Taylor Otwell mentioned here, "This is intentional and for performance reasons." However there is an easy way to achieve this:

class EventSession extends Eloquent {

    protected $table = 'sessions';
    protected $appends = array('availability');

    public function getAvailabilityAttribute()
    {
        return $this->calculateAvailability();  
    }
}

Any attributes listed in the $appends property will automatically be included in the array or JSON form of the model, provided that you've added the appropriate accessor.

Old answer (for Laravel versions < 4.08):

The best solution that I've found is to override the toArray() method and either explicity set the attribute:

class Book extends Eloquent {

    protected $table = 'books';

    public function toArray()
    {
        $array = parent::toArray();
        $array['upper'] = $this->upper;
        return $array;
    }

    public function getUpperAttribute()
    {
        return strtoupper($this->title);    
    }

}

or, if you have lots of custom accessors, loop through them all and apply them:

class Book extends Eloquent {

    protected $table = 'books';

    public function toArray()
    {
        $array = parent::toArray();
        foreach ($this->getMutatedAttributes() as $key)
        {
            if ( ! array_key_exists($key, $array)) {
                $array[$key] = $this->{$key};   
            }
        }
        return $array;
    }

    public function getUpperAttribute()
    {
        return strtoupper($this->title);    
    }

}

How to get the next auto-increment id in mysql

I suggest to rethink what you are doing. I never experienced one single use case where that special knowledge is required. The next id is a very special implementation detail and I wouldn't count on getting it is ACID safe.

Make one simple transaction which updates your inserted row with the last id:

BEGIN;

INSERT INTO payments (date, item, method)
     VALUES (NOW(), '1 Month', 'paypal');

UPDATE payments SET payment_code = CONCAT("sahf4d2fdd45", LAST_INSERT_ID())
     WHERE id = LAST_INSERT_ID();

COMMIT;

What is the precise meaning of "ours" and "theirs" in git?

From git checkout's usage:

-2, --ours            checkout our version for unmerged files
-3, --theirs          checkout their version for unmerged files
-m, --merge           perform a 3-way merge with the new branch

When resolving merge conflicts, you can do git checkout --theirs some_file, and git checkout --ours some_file to reset the file to the current version and the incoming versions respectively.

If you've done git checkout --ours some_file or git checkout --theirs some_file and would like to reset the file to the 3-way merge version of the file, you can do git checkout --merge some_file.

Show dialog from fragment?

 public void showAlert(){


     AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
     LayoutInflater inflater = getActivity().getLayoutInflater();
     View alertDialogView = inflater.inflate(R.layout.test_dialog, null);
     alertDialog.setView(alertDialogView);

     TextView textDialog = (TextView) alertDialogView.findViewById(R.id.text_testDialogMsg);
     textDialog.setText(questionMissing);

     alertDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int which) {
             dialog.cancel();
         }
     });
     alertDialog.show();

}

where .test_dialog is of xml custom

BeautifulSoup Grab Visible Webpage Text

The title is inside an <nyt_headline> tag, which is nested inside an <h1> tag and a <div> tag with id "article".

soup.findAll('nyt_headline', limit=1)

Should work.

The article body is inside an <nyt_text> tag, which is nested inside a <div> tag with id "articleBody". Inside the <nyt_text> element, the text itself is contained within <p> tags. Images are not within those <p> tags. It's difficult for me to experiment with the syntax, but I expect a working scrape to look something like this.

text = soup.findAll('nyt_text', limit=1)[0]
text.findAll('p')

Catch multiple exceptions in one line (except block)

From Python documentation -> 8.3 Handling Exceptions:

A try statement may have more than one except clause, to specify handlers for different exceptions. At most one handler will be executed. Handlers only handle exceptions that occur in the corresponding try clause, not in other handlers of the same try statement. An except clause may name multiple exceptions as a parenthesized tuple, for example:

except (RuntimeError, TypeError, NameError):
    pass

Note that the parentheses around this tuple are required, because except ValueError, e: was the syntax used for what is normally written as except ValueError as e: in modern Python (described below). The old syntax is still supported for backwards compatibility. This means except RuntimeError, TypeError is not equivalent to except (RuntimeError, TypeError): but to except RuntimeError as TypeError: which is not what you want.

How to use format() on a moment.js duration?

This works for me:

moment({minutes: 150}).format('HH:mm') // 01:30

How can I save application settings in a Windows Forms application?

I don't like the proposed solution of using web.config or app.config. Try reading your own XML. Have a look at XML Settings Files – No more web.config.

How to import existing *.sql files in PostgreSQL 8.4?

Always preferred using a connection service file (lookup/google 'psql connection service file')

Then simply:

psql service={yourservicename} < {myfile.sql}

Where yourservicename is a section name from the service file.

Delete empty rows

If you are trying to delete empty spaces , try using ='' instead of is null. Hence , if your row contains empty spaces , is null will not capture those records. Empty space is not null and null is not empty space.

Dec  Hex     Binary    Char-acter Description
0    00  00000000      NUL        null

32  20  00100000      Space       space

So I recommend:

delete  from foo_table  where bar = ''

#or 

delete  from foo_table  where bar = '' or bar is null 

#or even better , 

delete from foo_table where rtrim(ltrim(isnull(bar,'')))='';

JavaScript code for getting the selected value from a combo box

There is an unnecessary hashtag; change the code to this:

var e = document.getElementById("ticket_category_clone").value;

How to restore default perspective settings in Eclipse IDE

Go Windows -> Perspective -> Reset Perspective definetly this one help you.

Python - How to concatenate to a string in a for loop?

That's not how you do it.

>>> ''.join(['first', 'second', 'other'])
'firstsecondother'

is what you want.

If you do it in a for loop, it's going to be inefficient as string "addition"/concatenation doesn't scale well (but of course it's possible):

>>> mylist = ['first', 'second', 'other']
>>> s = ""
>>> for item in mylist:
...    s += item
...
>>> s
'firstsecondother'

How to get current instance name from T-SQL

How about this:

EXECUTE xp_regread @rootkey='HKEY_LOCAL_MACHINE',
                   @key='SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQl',
                   @value_name='MSSQLSERVER'

This will get the instance name as well. null means default instance:

SELECT SERVERPROPERTY ('InstanceName')

http://technet.microsoft.com/en-us/library/ms174396.aspx

ping response "Request timed out." vs "Destination Host unreachable"

As I understand it, "request timeout" means the ICMP packet reached from one host to the other host but the reply could not reach the requesting host. There may be more packet loss or some physical issue. "destination host unreachable" means there is no proper route defined between two hosts.

How to Specify Eclipse Proxy Authentication Credentials?

In Eclipse, go to Window → Preferences → General → Network Connections. In the Active Provider combo box, choose "Manual". In the proxy entries table, for each entry click "Edit..." and supply your proxy host, port, username and password details.

Eclipse screenshot

Spring Boot Remove Whitelabel Error Page

server.error.whitelabel.enabled=false

Include the above line to the Resources folders application.properties

More Error Issue resolve please refer http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-customize-the-whitelabel-error-page

What is this Javascript "require"?

I noticed that whilst the other answers explained what require is and that it is used to load modules in Node they did not give a full reply on how to load node modules when working in the Browser.

It is quite simple to do. Install your module using npm as you describe, and the module itself will be located in a folder usually called node_modules.

Now the simplest way to load it into your app is to reference it from your html with a script tag which points at this directory. i.e if your node_modules directory is in the root of the project at the same level as your index.html you would write this in your index.html:

<script src="node_modules/ng"></script>

That whole script will now be loaded into the page - so you can access its variables and methods directly.

There are other approaches which are more widely used in larger projects, such as a module loader like require.js. Of the two, I have not used Require myself, but I think it is considered by many people the way to go.

select a value where it doesn't exist in another table

select ID from A where ID not in (select ID from B);

or

select ID from A except select ID from B;

Your second question:

delete from A where ID not in (select ID from B);

When is each sorting algorithm used?

Quicksort is usually the fastest on average, but It has some pretty nasty worst-case behaviors. So if you have to guarantee no bad data gives you O(N^2), you should avoid it.

Merge-sort uses extra memory, but is particularly suitable for external sorting (i.e. huge files that don't fit into memory).

Heap-sort can sort in-place and doesn't have the worst case quadratic behavior, but on average is slower than quicksort in most cases.

Where only integers in a restricted range are involved, you can use some kind of radix sort to make it very fast.

In 99% of the cases, you'll be fine with the library sorts, which are usually based on quicksort.

"Incorrect string value" when trying to insert UTF-8 into MySQL via JDBC?

Got the same problem, to save the data with utf8mb4 needs to make sure:

  1. character_set_client, character_set_connection, character_set_results are utf8mb4: character_set_client and character_set_connection indicate the character set in which statements are sent by the client, character_set_results indicates the character set in which the server returns query results to the client.
    See charset-connection.

  2. the table and column encoding is utf8mb4

For JDBC, there are two solutions:

Solution 1 (need to restart MySQL):

  1. modify my.cnf like the following and restart MySQL:

    [mysql]
    default-character-set=utf8mb4
    
    [mysqld]
    character-set-server=utf8mb4
    collation-server=utf8mb4_unicode_ci
    

this can make sure the database and character_set_client, character_set_connection, character_set_results are utf8mb4 by default.

  1. restart MySQL

  2. change the table and column encoding to utf8mb4

  3. STOP specifying characterEncoding=UTF-8 and characterSetResults=UTF-8 in the jdbc connector,cause this will override character_set_client, character_set_connection, character_set_results to utf8

Solution two (don't need to restart MySQL):

  1. change the table and column encoding to utf8mb4

  2. specifying characterEncoding=UTF-8 in the jdbc connector,cause the jdbc connector doesn't suport utf8mb4.

  3. write your sql statment like this (need to add allowMultiQueries=true to jdbc connector):

    'SET NAMES utf8mb4;INSERT INTO Mytable ...';
    

this will make sure each connection to the server, character_set_client,character_set_connection,character_set_results are utf8mb4.
Also see charset-connection.

Saving changes after table edit in SQL Server Management Studio

This is a risk to turning off this option. You can lose changes if you have change tracking turned on (your tables).

Chris

http://chrisbarba.wordpress.com/2009/04/15/sql-server-2008-cant-save-changes-to-tables/

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

As gengkev alludes to in his comment above, it looks like the best/only way to do this is with an async xhr2 call:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'blob:http%3A//your.blob.url.here', true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
  if (this.status == 200) {
    var myBlob = this.response;
    // myBlob is now the blob that the object URL pointed to.
  }
};
xhr.send();

Update (2018): For situations where ES5 can safely be used, Joe has a simpler ES5-based answer below.

How to use 'hover' in CSS

You should have used:

a:hover {
    text-decoration: underline;
}

hover is a pseudo class in CSS. No need to assign a class.

Convert Variable Name to String?

To get the variable name of var as a string:

var = 1000
var_name = [k for k,v in locals().items() if v == var][0] 
print(var_name) # ---> outputs 'var'

How to add two strings as if they were numbers?

var result = Number(num1) + Number(num2);

JavaScript implementation of Gzip

We just released pako https://github.com/nodeca/pako , port of zlib to javascript. I think that's now the fastest js implementation of deflate / inflate / gzip / ungzip. Also, it has democratic MIT licence. Pako supports all zlib options and it's results are binary equal.

Example:

var inflate = require('pako/lib/inflate').inflate; 
var text = inflate(zipped, {to: 'string'});

Animation fade in and out

Here is my solution. It uses AnimatorSet. AnimationSet library was too buggy to get working. This provides seamless and infinite transitions between fade in and out.

public static void setAlphaAnimation(View v) {
    ObjectAnimator fadeOut = ObjectAnimator.ofFloat(v, "alpha",  1f, .3f);
    fadeOut.setDuration(2000);
    ObjectAnimator fadeIn = ObjectAnimator.ofFloat(v, "alpha", .3f, 1f);
    fadeIn.setDuration(2000);

    final AnimatorSet mAnimationSet = new AnimatorSet();

    mAnimationSet.play(fadeIn).after(fadeOut);

    mAnimationSet.addListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animation) {
            super.onAnimationEnd(animation);
            mAnimationSet.start();
        }
    });
    mAnimationSet.start();
}

How to remove "index.php" in codeigniter's path

Just thought i might add

RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA] 

would be the .htaccess and be sure to edit your application/config.php variable in the following manner:

replace

$config['uri_protocol'] = “AUTO” 

with

$config['uri_protocol'] = “REQUEST_URI”

C# ASP.NET Send Email via TLS

On SmtpClient there is an EnableSsl property that you would set.

i.e.

SmtpClient client = new SmtpClient(exchangeServer);
client.EnableSsl = true;
client.Send(msg);

yii2 hidden input value

Like This:

<?= $form->field($model, 'hidden')->hiddenInput(['class' => 'form-control', 'maxlength' => true,])->label(false) ?>

Partly JSON unmarshal into a map in Go

Here is an elegant way to do similar thing. But why do partly JSON unmarshal? That doesn't make sense.

  1. Create your structs for the Chat.
  2. Decode json to the Struct.
  3. Now you can access everything in Struct/Object easily.

Look below at the working code. Copy and paste it.

import (
   "bytes"
   "encoding/json" // Encoding and Decoding Package
   "fmt"
 )

var messeging = `{
"say":"Hello",
"sendMsg":{
    "user":"ANisus",
    "msg":"Trying to send a message"
   }
}`

type SendMsg struct {
   User string `json:"user"`
   Msg  string `json:"msg"`
}

 type Chat struct {
   Say     string   `json:"say"`
   SendMsg *SendMsg `json:"sendMsg"`
}

func main() {
  /** Clean way to solve Json Decoding in Go */
  /** Excellent solution */

   var chat Chat
   r := bytes.NewReader([]byte(messeging))
   chatErr := json.NewDecoder(r).Decode(&chat)
   errHandler(chatErr)
   fmt.Println(chat.Say)
   fmt.Println(chat.SendMsg.User)
   fmt.Println(chat.SendMsg.Msg)

}

 func errHandler(err error) {
   if err != nil {
     fmt.Println(err)
     return
   }
 }

Go playground

regex match any whitespace

Your regex should work 'as-is'. Assuming that it is doing what you want it to.

wordA(\s*)wordB(?! wordc)

This means match wordA followed by 0 or more spaces followed by wordB, but do not match if followed by wordc. Note the single space between ?! and wordc which means that wordA wordB wordc will not match, but wordA wordB wordc will.

Here are some example matches and the associated replacement output:

enter image description here

Note that all matches are replaced no matter how many spaces. There are a couple of other points: -

  • (?! wordc) is a negative lookahead, so you wont match lines wordA wordB wordc which is assume is intended (and is why the last line is not matched). Currently you are relying on the space after ?! to match the whitespace. You may want to be more precise and use (?!\swordc). If you want to match against more than one space before wordc you can use (?!\s*wordc) for 0 or more spaces or (?!\s*+wordc) for 1 or more spaces depending on what your intention is. Of course, if you do want to match lines with wordc after wordB then you shouldn't use a negative lookahead.

  • * will match 0 or more spaces so it will match wordAwordB. You may want to consider + if you want at least one space.

  • (\s*) - the brackets indicate a capturing group. Are you capturing the whitespace to a group for a reason? If not you could just remove the brackets, i.e. just use \s.

Update based on comment

Hello the problem is not the expression but the HTML out put   that are not considered as whitespace. it's a Joomla website.

Preserving your original regex you can use:

wordA((?:\s|&nbsp;)*)wordB(?!(?:\s|&nbsp;)wordc)

The only difference is that not the regex matches whitespace OR &nbsp;. I replaced wordc with \swordc since that is more explicit. Note as I have already pointed out that the negative lookahead ?! will not match when wordB is followed by a single whitespace and wordc. If you want to match multiple whitespaces then see my comments above. I also preserved the capture group around the whitespace, if you don't want this then remove the brackets as already described above.

Example matches:

enter image description here

Eventviewer eventid for lock and unlock

You will need to enable logging of these events. Do so by opening the group policy editor:

run -> gpedit.msc

and configuring the following category:

Computer Configuration ->
Windows Settings ->
Security Settings ->
Advanced Audit Policy Configuration ->
System Audit Policies - Local Group Policy Object ->
Logon/Logoff ->
Audit Other Login/Logoff Events

(In the Explain tab it says "... allows you to audit ... Locking and unlocking a workstation".)

How to skip over an element in .map()?

TLDR: You can first filter your array and then perform your map but this would require two passes on the array (filter returns an array to map). Since this array is small, it is a very small performance cost. You can also do a simple reduce. However if you want to re-imagine how this can be done with a single pass over the array (or any datatype), you can use an idea called "transducers" made popular by Rich Hickey.

Answer:

We should not require increasing dot chaining and operating on the array [].map(fn1).filter(f2)... since this approach creates intermediate arrays in memory on every reducing function.

The best approach operates on the actual reducing function so there is only one pass of data and no extra arrays.

The reducing function is the function passed into reduce and takes an accumulator and input from the source and returns something that looks like the accumulator

// 1. create a concat reducing function that can be passed into `reduce`
const concat = (acc, input) => acc.concat([input])

// note that [1,2,3].reduce(concat, []) would return [1,2,3]

// transforming your reducing function by mapping
// 2. create a generic mapping function that can take a reducing function and return another reducing function
const mapping = (changeInput) => (reducing) => (acc, input) => reducing(acc, changeInput(input))

// 3. create your map function that operates on an input
const getSrc = (x) => x.src
const mappingSrc = mapping(getSrc)

// 4. now we can use our `mapSrc` function to transform our original function `concat` to get another reducing function
const inputSources = [{src:'one.html'}, {src:'two.txt'}, {src:'three.json'}]
inputSources.reduce(mappingSrc(concat), [])
// -> ['one.html', 'two.txt', 'three.json']

// remember this is really essentially just
// inputSources.reduce((acc, x) => acc.concat([x.src]), [])


// transforming your reducing function by filtering
// 5. create a generic filtering function that can take a reducing function and return another reducing function
const filtering = (predicate) => (reducing) => (acc, input) => (predicate(input) ? reducing(acc, input): acc)

// 6. create your filter function that operate on an input
const filterJsonAndLoad = (img) => {
  console.log(img)
  if(img.src.split('.').pop() === 'json') {
    // game.loadSprite(...);
    return false;
  } else {
    return true;
  }
}
const filteringJson = filtering(filterJsonAndLoad)

// 7. notice the type of input and output of these functions
// concat is a reducing function,
// mapSrc transforms and returns a reducing function
// filterJsonAndLoad transforms and returns a reducing function
// these functions that transform reducing functions are "transducers", termed by Rich Hickey
// source: http://clojure.com/blog/2012/05/15/anatomy-of-reducer.html
// we can pass this all into reduce! and without any intermediate arrays

const sources = inputSources.reduce(filteringJson(mappingSrc(concat)), []);
// [ 'one.html', 'two.txt' ]

// ==================================
// 8. BONUS: compose all the functions
// You can decide to create a composing function which takes an infinite number of transducers to
// operate on your reducing function to compose a computed accumulator without ever creating that
// intermediate array
const composeAll = (...args) => (x) => {
  const fns = args
  var i = fns.length
  while (i--) {
    x = fns[i].call(this, x);
  }
  return x
}

const doABunchOfStuff = composeAll(
    filtering((x) => x.src.split('.').pop() !== 'json'),
    mapping((x) => x.src),
    mapping((x) => x.toUpperCase()),
    mapping((x) => x + '!!!')
)

const sources2 = inputSources.reduce(doABunchOfStuff(concat), [])
// ['ONE.HTML!!!', 'TWO.TXT!!!']

Resources: rich hickey transducers post

MySQL - Replace Character in Columns

maybe I'd go by this.

 SQL = SELECT REPLACE(myColumn, '""', '\'') FROM myTable

I used singlequotes because that's the one that registers string expressions in MySQL, or so I believe.

Hope that helps.

Convert pyspark string to date format

The strptime() approach does not work for me. I get another cleaner solution, using cast:

from pyspark.sql.types import DateType
spark_df1 = spark_df.withColumn("record_date",spark_df['order_submitted_date'].cast(DateType()))
#below is the result
spark_df1.select('order_submitted_date','record_date').show(10,False)

+---------------------+-----------+
|order_submitted_date |record_date|
+---------------------+-----------+
|2015-08-19 12:54:16.0|2015-08-19 |
|2016-04-14 13:55:50.0|2016-04-14 |
|2013-10-11 18:23:36.0|2013-10-11 |
|2015-08-19 20:18:55.0|2015-08-19 |
|2015-08-20 12:07:40.0|2015-08-20 |
|2013-10-11 21:24:12.0|2013-10-11 |
|2013-10-11 23:29:28.0|2013-10-11 |
|2015-08-20 16:59:35.0|2015-08-20 |
|2015-08-20 17:32:03.0|2015-08-20 |
|2016-04-13 16:56:21.0|2016-04-13 |

ORA-12528: TNS Listener: all appropriate instances are blocking new connections. Instance "CLRExtProc", status UNKNOWN

I had this problem on my developent environment with Visual Studio.

What helped me was to Clean Solution in Visual Studio and then do a rebuild.

Converting a date string to a DateTime object using Joda Time library

There are two ways this could be achieved.

DateTimeFormat

DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss").parseDateTime("04/02/2011 20:27:05");

SimpleDateFormat

        String dateValue = "04/02/2011 20:27:05";
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); //  04/02/2011 20:27:05

        Date date = sdf.parse(dateValue); // returns date object
        System.out.println(date); // outputs: Fri Feb 04 20:27:05 IST 2011

Add Expires headers

try this solution and it is working fine for me

## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType text/html "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType text/css "access plus 1 year"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 1 month"
</IfModule>

<IfModule mod_headers.c>
  <FilesMatch "\.(js|css|xml|gz)$">
    Header append Vary: Accept-Encoding
  </FilesMatch>
</IfModule>

<ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>

<IfModule mod_deflate.c>
SetOutputFilter DEFLATE
AddOutputFilterByType DEFLATE text/html text/css text/plain text/xml text/x-js text/js 
</IfModule>

## EXPIRES CACHING ##

How to determine the encoding of text?

Another option for working out the encoding is to use libmagic (which is the code behind the file command). There are a profusion of python bindings available.

The python bindings that live in the file source tree are available as the python-magic (or python3-magic) debian package. It can determine the encoding of a file by doing:

import magic

blob = open('unknown-file', 'rb').read()
m = magic.open(magic.MAGIC_MIME_ENCODING)
m.load()
encoding = m.buffer(blob)  # "utf-8" "us-ascii" etc

There is an identically named, but incompatible, python-magic pip package on pypi that also uses libmagic. It can also get the encoding, by doing:

import magic

blob = open('unknown-file', 'rb').read()
m = magic.Magic(mime_encoding=True)
encoding = m.from_buffer(blob)

How to validate domain name in PHP?

Here is another way without regex.

$myUrl = "http://www.domain.com/link.php";
$myParsedURL = parse_url($myUrl);
$myDomainName= $myParsedURL['host'];
$ipAddress = gethostbyname($myDomainName);
if($ipAddress == $myDomainName)
{
   echo "There is no url";
}
else
{
   echo "url found";
}

Add up a column of numbers at the Unix shell

cat files.txt | awk '{ total += $1} END {print total}'

You can use the awk to do the same it even skips the non integers

$ cat files.txt
1
2.3
3.4
ew
1

$ cat files.txt | awk '{ total += $1} END {print total}'
7.7

or you can use ls command and calculate human readable output

$ ls -l | awk '{ sum += $5} END  {hum[1024^3]="Gb"; hum[1024^2]="Mb"; hum[1024]="Kb"; for (x=1024^3; x>=1024; x/=1024) { if (sum>=x) { printf "%.2f %s\n",sum/x,hum[x]; break; } } if (sum<1024) print "1kb"; }'
15.69 Mb

$ ls -l *.txt | awk '{ sum += $5} END  {hum[1024^3]="Gb"; hum[1024^2]="Mb"; hum[1024]="Kb"; for (x=1024^3; x>=1024; x/=1024) { if (sum>=x) { printf "%.2f %s\n",sum/x,hum[x]; break; } } if (sum<1024) print "1kb"; }'
2.10 Mb

Multiple Python versions on the same machine?

Update 2019: Using asdf

These days I suggest using asdf to install various versions of Python interpreters next to each other.

Note1: asdf works not only for Python but for all major languages.

Note2: asdf works fine in combination with popular package-managers such as pipenv and poetry.

If you have asdf installed you can easily download/install new Python interpreters:

# Install Python plugin for asdf:
asdf plugin-add python

# List all available Python interpreters:
asdf list-all python

# Install the Python interpreters that you need:
asdf install python 3.7.4
asdf install python 3.6.9
# etc...

# If you want to define the global version:
asdf global python 3.7.4

# If you want to define the local (project) version:
# (this creates a file .tool-versions in the current directory.)
asdf local python 3.7.4

Old Answer: Install Python from source

If you need to install multiple versions of Python (next to the main one) on Ubuntu / Mint: (should work similar on other Unixs'.)

1) Install Required Packages for source compilation

$ sudo apt-get install build-essential checkinstall
$ sudo apt-get install libreadline-gplv2-dev libncursesw5-dev libssl-dev libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev

2) Download and extract desired Python version

Download Python Source for Linux as tarball and move it to /usr/src.

Extract the downloaded package in place. (replace the 'x's with your downloaded version)

$ sudo tar xzf Python-x.x.x.tgz

3) Compile and Install Python Source

$ cd Python-x.x.x
$ sudo ./configure
$ sudo make altinstall

Your new Python bin is now located in /usr/local/bin. You can test the new version:

$ pythonX.X -V
Python x.x.x
$ which pythonX.X
/usr/local/bin/pythonX.X

# Pip is now available for this version as well:
$ pipX.X -V
pip X.X.X from /usr/local/lib/pythonX.X/site-packages (python X.X)

How to access the first property of a Javascript object?

we can also do with this approch.

var example = {
  foo1: { /* stuff1 */},
  foo2: { /* stuff2 */},
  foo3: { /* stuff3 */}
}; 
Object.entries(example)[0][1];

org.hibernate.MappingException: Unknown entity: annotations.Users

Check the package name is given in the property packagesToScan in the dispatcher-servlet.xml

<bean id="sessionFactory"             class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">  
        <property name="dataSource" ref="dataSource" />  
        <property name="packagesToScan" value="**entity package name here**"></property> 
        <property name="hibernateProperties">  
            <props>  
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>  
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>  
            </props>  
        </property>  
    </bean>

How to verify if nginx is running or not?

If you are on mac machine and had installed nginx using

brew install nginx

then

brew services list

is the command for you. This will return a list of services installed via brew and their corresponding status.

enter image description here

grep's at sign caught as whitespace

After some time with Google I asked on the ask ubuntu chat room.

A user there was king enough to help me find the solution I was looking for and i wanted to share so that any following suers running into this may find it:

grep -P "(^|\s)abc(\s|$)" gives the result I was looking for. -P is an experimental implementation of perl regexps.

grepping for abc and then using filters like grep -v '@abc' (this is far from perfect...) should also work, but my patch does something similar.

What's the C# equivalent to the With statement in VB?

Aside from object initializers (usable only in constructor calls), the best you can get is:

var it = Stuff.Elements.Foo;
it.Name = "Bob Dylan";
it.Age = 68;
...

Run react-native application on iOS device directly from command line?

First install the required library globally on your computer:

npm install -g ios-deploy

Go to your settings on your iPhone to find the name of the device.

Then provide that below like:

react-native run-ios --device "______\'s iPhone"

Sometimes this will fail and output a message like this:

Found Xcode project ________.xcodeproj
Could not find device with the name: "_______'s iPhone".
Choose one of the following:
______’s iPhone Udid: _________

That udid is used like this:

react-native run-ios --udid 0412e2c230a14e23451699

Optionally you may use:

react-native run-ios --udid 0412e2c230a14e23451699 -- configuration Release

Xcode 6.1 - How to uninstall command line tools?

An excerpt from an apple technical note (Thanks to matthias-bauch)

Xcode includes all your command-line tools. If it is installed on your system, remove it to uninstall your tools.

If your tools were downloaded separately from Xcode, then they are located at /Library/Developer/CommandLineTools on your system. Delete the CommandLineTools folder to uninstall them.

you could easily delete using terminal:

Here is an article that explains how to remove the command line tools but do it at your own risk.Try this only if any of the above doesn't work.

Proper way to handle multiple forms on one page in Django

Django's class based views provide a generic FormView but for all intents and purposes it is designed to only handle one form.

One way to handle multiple forms with same target action url using Django's generic views is to extend the 'TemplateView' as shown below; I use this approach often enough that I have made it into an Eclipse IDE template.

class NegotiationGroupMultifacetedView(TemplateView):
    ### TemplateResponseMixin
    template_name = 'offers/offer_detail.html'

    ### ContextMixin 
    def get_context_data(self, **kwargs):
        """ Adds extra content to our template """
        context = super(NegotiationGroupDetailView, self).get_context_data(**kwargs)

        ...

        context['negotiation_bid_form'] = NegotiationBidForm(
            prefix='NegotiationBidForm', 
            ...
            # Multiple 'submit' button paths should be handled in form's .save()/clean()
            data = self.request.POST if bool(set(['NegotiationBidForm-submit-counter-bid',
                                              'NegotiationBidForm-submit-approve-bid',
                                              'NegotiationBidForm-submit-decline-further-bids']).intersection(
                                                    self.request.POST)) else None,
            )
        context['offer_attachment_form'] = NegotiationAttachmentForm(
            prefix='NegotiationAttachment', 
            ...
            data = self.request.POST if 'NegotiationAttachment-submit' in self.request.POST else None,
            files = self.request.FILES if 'NegotiationAttachment-submit' in self.request.POST else None
            )
        context['offer_contact_form'] = NegotiationContactForm()
        return context

    ### NegotiationGroupDetailView 
    def post(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)

        if context['negotiation_bid_form'].is_valid():
            instance = context['negotiation_bid_form'].save()
            messages.success(request, 'Your offer bid #{0} has been submitted.'.format(instance.pk))
        elif context['offer_attachment_form'].is_valid():
            instance = context['offer_attachment_form'].save()
            messages.success(request, 'Your offer attachment #{0} has been submitted.'.format(instance.pk))
                # advise of any errors

        else 
            messages.error('Error(s) encountered during form processing, please review below and re-submit')

        return self.render_to_response(context)

The html template is to the following effect:

...

<form id='offer_negotiation_form' class="content-form" action='./' enctype="multipart/form-data" method="post" accept-charset="utf-8">
    {% csrf_token %}
    {{ negotiation_bid_form.as_p }}
    ...
    <input type="submit" name="{{ negotiation_bid_form.prefix }}-submit-counter-bid" 
    title="Submit a counter bid"
    value="Counter Bid" />
</form>

...

<form id='offer-attachment-form' class="content-form" action='./' enctype="multipart/form-data" method="post" accept-charset="utf-8">
    {% csrf_token %}
    {{ offer_attachment_form.as_p }}

    <input name="{{ offer_attachment_form.prefix }}-submit" type="submit" value="Submit" />
</form>

...

Div 100% height works on Firefox but not in IE

I don't think IE supports the use of auto for setting height / width, so you could try giving this a numeric value (like Jarett suggests).

Also, it doesn't look like you are clearing your floats properly. Try adding this to your CSS for #container:

#container {
    height:100%;
    width:100%;
    overflow:hidden;
    /* for IE */
    zoom:1;
}

Pass table as parameter into sql server UDF

PASSING TABLE AS PARAMETER IN STORED PROCEDURE

Step 1:

CREATE TABLE [DBO].T_EMPLOYEES_DETAILS ( Id int, Name nvarchar(50), Gender nvarchar(10), Salary int )

Step 2:

CREATE TYPE EmpInsertType AS TABLE ( Id int, Name nvarchar(50), Gender nvarchar(10), Salary int )

Step 3:

/* Must add READONLY keyword at end of the variable */

CREATE PROC PRC_EmpInsertType @EmployeeInsertType EmpInsertType READONLY AS BEGIN INSERT INTO [DBO].T_EMPLOYEES_DETAILS SELECT * FROM @EmployeeInsertType END

Step 4:

DECLARE @EmployeeInsertType EmpInsertType

INSERT INTO @EmployeeInsertType VALUES(1,'John','Male',50000) INSERT INTO @EmployeeInsertType VALUES(2,'Praveen','Male',60000) INSERT INTO @EmployeeInsertType VALUES(3,'Chitra','Female',45000) INSERT INTO @EmployeeInsertType VALUES(4,'Mathy','Female',6600) INSERT INTO @EmployeeInsertType VALUES(5,'Sam','Male',50000)

EXEC PRC_EmpInsertType @EmployeeInsertType

=======================================

SELECT * FROM T_EMPLOYEES_DETAILS

OUTPUT

1 John Male 50000

2 Praveen Male 60000

3 Chitra Female 45000

4 Mathy Female 6600

5 Sam Male 50000

Substring in excel

What about using Replace all? Just replace All on bracket to space. And comma to space. And I think you can achieve it.

What is Hash and Range Primary Key?

"Hash and Range Primary Key" means that a single row in DynamoDB has a unique primary key made up of both the hash and the range key. For example with a hash key of X and range key of Y, your primary key is effectively XY. You can also have multiple range keys for the same hash key but the combination must be unique, like XZ and XA. Let's use their examples for each type of table:

Hash Primary Key – The primary key is made of one attribute, a hash attribute. For example, a ProductCatalog table can have ProductID as its primary key. DynamoDB builds an unordered hash index on this primary key attribute.

This means that every row is keyed off of this value. Every row in DynamoDB will have a required, unique value for this attribute. Unordered hash index means what is says - the data is not ordered and you are not given any guarantees into how the data is stored. You won't be able to make queries on an unordered index such as Get me all rows that have a ProductID greater than X. You write and fetch items based on the hash key. For example, Get me the row from that table that has ProductID X. You are making a query against an unordered index so your gets against it are basically key-value lookups, are very fast, and use very little throughput.


Hash and Range Primary Key – The primary key is made of two attributes. The first attribute is the hash attribute and the second attribute is the range attribute. For example, the forum Thread table can have ForumName and Subject as its primary key, where ForumName is the hash attribute and Subject is the range attribute. DynamoDB builds an unordered hash index on the hash attribute and a sorted range index on the range attribute.

This means that every row's primary key is the combination of the hash and range key. You can make direct gets on single rows if you have both the hash and range key, or you can make a query against the sorted range index. For example, get Get me all rows from the table with Hash key X that have range keys greater than Y, or other queries to that affect. They have better performance and less capacity usage compared to Scans and Queries against fields that are not indexed. From their documentation:

Query results are always sorted by the range key. If the data type of the range key is Number, the results are returned in numeric order; otherwise, the results are returned in order of ASCII character code values. By default, the sort order is ascending. To reverse the order, set the ScanIndexForward parameter to false

I probably missed some things as I typed this out and I only scratched the surface. There are a lot more aspects to take into consideration when working with DynamoDB tables (throughput, consistency, capacity, other indices, key distribution, etc.). You should take a look at the sample tables and data page for examples.

Raise an error manually in T-SQL to jump to BEGIN CATCH block

you can use raiserror. Read more details here

--from MSDN

BEGIN TRY
    -- RAISERROR with severity 11-19 will cause execution to 
    -- jump to the CATCH block.
    RAISERROR ('Error raised in TRY block.', -- Message text.
               16, -- Severity.
               1 -- State.
               );
END TRY
BEGIN CATCH
    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;

    SELECT 
        @ErrorMessage = ERROR_MESSAGE(),
        @ErrorSeverity = ERROR_SEVERITY(),
        @ErrorState = ERROR_STATE();

    -- Use RAISERROR inside the CATCH block to return error
    -- information about the original error that caused
    -- execution to jump to the CATCH block.
    RAISERROR (@ErrorMessage, -- Message text.
               @ErrorSeverity, -- Severity.
               @ErrorState -- State.
               );
END CATCH;

EDIT If you are using SQL Server 2012+ you can use throw clause. Here are the details.

Connect to SQL Server database from Node.js

//start the program
var express = require('express');
var app = express();

app.get('/', function (req, res) {

    var sql = require("mssql");

    // config for your database
    var config = {
        user: 'datapullman',
        password: 'system',
        server: 'localhost', 
        database: 'chat6' 
    };

    // connect to your database
    sql.connect(config, function (err) {

        if (err) console.log(err);

        // create Request object
        var request = new sql.Request();

        // query to the database and get the records

        request.query("select * From emp", function (err, recordset) {            
            if  (err) console.log(err)

            // send records as a response
            res.send(recordset);

        });
    });
});

var server = app.listen(5000, function () {
    console.log('Server is running..');
});

//create a table as emp in a database (i have created as chat6)

// programs ends here

//save it as app.js and run as node app.js //open in you browser as localhost:5000

How can I generate a list or array of sequential integers in Java?

You could use Guava Ranges

You can get a SortedSet by using

ImmutableSortedSet<Integer> set = Ranges.open(1, 5).asSet(DiscreteDomains.integers());
// set contains [2, 3, 4]

sklearn: Found arrays with inconsistent numbers of samples when calling LinearRegression.fit()

Some days I faced the same problem. Reason was different sizes arrays.

Differences between Lodash and Underscore.js

Lodash is inspired by Underscore.js, but nowadays it is a superior solution. You can make your custom builds, have a higher performance, support AMD and have great extra features. Check this Lodash vs. Underscore.js benchmarks on jsperf and... this awesome post about Lodash:

One of the most useful feature when you work with collections, is the shorthand syntax:

var characters = [
  { 'name': 'barney', 'age': 36, 'blocked': false },
  { 'name': 'fred',   'age': 40, 'blocked': true }
];

// Using "_.filter" callback shorthand
_.filter(characters, { 'age': 36 });

// Using Underscore.js
_.filter(characters, function(character) { return character.age === 36; } );

// ? [{ 'name': 'barney', 'age': 36, 'blocked': false }]

(taken from Lodash documentation)

Getting mouse position in c#

If you need to get current position in form's area(got experimentally), try:

Console.WriteLine("Current mouse position in form's area is " + 
    (Control.MousePosition.X - this.Location.X - 8).ToString() +
    "x" + 
    (Control.MousePosition.Y - this.Location.Y - 30).ToString()
);

Although, 8 and 30 integers were found by experimenting.

Would be awesome if someone could explain why exactly these numbers ^.


Also, there's another variant(considering code is in Form's CodeBehind):

Point cp = PointToClient(Cursor.Position); // Getting a cursor's position according form's area
Console.WriteLine("Cursor position: X = " + cp.X + ", Y = " + cp.Y);

The type WebMvcConfigurerAdapter is deprecated

Since Spring 5 you just need to implement the interface WebMvcConfigurer:

public class MvcConfig implements WebMvcConfigurer {

This is because Java 8 introduced default methods on interfaces which cover the functionality of the WebMvcConfigurerAdapter class

See here:

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/config/annotation/WebMvcConfigurerAdapter.html

Converting a String to Object

String extends Object, which means an Object. Object o = a; If you really want to get as Object, you may do like below.

String s = "Hi";

Object a =s;

echo that outputs to stderr

You could do this, which facilitates reading:

>&2 echo "error"

>&2 copies file descriptor #2 to file descriptor #1. Therefore, after this redirection is performed, both file descriptors will refer to the same file: the one file descriptor #2 was originally referring to. For more information see the Bash Hackers Illustrated Redirection Tutorial.

Transitions on the CSS display property

According to W3C Working Draft 19 November 2013 display is not an animatable property. Fortunately, visibility is animatable. You may chain its transition with a transition of opacity (JSFiddle):

  • HTML:

    <a href="http://example.com" id="foo">Foo</a>
    <button id="hide-button">Hide</button>
    <button id="show-button">Show</button>
    
  • CSS:

    #foo {
        transition-property: visibility, opacity;
        transition-duration: 0s, 1s;
    }
    
    #foo.hidden {
        opacity: 0;
        visibility: hidden;
        transition-property: opacity, visibility;
        transition-duration: 1s, 0s;
        transition-delay: 0s, 1s;
    }
    
  • JavaScript for testing:

    var foo = document.getElementById('foo');
    
    document.getElementById('hide-button').onclick = function () {
        foo.className = 'hidden';
    };
    
    document.getElementById('show-button').onclick = function () {
        foo.className = '';
    };
    

Note that if you just make the link transparent, without setting visibility: hidden, then it would stay clickable.

Javascript: Extend a Function

There are several ways to go about this, it depends what your purpose is, if you just want to execute the function as well and in the same context, you can use .apply():

function init(){
  doSomething();
}
function myFunc(){
  init.apply(this, arguments);
  doSomethingHereToo();
}

If you want to replace it with a newer init, it'd look like this:

function init(){
  doSomething();
}
//anytime later
var old_init = init;
init = function() {
  old_init.apply(this, arguments);
  doSomethingHereToo();
};

How to find locked rows in Oracle

Given some table, you can find which rows are not locked with SELECT FOR UPDATESKIP LOCKED.

For example, this query will lock (and return) every unlocked row:

SELECT * FROM mytable FOR UPDATE SKIP LOCKED

References

How to increase the distance between table columns in HTML?

A better solution than selected answer would be to use border-size rather than border-spacing. The main problem with using border-spacing is that even the first column would have a spacing in the front.

For example,

_x000D_
_x000D_
table {_x000D_
  border-collapse: separate;_x000D_
  border-spacing: 80px 0;_x000D_
}_x000D_
_x000D_
td {_x000D_
  padding: 10px 0;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>First Column</td>_x000D_
    <td>Second Column</td>_x000D_
    <td>Third Column</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>1</td>_x000D_
    <td>2</td>_x000D_
    <td>3</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

To avoid this use: border-left: 100px solid #FFF; and set border:0px for the first column.

For example,

_x000D_
_x000D_
td,th{_x000D_
  border-left: 100px solid #FFF;_x000D_
}_x000D_
_x000D_
 tr>td:first-child {_x000D_
   border:0px;_x000D_
 }
_x000D_
<table id="t">_x000D_
  <tr>_x000D_
    <td>Column1</td>_x000D_
    <td>Column2</td>_x000D_
    <td>Column3</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>1000</td>_x000D_
    <td>2000</td>_x000D_
    <td>3000</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to check if there exists a process with a given pid in Python?

Combining Giampaolo Rodolà's answer for POSIX and mine for Windows I got this:

import os
if os.name == 'posix':
    def pid_exists(pid):
        """Check whether pid exists in the current process table."""
        import errno
        if pid < 0:
            return False
        try:
            os.kill(pid, 0)
        except OSError as e:
            return e.errno == errno.EPERM
        else:
            return True
else:
    def pid_exists(pid):
        import ctypes
        kernel32 = ctypes.windll.kernel32
        SYNCHRONIZE = 0x100000

        process = kernel32.OpenProcess(SYNCHRONIZE, 0, pid)
        if process != 0:
            kernel32.CloseHandle(process)
            return True
        else:
            return False

How to convert a datetime to string in T-SQL

The following query will get the current datetime and convert into string. with the following format
yyyy-mm-dd hh:mm:ss(24h)

SELECT convert(varchar(25), getdate(), 120) 

Call an overridden method from super class in typescript

If you want a super class to call a function from a subclass, the cleanest way is to define an abstract pattern, in this manner you explicitly know the method exists somewhere and must be overridden by a subclass.

This is as an example, normally you do not call a sub method within the constructor as the sub instance is not initialized yet… (reason why you have an "undefined" in your question's example)

abstract class A {
    // The abstract method the subclass will have to call
    protected abstract doStuff():void;

    constructor(){
     alert("Super class A constructed, calling now 'doStuff'")
     this.doStuff();
    }
}

class B extends A{

    // Define here the abstract method
    protected doStuff()
    {
        alert("Submethod called");
    }
}

var b = new B();

Test it Here

And if like @Max you really want to avoid implementing the abstract method everywhere, just get rid of it. I don't recommend this approach because you might forget you are overriding the method.

abstract class A {
    constructor() {
        alert("Super class A constructed, calling now 'doStuff'")
        this.doStuff();
    }

    // The fallback method the subclass will call if not overridden
    protected doStuff(): void {
        alert("Default doStuff");
    };
}

class B extends A {
    // Override doStuff()
    protected doStuff() {
        alert("Submethod called");
    }
}

class C extends A {
    // No doStuff() overriding, fallback on A.doStuff()
}

var b = new B();
var c = new C();

Try it Here

Using Django time/date widgets in custom form

Yep, I ended up overriding the /admin/jsi18n/ url.

Here's what I added in my urls.py. Make sure it's above the /admin/ url

    (r'^admin/jsi18n', i18n_javascript),

And here is the i18n_javascript function I created.

from django.contrib import admin
def i18n_javascript(request):
  return admin.site.i18n_javascript(request)

Excel VBA: Copying multiple sheets into new workbook

This worked for me (I added an "if sheet visible" because in my case I wanted to skip hidden sheets)

   Sub Create_new_file()

Application.DisplayAlerts = False

Dim wb As Workbook
Dim wbNew As Workbook
Dim sh As Worksheet
Dim shNew As Worksheet
Dim pname, parea As String


Set wb = ThisWorkbook
Workbooks.Add
Set wbNew = ActiveWorkbook

For Each sh In wb.Worksheets

    pname = sh.Name


    If sh.Visible = True Then

    sh.Copy After:=wbNew.Sheets(Sheets.Count)

    wbNew.Sheets(Sheets.Count).Cells.ClearContents
    wbNew.Sheets(Sheets.Count).Cells.ClearFormats
    wb.Sheets(sh.Name).Activate
    Range(sh.PageSetup.PrintArea).Select
    Selection.Copy

    wbNew.Sheets(pname).Activate
    Range("A1").Select

    With Selection

        .PasteSpecial (xlValues)
        .PasteSpecial (xlFormats)
        .PasteSpecial (xlPasteColumnWidths)

    End With

    ActiveSheet.Name = pname

    End If


Next

wbNew.Sheets("Hoja1").Delete

Application.DisplayAlerts = True

End Sub

How to move the layout up when the soft keyboard is shown android

Make use of Relative layout it will adjust the view so that you can see that view while typing the text

How can I combine multiple nested Substitute functions in Excel?

I would use the following approach:

=SUBSTITUTE(LEFT(A2,LEN(A2)-X),"_","-")

where X denotes the length of things you're not after. And, for X I'd use

(ISERROR(FIND("_S",A2,1))*2)+
(ISERROR(FIND("_40K",A2,1))*4)+
(ISERROR(FIND("_60K",A2,1))*4)+
(ISERROR(FIND("_AB",A2,1))*3)+
(ISERROR(FIND("_CD",A2,1))*3)+
(ISERROR(FIND("_EF",A2,1))*3)

The above ISERROR(FIND("X",.,.))*x will return 0 if X is not found and x (the length of X) if it is found. So technically you're trimming A2 from the right with possible matches.

The advantage of this approach above the other mentioned is that it's more apparent what substitution (or removal) is taking place, since the "substitution" is not nested.

VBA check if file exists

For checking existence one can also use (works for both, files and folders):

Not Dir(DirFile, vbDirectory) = vbNullString

The result is True if a file or a directory exists.

Example:

If Not Dir("C:\Temp\test.xlsx", vbDirectory) = vbNullString Then
    MsgBox "exists"
Else
    MsgBox "does not exist"
End If

Check If only numeric values were entered in input. (jQuery)

for future visitors, you can add this functon that allow user to enter only numbers: you will only have to add jquery and the class name to the input check that into http://jsfiddle.net/celia/dvnL9has/2/

$('.phone_number').keypress(function(event){
var numero= String.fromCharCode(event.keyCode);
 var myArray = ['0','1','2','3','4','5','6','7','8','9',0,1,2,3,4,5,6,7,8,9];
index = myArray.indexOf(numero);// 1
var longeur= $('.phone_number').val().length;
if(window.getSelection){
 text = window.getSelection().toString();
 } if(index>=0&text.length>0){
  }else if(index>=0&longeur<10){
    }else {return false;} });

Python: PIP install path, what is the correct location for this and other addons?

Modules go in site-packages and executables go in your system's executable path. For your environment, this path is /usr/local/bin/.

To avoid having to deal with this, simply use easy_install, distribute or pip. These tools know which files need to go where.

What is the difference between single-quoted and double-quoted strings in PHP?

Example of single, double, heredoc, and nowdoc quotes

<?php

    $fname = "David";

    // Single quotes
    echo 'My name is $fname.'; // My name is $fname.

    // Double quotes
    echo "My name is $fname."; // My name is David.

    // Curly braces to isolate the name of the variable
    echo "My name is {$fname}."; // My name is David.

    // Example of heredoc
    echo $foo = <<<abc
    My name is {$fname}
    abc;

        // Example of nowdoc
        echo <<< 'abc'
        My name is "$name".
        Now, I am printing some
    abc;

?>

How to print Two-Dimensional Array like table

Declared a 7 by 5 array which is similar to yours, with some dummy data. Below should do.

    int[][] array = {{21, 12, 32, 14, 52}, {43, 43, 55, 66, 72}, {57, 64, 52, 57, 88},{52, 33, 54, 37, 82},{55, 62, 35, 17, 28},{55, 66, 58, 72, 28}}; 
    
    for (int i = 0; i < array.length; i++) {
        for (int j = 0; j < array[i].length; j++) {
            System.out.print(array[i][j] + " ");
        }
        System.out.println(); // the trick is here, print a new line after iterating first row.
    }

Posting JSON data via jQuery to ASP .NET MVC 4 controller action

//simple json object in asp.net mvc

var model = {"Id": "xx", "Name":"Ravi"};
$.ajax({    url: 'test/[ControllerName]',
                        type: "POST",
                        data: model,
                        success: function (res) {
                            if (res != null) {
                                alert("done.");
                            }
                        },
                        error: function (res) {

                        }
                    });


//model in c#
public class MyModel
{
 public string Id {get; set;}
 public string Name {get; set;}
}

//controller in asp.net mvc


public ActionResult test(MyModel model)
{
 //now data in your model 
}

Remove empty array elements

foreach($linksArray as $key => $link) 
{ 
    if($link === '') 
    { 
        unset($linksArray[$key]); 
    } 
} 
print_r($linksArray); 

Iterate a list with indexes in Python

>>> a = [3,4,5,6]
>>> for i, val in enumerate(a):
...     print i, val
...
0 3
1 4
2 5
3 6
>>>

Set encoding and fileencoding to utf-8 in Vim

You can set the variable 'fileencodings' in your .vimrc.

This is a list of character encodings considered when starting to edit an existing file. When a file is read, Vim tries to use the first mentioned character encoding. If an error is detected, the next one in the list is tried. When an encoding is found that works, 'fileencoding' is set to it. If all fail, 'fileencoding' is set to an empty string, which means the value of 'encoding' is used.

See :help filencodings

If you often work with e.g. cp1252, you can add it there:

set fileencodings=ucs-bom,utf-8,cp1252,default,latin9

JSON.Net Self referencing loop detected

This may help you.

public MyContext() : base("name=MyContext") 
{ 
    Database.SetInitializer(new MyContextDataInitializer()); 
    this.Configuration.LazyLoadingEnabled = false; 
    this.Configuration.ProxyCreationEnabled = false; 
} 

http://code.msdn.microsoft.com/Loop-Reference-handling-in-caaffaf7

How do I truly reset every setting in Visual Studio 2012?

Click on Tools menu > Import and Export Settings > Reset all settings > Next > "No, just reset settings, overwriting all current settings" > Next > Finish.

How to set default Checked in checkbox ReactJS?

<div className="display__lbl_input">
              <input
                type="checkbox"
                onChange={this.handleChangeFilGasoil}
                value="Filter Gasoil"
                name="Filter Gasoil"
                id=""
              />
              <label htmlFor="">Filter Gasoil</label>
            </div>

handleChangeFilGasoil = (e) => {
    if(e.target.checked){
        this.setState({
            checkedBoxFG:e.target.value
        })
        console.log(this.state.checkedBoxFG)
    }
    else{
     this.setState({
        checkedBoxFG : ''
     })
     console.log(this.state.checkedBoxFG)
    }
  };

Sending images using Http Post

I usually do this in the thread handling the json response:

try {
  Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageUrl).getContent());
} catch (MalformedURLException e) {
  e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();
}

If you need to do transformations on the image, you'll want to create a Drawable instead of a Bitmap.

Delete ActionLink with confirm dialog

I wanted the same thing; a delete button on my Details view. I eventually realised I needed to post from that view:

@using (Html.BeginForm())
        {
            @Html.AntiForgeryToken()
            @Html.HiddenFor(model => model.Id)
            @Html.ActionLink("Edit", "Edit", new { id = Model.Id }, new { @class = "btn btn-primary", @style="margin-right:30px" })

            <input type="submit" value="Delete" class="btn btn-danger" onclick="return confirm('Are you sure you want to delete this record?');" />
        }

And, in the Controller:

 // this action deletes record - called from the Delete button on Details view
    [HttpPost]
    public ActionResult Details(MainPlus mainPlus)
    {
        if (mainPlus != null)
        {
            try
            {
                using (IDbConnection db = new SqlConnection(PCALConn))
                {
                    var result = db.Execute("DELETE PCAL.Main WHERE Id = @Id", new { Id = mainPlus.Id });
                }
                return RedirectToAction("Calls");
            } etc

How to get last items of a list in Python?

You can use negative integers with the slicing operator for that. Here's an example using the python CLI interpreter:

>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
>>> a[-9:]
[4, 5, 6, 7, 8, 9, 10, 11, 12]

the important line is a[-9:]

How to set encoding in .getJSON jQuery

You need to analyze the JSON calls using Wireshark, so you will see if you include the charset in the formation of the JSON page or not, for example:

  • If the page is simple if text / html
0000  48 54 54 50 2f 31 2e 31  20 32 30 30 20 4f 4b 0d   HTTP/1.1  200 OK.
0010  0a 43 6f 6e 74 65 6e 74  2d 54 79 70 65 3a 20 74   .Content -Type: t
0020  65 78 74 2f 68 74 6d 6c  0d 0a 43 61 63 68 65 2d   ext/html ..Cache-
0030  43 6f 6e 74 72 6f 6c 3a  20 6e 6f 2d 63 61 63 68   Control:  no-cach
  • If the page is of the type including custom JSON with MIME "charset = ISO-8859-1"
0000  48 54 54 50 2f 31 2e 31  20 32 30 30 20 4f 4b 0d   HTTP/1.1  200 OK.
0010  0a 43 61 63 68 65 2d 43  6f 6e 74 72 6f 6c 3a 20   .Cache-C ontrol: 
0020  6e 6f 2d 63 61 63 68 65  0d 0a 43 6f 6e 74 65 6e   no-cache ..Conten
0030  74 2d 54 79 70 65 3a 20  74 65 78 74 2f 68 74 6d   t-Type:  text/htm
0040  6c 3b 20 63 68 61 72 73  65 74 3d 49 53 4f 2d 38   l; chars et=ISO-8
0050  38 35 39 2d 31 0d 0a 43  6f 6e 6e 65 63 74 69 6f   859-1..C onnectio

Why is that? because we can not put on the page of JSON a goal like this:

In my case I use the manufacturer Connect Me 9210 Digi:

  • I had to use a flag to indicate that one would use non-standard MIME: p-> theCgiPtr-> = fDataType eRpDataTypeOther;
  • It added the new MIME in the variable: strcpy (p-> theCgiPtr-> fOtherMimeType, "text / html; charset = ISO-8859-1 ");

It worked for me without having to convert the data passed by JSON for UTF-8 and then redo the conversion on the page ...

Returning Month Name in SQL Server Query

Without hitting db we can fetch all months name.

WITH CTE_Sample1 AS
(
    Select 0 as MonthNumber

    UNION ALL

    select MonthNumber+1 FROM CTE_Sample1
        WHERE MonthNumber+1<12
)

Select DateName( month , DateAdd( month , MonthNumber ,0 ) ) from CTE_Sample1

Using ResourceManager

This SO answer might help in this case.
If the main project already references the resource project, then you could just explicitly work with your generated-resource class in your code, and access its ResourceManager from that. Hence, something along the lines of:

ResourceManager resMan = YeagerTechResources.Resources.ResourceManager;

// then, you could go on working with that
ResourceSet resourceSet = resMan.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
// ...

Why should I prefer to use member initialization lists?

  1. Initialization of base class

One important reason for using constructor initializer list which is not mentioned in answers here is initialization of base class.

As per the order of construction, base class should be constructed before child class. Without constructor initializer list, this is possible if your base class has default constructor which will be called just before entering the constructor of child class.

But, if your base class has only parameterized constructor, then you must use constructor initializer list to ensure that your base class is initialized before child class.

  1. Initialization of Subobjects which only have parameterized constructors

  2. Efficiency

Using constructor initializer list, you initialize your data members to exact state which you need in your code rather than first initializing them to their default state & then changing their state to the one you need in your code.

  1. Initializing non-static const data members

If non-static const data members in your class have default constructors & you don't use constructor initializer list, you won't be able to initialize them to intended state as they will be initialized to their default state.

  1. Initialization of reference data members

Reference data members must be intialized when compiler enters constructor as references can't be just declared & initialized later. This is possible only with constructor initializer list.

Jquery, set value of td in a table?

use .html() along with selector to get/set HTML:

 $('#detailInfo').html('changed value');

Jackson - Deserialize using generic class

You need to create a TypeReference object for each generic type you use and use that for deserialization. For example -

mapper.readValue(jsonString, new TypeReference<Data<String>>() {});

How do I write outputs to the Log in Android?

import android.util.Log;

and then

Log.i("the your message will go here"); 

How do I start my app on startup?

Another approach is to use android.intent.action.USER_PRESENT instead of android.intent.action.BOOT_COMPLETED to avoid slow downs during the boot process. But this is only true if the user has enabled the lock Screen - otherwise this intent is never broadcasted.

Reference blog - The Problem With Android’s ACTION_USER_PRESENT Intent

PHP: How to remove specific element from an array?

foreach ($get_dept as $key5 => $dept_value) {
                if ($request->role_id == 5 || $request->role_id == 6){
                    array_splice($get_dept, $key5, 1);
                }
            }

GUI Tool for PostgreSQL

Postgres Enterprise Manager from EnterpriseDB is probably the most advanced you'll find. It includes all the features of pgAdmin, plus monitoring of your hosts and database servers, predictive reporting, alerting and a SQL Profiler.

http://www.enterprisedb.com/products-services-training/products/postgres-enterprise-manager

Ninja edit disclaimer/notice: it seems that this user is affiliated with EnterpriseDB, as the linked Postgres Enterprise Manager website contains a video of one Dave Page.

Saving plots (AxesSubPlot) generated from python pandas with matplotlib's savefig

this may be a simpler approach:

(DesiredFigure).get_figure().savefig('figure_name.png')

i.e.

dfcorr.hist(bins=50).get_figure().savefig('correlation_histogram.png')

How can I escape double quotes in XML attributes values?

The String conversion page on the Coder's Toolbox site is handy for encoding more than a small amount of HTML or XML code for inclusion as a value in an XML element.

How to search for a string in text files?

How to search the text in the file and Returns an file path in which the word is found (??? ?????? ????? ?????? ? ????? ? ?????????? ???? ? ????? ? ??????? ??? ????? ???????)

import os
import re

class Searcher:
    def __init__(self, path, query):
        self.path   = path

        if self.path[-1] != '/':
            self.path += '/'

        self.path = self.path.replace('/', '\\')
        self.query  = query
        self.searched = {}

    def find(self):
        for root, dirs, files in os.walk( self.path ):
            for file in files:
                if re.match(r'.*?\.txt$', file) is not None:
                    if root[-1] != '\\':
                        root += '\\'           
                    f = open(root + file, 'rt')
                    txt = f.read()
                    f.close()

                    count = len( re.findall( self.query, txt ) )
                    if count > 0:
                        self.searched[root + file] = count

    def getResults(self):
        return self.searched

In Main()

# -*- coding: UTF-8 -*-

import sys
from search import Searcher

path = 'c:\\temp\\'
search = 'search string'


if __name__ == '__main__':

    if len(sys.argv) == 3:
        # ??????? ?????? ?????????? ? ???????? ??? ?????????
        Search = Searcher(sys.argv[1], sys.argv[2])
    else:
        Search = Searcher(path, search)

    # ?????? ?????
    Search.find()

    # ???????? ?????????
    results = Search.getResults()

    # ??????? ?????????
    print 'Found ', len(results), ' files:'

    for file, count in results.items():
        print 'File: ', file, ' Found entries:' , count

How to load external webpage in WebView

public class WebViewController extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
}
webView.setWebViewClient(new WebViewController());

2D cross-platform game engine for Android and iOS?

I find a nice and tidy Wave game engine few days ago. It uses C# and have Windows Phone and Windows Store converters as well which makes it a great replacement of XNA for me

How to increment an iterator by 2?

You could use the 'assignment by addition' operator

iter += 2;

Squash my last X commits together using Git

I think the easiest way to do this is by making a new branch based on master and doing a merge --squash of the feature branch.

git checkout master
git checkout -b feature_branch_squashed
git merge --squash feature_branch

Then you have all of the changes ready to commit.

Border for an Image view in Android?

you must create a background.xml in res/drawable this code

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#FFFFFF" />
<corners android:radius="6dp" />
<stroke
    android:width="6dp"
    android:color="@android:color/white" />
<padding
    android:bottom="6dp"
    android:left="6dp"
    android:right="6dp"
    android:top="6dp" />
</shape>

How to prevent errno 32 broken pipe?

The broken pipe error usually occurs if your request is blocked or takes too long and after request-side timeout, it'll close the connection and then, when the respond-side (server) tries to write to the socket, it will throw a pipe broken error.

How do I get the current year using SQL on Oracle?

To display the current system date in oracle-sql

   select sysdate from dual;

How to activate virtualenv?

For Windows You can perform as:

TO create the virtual env as: virtualenv envName –python=python.exe (if not create environment variable)

To activate the virtual env : > \path\to\envName\Scripts\activate

To deactivate the virtual env : > \path\to\env\Scripts\deactivate

It fine works on the new python version .

Jenkins - Configure Jenkins to poll changes in SCM

That's an old question, I know. But, according to me, it is missing proper answer.

The actual / optimal workflow here would be to incorporate SVN's post-commit hook so it triggers Jenkins job after the actual commit is issued only, not in any other case. This way you avoid unneeded polls on your SCM system.

You may find the following links interesting:

In case of my setup in the corp's SVN server, I utilize the following (censored) script as a post-commit hook on the subversion server side:

#!/bin/sh

# POST-COMMIT HOOK

REPOS="$1"
REV="$2"
#TXN_NAME="$3"
LOGFILE=/var/log/xxx/svn/xxx.post-commit.log

MSG=$(svnlook pg --revprop $REPOS svn:log -r$REV)
JENK="http://jenkins.xxx.com:8080/job/xxx/job/xxx/buildWithParameters?token=xxx&username=xxx&cause=xxx+r$REV"
JENKtest="http://jenkins.xxx.com:8080/view/all/job/xxx/job/xxxx/buildWithParameters?token=xxx&username=xxx&cause=xxx+r$REV"

echo post-commit $* >> $LOGFILE 2>&1

# trigger Jenkins job - xxx
svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -qP "branches/xxx/xxx/Source"
if test 0 -eq $? ; then
        echo $(date) - $REPOS - $REV: >> $LOGFILE
        svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -P "branches/xxx/xxx/Source" >> $LOGFILE 2>&1
        echo logmsg: $MSG >> $LOGFILE 2>&1
        echo curl -qs $JENK >> $LOGFILE 2>&1
        curl -qs $JENK >> $LOGFILE 2>&1
        echo -------- >> $LOGFILE
fi

# trigger Jenkins job - xxxx
svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -qP "branches/xxx_TEST"
if test 0 -eq $? ; then
        echo $(date) - $REPOS - $REV: >> $LOGFILE
        svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -P "branches/xxx_TEST" >> $LOGFILE 2>&1
        echo logmsg: $MSG >> $LOGFILE 2>&1
        echo curl -qs $JENKtest >> $LOGFILE 2>&1
        curl -qs $JENKtest >> $LOGFILE 2>&1
        echo -------- >> $LOGFILE
fi

exit 0

How to escape single quotes within single quoted strings

I can confirm that using '\'' for a single quote inside a single-quoted string does work in Bash, and it can be explained in the same way as the "gluing" argument from earlier in the thread. Suppose we have a quoted string: 'A '\''B'\'' C' (all quotes here are single quotes). If it is passed to echo, it prints the following: A 'B' C. In each '\'' the first quote closes the current single-quoted string, the following \' glues a single quote to the previous string (\' is a way to specify a single quote without starting a quoted string), and the last quote opens another single-quoted string.

How to update values using pymongo?

You can use the $set syntax if you want to set the value of a document to an arbitrary value. This will either update the value if the attribute already exists on the document or create it if it doesn't. If you need to set a single value in a dictionary like you describe, you can use the dot notation to access child values.

If p is the object retrieved:

existing = p['d']['a']

For pymongo versions < 3.0

db.ProductData.update({
  '_id': p['_id']
},{
  '$set': {
    'd.a': existing + 1
  }
}, upsert=False, multi=False)

For pymongo versions >= 3.0

db.ProductData.update_one({
  '_id': p['_id']
},{
  '$set': {
    'd.a': existing + 1
  }
}, upsert=False)

However if you just need to increment the value, this approach could introduce issues when multiple requests could be running concurrently. Instead you should use the $inc syntax:

For pymongo versions < 3.0:

db.ProductData.update({
  '_id': p['_id']
},{
  '$inc': {
    'd.a': 1
  }
}, upsert=False, multi=False)

For pymongo versions >= 3.0:

db.ProductData.update_one({
  '_id': p['_id']
},{
  '$inc': {
    'd.a': 1
  }
}, upsert=False)

This ensures your increments will always happen.

How to compare two maps by their values

I don't think there is a "apache-common-like" tool to compare maps since the equality of 2 maps is very ambiguous and depends on the developer needs and the map implementation...

For exemple if you compare two hashmaps in java: - You may want to just compare key/values are the same - You may also want to compare if the keys are ordered the same way - You may also want to compare if the remaining capacity is the same ... You can compare a lot of things!

What such a tool would do when comparing 2 different map implementations such that: - One map allow null keys - The other throw runtime exception on map2.get(null)

You'd better to implement your own solution according to what you really need to do, and i think you already got some answers above :)

How to execute cmd commands via Java

Every execution of exec spawns a new process with its own environment. So your second invocation is not connected to the first in any way. It will just change its own working directory and then exit (i.e. it's effectively a no-op).

If you want to compose requests, you'll need to do this within a single call to exec. Bash allows multiple commands to be specified on a single line if they're separated by semicolons; Windows CMD may allow the same, and if not there's always batch scripts.

As Piotr says, if this example is actually what you're trying to achieve, you can perform the same thing much more efficiently, effectively and platform-safely with the following:

String[] filenames = new java.io.File("C:/").list();

endforeach in loops?

Using foreach: ... endforeach; does not only make things readable, it also makes least load for memory as introduced in PHP docs So for big apps, receiving many users this would be the best solution

How do I add a foreign key to an existing SQLite table?

In case somebody else needs info on SQLiteStudio, you can easily do it form it's GUI.

Double-click on the column and double-click foreign key row, then tick foreign key and click configure. You can add the reference column, then click OK in every window.

Finally click on the green tick to commit changes in the structure.

BE AWARE THAT THESE STEPS CREATE SQL SCRIPTS THAT DELETES THE TABLE AND RECREATES IT!!

Backup your data from the database.

List all employee's names and their managers by manager name using an inner join

Select e.lastname as employee ,m.lastname as manager
  from employees e,employees m
 where e.managerid=m.employyid(+)

How to nicely format floating numbers to string without unnecessary decimal 0's

String s = String.valueof("your int variable");
while (g.endsWith("0") && g.contains(".")) {
    g = g.substring(0, g.length() - 1);
    if (g.endsWith("."))
    {
        g = g.substring(0, g.length() - 1);
    }
}

What is the difference between task and thread?

A task is something you want done.

A thread is one of the many possible workers which performs that task.

In .NET 4.0 terms, a Task represents an asynchronous operation. Thread(s) are used to complete that operation by breaking the work up into chunks and assigning to separate threads.

Exporting PDF with jspdf not rendering CSS

To remove black background only add background-color: white; to the style of

How to configure nginx to enable kinda 'file browser' mode?

All answers contain part of the answer. Let me try to combine all in one.

Quick setup "file browser" mode on freshly installed nginx server:

  1. Edit default config for nginx:

    sudo vim /etc/nginx/sites-available/default
    
  2. Add following to config section:

    location /myfolder {  # new url path
       alias /home/username/myfolder/; # directory to list
       autoindex on;
    }
    
  3. Create folder and sample file there:

    mkdir -p /home/username/myfolder/
    ls -la >/home/username/myfolder/mytestfile.txt
    
  4. Restart nginx

    sudo systemctl restart nginx
    
  5. Check result: http://<your-server-ip>/myfolder for example http://192.168.0.10/myfolder/

enter image description here

Retrieving the output of subprocess.call()

I have the following solution. It captures the exit code, the stdout, and the stderr too of the executed external command:

import shlex
from subprocess import Popen, PIPE

def get_exitcode_stdout_stderr(cmd):
    """
    Execute the external command and get its exitcode, stdout and stderr.
    """
    args = shlex.split(cmd)

    proc = Popen(args, stdout=PIPE, stderr=PIPE)
    out, err = proc.communicate()
    exitcode = proc.returncode
    #
    return exitcode, out, err

cmd = "..."  # arbitrary external command, e.g. "python mytest.py"
exitcode, out, err = get_exitcode_stdout_stderr(cmd)

I also have a blog post on it here.

Edit: the solution was updated to a newer one that doesn't need to write to temp. files.

Set the table column width constant regardless of the amount of text in its cells?

Just add <div> tag inside <td> or <th> define width inside <div>. This will help you. Nothing else works.

eg.

<td><div style="width: 50px" >...............</div></td>

How can you create multiple cursors in Visual Studio Code

Alt + Command + Shift will add a cursor to the next instance of what you've selected. E.g. a variable or function name

How do I check that a Java String is not all whitespaces?

While personally I would be preferring !str.isBlank(), as others already suggested (or str -> !str.isBlank() as a Predicate), a more modern and efficient version of the str.trim() approach mentioned above, would be using str.strip() - considering nulls as "whitespace":

if (str != null && str.strip().length() > 0) {...}

For example as Predicate, for use with streams, e. g. in a unit test:

@Test
public void anyNonEmptyStrippedTest() {
    String[] strings = null;
    Predicate<String> isNonEmptyStripped = str -> str != null && str.strip().length() > 0;
    assertTrue(Optional.ofNullable(strings).map(arr -> Stream.of(arr).noneMatch(isNonEmptyStripped)).orElse(true));
    strings = new String[] { null, "", " ", "\\n", "\\t", "\\r" };
    assertTrue(Optional.ofNullable(strings).map(arr -> Stream.of(arr).anyMatch(isNonEmptyStripped)).orElse(true));
    strings = new String[] { null, "", " ", "\\n", "\\t", "\\r", "test" };
}

What's the difference between F5 refresh and Shift+F5 in Google Chrome browser?

The difference is not just for Chrome but for most of the web browsers.

enter image description here

F5 refreshes the web page and often reloads the same page from the cached contents of the web browser. However, reloading from cache every time is not guaranteed and it also depends upon the cache expiry.

Shift + F5 forces the web browser to ignore its cached contents and retrieve a fresh copy of the web page into the browser.

Shift + F5 guarantees loading of latest contents of the web page.
However, depending upon the size of page, it is usually slower than F5.

You may want to refer to: What requests do browsers' "F5" and "Ctrl + F5" refreshes generate?

Difference between `npm start` & `node app.js`, when starting app?

From the man page, npm start:

runs a package's "start" script, if one was provided. If no version is specified, then it starts the "active" version.

Admittedly, that description is completely unhelpful, and that's all it says. At least it's more documented than socket.io.

Anyhow, what really happens is that npm looks in your package.json file, and if you have something like

"scripts": { "start": "coffee server.coffee" }

then it will do that. If npm can't find your start script, it defaults to:

node server.js

 

CSS3 Transform Skew One Side

Maybe you want to use CSS "clip-path" (Works with transparency and background)

"clip-path" reference: https://developer.mozilla.org/en-US/docs/Web/CSS/clip-path

Generator: http://bennettfeely.com/clippy/

Example:

_x000D_
_x000D_
/* With percent */_x000D_
.element-percent {_x000D_
  background: red;_x000D_
  width: 150px;_x000D_
  height: 48px;_x000D_
  display: inline-block;_x000D_
  _x000D_
  clip-path: polygon(0 0, 100% 0%, 75% 100%, 0% 100%);_x000D_
}_x000D_
_x000D_
/* With pixel */_x000D_
.element-pixel {_x000D_
  background: blue;_x000D_
  width: 150px;_x000D_
  height: 48px;_x000D_
  display: inline-block;_x000D_
  _x000D_
  clip-path: polygon(0 0, 100% 0%, calc(100% - 32px) 100%, 0% 100%);_x000D_
}_x000D_
_x000D_
/* With background */_x000D_
.element-background {_x000D_
  background: url(https://images.pexels.com/photos/170811/pexels-photo-170811.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260) no-repeat center/cover;_x000D_
  width: 150px;_x000D_
  height: 48px;_x000D_
  display: inline-block;_x000D_
  _x000D_
  clip-path: polygon(0 0, 100% 0%, calc(100% - 32px) 100%, 0% 100%);_x000D_
}
_x000D_
<div class="element-percent"></div>_x000D_
_x000D_
<br />_x000D_
_x000D_
<div class="element-pixel"></div>_x000D_
_x000D_
<br />_x000D_
_x000D_
<div class="element-background"></div>
_x000D_
_x000D_
_x000D_

MySQL maximum memory usage

MySQL's maximum memory usage very much depends on hardware, your settings and the database itself.

Hardware

The hardware is the obvious part. The more RAM the merrier, faster disks ftw. Don't believe those monthly or weekly news letters though. MySQL doesn't scale linear - not even on Oracle hardware. It's a little trickier than that.

The bottom line is: there is no general rule of thumb for what is recommend for your MySQL setup. It all depends on the current usage or the projections.

Settings & database

MySQL offers countless variables and switches to optimize its behavior. If you run into issues, you really need to sit down and read the (f'ing) manual.

As for the database -- a few important constraints:

  • table engine (InnoDB, MyISAM, ...)
  • size
  • indices
  • usage

Most MySQL tips on stackoverflow will tell you about 5-8 so called important settings. First off, not all of them matter - e.g. allocating a lot of resources to InnoDB and not using InnoDB doesn't make a lot of sense because those resources are wasted.

Or - a lot of people suggest to up the max_connection variable -- well, little do they know it also implies that MySQL will allocate more resources to cater those max_connections -- if ever needed. The more obvious solution might be to close the database connection in your DBAL or to lower the wait_timeout to free those threads.

If you catch my drift -- there's really a lot, lot to read up on and learn.

Engines

Table engines are a pretty important decision, many people forget about those early on and then suddenly find themselves fighting with a 30 GB sized MyISAM table which locks up and blocks their entire application.

I don't mean to say MyISAM sucks, but InnoDB can be tweaked to respond almost or nearly as fast as MyISAM and offers such thing as row-locking on UPDATE whereas MyISAM locks the entire table when it is written to.

If you're at liberty to run MySQL on your own infrastructure, you might also want to check out the percona server because among including a lot of contributions from companies like Facebook and Google (they know fast), it also includes Percona's own drop-in replacement for InnoDB, called XtraDB.

See my gist for percona-server (and -client) setup (on Ubuntu): http://gist.github.com/637669

Size

Database size is very, very important -- believe it or not, most people on the Intarwebs have never handled a large and write intense MySQL setup but those do really exist. Some people will troll and say something like, "Use PostgreSQL!!!111", but let's ignore them for now.

The bottom line is: judging from the size, decision about the hardware are to be made. You can't really make a 80 GB database run fast on 1 GB of RAM.

Indices

It's not: the more, the merrier. Only indices needed are to be set and usage has to be checked with EXPLAIN. Add to that that MySQL's EXPLAIN is really limited, but it's a start.

Suggested configurations

About these my-large.cnf and my-medium.cnf files -- I don't even know who those were written for. Roll your own.

Tuning primer

A great start is the tuning primer. It's a bash script (hint: you'll need linux) which takes the output of SHOW VARIABLES and SHOW STATUS and wraps it into hopefully useful recommendation. If your server has ran some time, the recommendation will be better since there will be data to base them on.

The tuning primer is not a magic sauce though. You should still read up on all the variables it suggests to change.

Reading

I really like to recommend the mysqlperformanceblog. It's a great resource for all kinds of MySQL-related tips. And it's not just MySQL, they also know a lot about the right hardware or recommend setups for AWS, etc.. These guys have years and years of experience.

Another great resource is planet-mysql, of course.

Indent List in HTML and CSS

_x000D_
_x000D_
li {
  padding-left: 30px;
}
_x000D_
<p>Some text to show left edge of container.<p>
<ul>
  <li>List item</li>
</ul>
_x000D_
_x000D_
_x000D_ The above will add 30px of space between the bullet or number and your text.

_x000D_
_x000D_
li {
  margin-left: 30px;
}
_x000D_
<p>Some text to show left edge of container.<p>
<ul>
  <li>List item</li>
</ul>
_x000D_
_x000D_
_x000D_ The above will add 30px of space between the bullet or number and the left edge of the container.

How to set up a squid Proxy with basic username and password authentication?

Here's what I had to do to setup basic auth on Ubuntu 14.04 (didn't find a guide anywhere else)

Basic squid conf

/etc/squid3/squid.conf instead of the super bloated default config file

auth_param basic program /usr/lib/squid3/basic_ncsa_auth /etc/squid3/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

# Choose the port you want. Below we set it to default 3128.
http_port 3128

Please note the basic_ncsa_auth program instead of the old ncsa_auth

squid 2.x

For squid 2.x you need to edit /etc/squid/squid.conf file and place:

auth_param basic program /usr/lib/squid/digest_pw_auth /etc/squid/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

Setting up a user

sudo htpasswd -c /etc/squid3/passwords username_you_like

and enter a password twice for the chosen username then

sudo service squid3 restart

squid 2.x

sudo htpasswd -c /etc/squid/passwords username_you_like

and enter a password twice for the chosen username then

sudo service squid restart

htdigest vs htpasswd

For the many people that asked me: the 2 tools produce different file formats:

  • htdigest stores the password in plain text.
  • htpasswd stores the password hashed (various hashing algos are available)

Despite this difference in format basic_ncsa_auth will still be able to parse a password file generated with htdigest. Hence you can alternatively use:

sudo htdigest -c /etc/squid3/passwords realm_you_like username_you_like

Beware that this approach is empirical, undocumented and may not be supported by future versions of Squid.

On Ubuntu 14.04 htdigest and htpasswd are both available in the [apache2-utils][1] package.

MacOS

Similar as above applies, but file paths are different.

Install squid

brew install squid

Start squid service

brew services start squid

Squid config file is stored at /usr/local/etc/squid.conf.

Comment or remove following line:

http_access allow localnet

Then similar to linux config (but with updated paths) add this:

auth_param basic program /usr/local/Cellar/squid/4.8/libexec/basic_ncsa_auth /usr/local/etc/squid_passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

Note that path to basic_ncsa_auth may be different since it depends on installed version when using brew, you can verify this with ls /usr/local/Cellar/squid/. Also note that you should add the above just bellow the following section:

#
# INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS
#

Now generate yourself a user:password basic auth credential (note: htpasswd and htdigest are also both available on MacOS)

htpasswd -c /usr/local/etc/squid_passwords username_you_like

Restart the squid service

brew services restart squid

How to iterate over the file in python

Just use for x in f: ..., this gives you line after line, is much shorter and readable (partly because it automatically stops when the file ends) and also saves you the rstrip call because the trailing newline is already stipped.

The error is caused by the exit condition, which can never be true: Even if the file is exhausted, readline will return an empty string, not None. Also note that you could still run into trouble with empty lines, e.g. at the end of the file. Adding if line.strip() == "": continue makes the code ignore blank lines, which is propably a good thing anyway.

Initialize 2D array

You can use for loop if you really want to.

char table[][] table = new char[row][col];
for(int i = 0; i < row * col ; ++i){
     table[i/row][i % col] = char('a' + (i+1));
}

or do what bhesh said.

Add custom headers to WebView resource requests - android

You should be able to control all your headers by skipping loadUrl and writing your own loadPage using Java's HttpURLConnection. Then use the webview's loadData to display the response.

There is no access to the headers which Google provides. They are in a JNI call, deep in the WebView source.

Size of character ('a') in C/C++

In C the type of character literals are int and char in C++. This is in C++ required to support function overloading. See this example:

void foo(char c)
{
    puts("char");
}
void foo(int i)
{
    puts("int");
}
int main()
{
    foo('i');
    return 0;
}

Output:

char

Struct Constructor in C++?

Syntax is as same as of class in C++. If you aware of creating constructor in c++ then it is same in struct.

struct Date
{
    int day;

    Date(int d)
    {
        day = d;
    }

    void printDay()
    {
        cout << "day " << day << endl;
    }
};

Struct can have all things as class in c++. As earlier said difference is only that by default C++ member have private access but in struct it is public.But as per programming consideration Use the struct keyword for data-only structures. Use the class keyword for objects that have both data and functions.

Return index of highest value in an array

Function taken from http://www.php.net/manual/en/function.max.php

function max_key($array) {
    foreach ($array as $key => $val) {
        if ($val == max($array)) return $key; 
    }
}

$arr = array (
    '11' => 14,
    '10' => 9,
    '12' => 7,
    '13' => 7,
    '14' => 4,
    '15' => 6
);

die(var_dump(max_key($arr)));

Works like a charm

Request is not available in this context

You can get around the problem without switching to classic mode and still use Application_Start

public class Global : HttpApplication
{
   private static HttpRequest initialRequest;

   static Global()
   {
      initialRequest = HttpContext.Current.Request;       
   }

   void Application_Start(object sender, EventArgs e)
   {
      //access the initial request here
   }

For some reason, the static type is created with a request in its HTTPContext, allowing you to store it and reuse it immediately in the Application_Start event

How to list all installed packages and their versions in Python?

If you want to get information about your installed python distributions and don't want to use your cmd console or terminal for it, but rather through python code, you can use the following code (tested with python 3.4):

import pip #needed to use the pip functions
for i in pip.get_installed_distributions(local_only=True):
    print(i)

The pip.get_installed_distributions(local_only=True) function-call returns an iterable and because of the for-loop and the print function the elements contained in the iterable are printed out separated by new line characters (\n). The result will (depending on your installed distributions) look something like this:

cycler 0.9.0
decorator 4.0.4
ipykernel 4.1.0
ipython 4.0.0
ipython-genutils 0.1.0
ipywidgets 4.0.3
Jinja2 2.8
jsonschema 2.5.1
jupyter 1.0.0
jupyter-client 4.1.1
#... and so on...

How do I deal with special characters like \^$.?*|+()[{ in my regex?

I think the easiest way to match the characters like

\^$.?*|+()[

are using character classes from within R. Consider the following to clean column headers from a data file, which could contain spaces, and punctuation characters:

> library(stringr)
> colnames(order_table) <- str_replace_all(colnames(order_table),"[:punct:]|[:space:]","")

This approach allows us to string character classes to match punctation characters, in addition to whitespace characters, something you would normally have to escape with \\ to detect. You can learn more about the character classes at this cheatsheet below, and you can also type in ?regexp to see more info about this.

https://www.rstudio.com/wp-content/uploads/2016/09/RegExCheatsheet.pdf

How do I print bold text in Python?

Install the termcolor module

sudo pip install termcolor

and then try this for colored text

from termcolor import colored
print colored('Hello', 'green')

or this for bold text:

from termcolor import colored
print colored('Hello', attrs=['bold'])

In Python 3 you can alternatively use cprint as a drop-in replacement for the built-in print, with the optional second parameter for colors or the attrs parameter for bold (and other attributes such as underline) in addition to the normal named print arguments such as file or end.

import sys
from termcolor import cprint
cprint('Hello', 'green', attrs=['bold'], file=sys.stderr)

Full disclosure, this answer is heavily based on Olu Smith's answer and was intended as an edit, which would have reduced the noise on this page considerably but because of some reviewers' misguided concept of what an edit is supposed to be, I am now forced to make this a separate answer.

Check if string doesn't contain another string

Or alternatively, you could use this:

WHERE CHARINDEX(N'Apples', someColumn) = 0

Not sure which one performs better - you gotta test it! :-)

Marc

UPDATE: the performance seems to be pretty much on a par with the other solution (WHERE someColumn NOT LIKE '%Apples%') - so it's really just a question of your personal preference.

How can I access my localhost from my Android device?

USB doesn't provide network to mobile device.

If both your desktop and phone are connected to the same WiFi (or any other local network), then use your desktop IP address assigned by the router (not localhost and not 127.0.0.1).

To find out the IP address of your desktop:

  • type into the command line ipconfig (Windows) or ifconfig (Unix)
    • on Linux the one-liner ifconfig | grep "inet " | grep -v 127.0.0.1 will yield only the important stuff
    • there's a bunch of suggestions on how to have a similar output on Windows
  • there's going to be a bunch of IP's
  • try all of them (except the forementioned localhost and 127.0.0.1)

If your phone is connected to the mobile network, then things are going to be harder.

Either go hardcore:

  • first find out your router external IP address (https://www.google.de/search?q=myip)
  • then, on the router, forward some port to <your desktop IP>:<server port number>
  • finally use the external IP address and forwarded port

Otherwise use something like xip.io or ngrok.

NOTE: The ifconfig command has been deprecated and thus missing by default on Debian Linux, starting from Debian stretch. The new and recommended alternative for examining a network configuration on Debian Linux is ip command. For example to use ip command to display a network configuration run the following:

ip address

The above ip command can be abbreviated to:

ip a

If you still prefer to use ifconfig as part of your daily sys admin routine, you can easily install it as part of the net-tools package.

apt-get install net-tools

Reference is here

What is the default root pasword for MySQL 5.7

After you installed MySQL-community-server 5.7 from fresh on linux, you will need to find the temporary password from /var/log/mysqld.log to login as root.

  1. grep 'temporary password' /var/log/mysqld.log
  2. Run mysql_secure_installation to change new password

ref: http://dev.mysql.com/doc/refman/5.7/en/linux-installation-yum-repo.html

ng-if check if array is empty

post.capabilities.items will still be defined because it's an empty array, if you check post.capabilities.items.length it should work fine because 0 is falsy.