Programs & Examples On #Information schema

The information schema is a set of views providing metadata for objects in relational databases: tables, views, columns, stored procedures, accounts etc.

PostgreSQL query to list all table names?

If you want list of database

SELECT datname FROM pg_database WHERE datistemplate = false;

If you want list of tables from current pg installation of all databases

SELECT table_schema,table_name FROM information_schema.tables
ORDER BY table_schema,table_name;

List all tables in postgresql information_schema

The "\z" COMMAND is also a good way to list tables when inside the interactive psql session.

eg.

# psql -d mcdb -U admin -p 5555
mcdb=# /z
                           Access privileges for database "mcdb"
 Schema |              Name              |   Type   |           Access privileges
--------+--------------------------------+----------+---------------------------------------
 public | activities                     | table    |
 public | activities_id_seq              | sequence |
 public | activities_users_mapping       | table    |
[..]
 public | v_schedules_2                  | view     | {admin=arwdxt/admin,viewuser=r/admin}
 public | v_systems                      | view     |
 public | vapp_backups                   | table    |
 public | vm_client                      | table    |
 public | vm_datastore                   | table    |
 public | vmentity_hle_map               | table    |
(148 rows)

How to find all the tables in MySQL with specific column names in them?

select distinct table_name 
from information_schema.columns 
where column_name in ('ColumnA') 
and table_schema='YourDatabase';
and table_name in 
(
 select distinct table_name 
 from information_schema.columns 
 where column_name in ('ColumnB')
 and table_schema='YourDatabase';
);

That ^^ will get the tables with ColumnA AND ColumnB instead of ColumnA OR ColumnB like the accepted answer

How to check if a Constraint exists in Sql server?

IF EXISTS(SELECT 1 FROM sys.foreign_keys WHERE parent_object_id = OBJECT_ID(N'dbo.TableName'))
 BEGIN 
ALTER TABLE TableName DROP CONSTRAINT CONSTRAINTNAME 
END 

How do I find a default constraint using INFORMATION_SCHEMA?

Necromancing.
If you only need to check if a default-constraint exists
(default-constraint(s) may have different name in poorly-managed DBs),
use INFORMATION_SCHEMA.COLUMNS (column_default):

IF NOT EXISTS(
    SELECT * FROM INFORMATION_SCHEMA.COLUMNS
    WHERE (1=1) 
    AND TABLE_SCHEMA = 'dbo' 
    AND TABLE_NAME = 'T_VWS_PdfBibliothek' 
    AND COLUMN_NAME = 'PB_Text'
    AND COLUMN_DEFAULT IS NOT NULL  
)
BEGIN 
    EXECUTE('ALTER TABLE dbo.T_VWS_PdfBibliothek 
                ADD CONSTRAINT DF_T_VWS_PdfBibliothek_PB_Text DEFAULT (N''image'') FOR PB_Text; 
    '); 
END 

If you want to check by the constraint-name only:

-- Alternative way: 
IF OBJECT_ID('DF_CONSTRAINT_NAME', 'D') IS NOT NULL 
BEGIN
    -- constraint exists, deal with it.
END 

And last but not least, you can just create a view called
INFORMATION_SCHEMA.DEFAULT_CONSTRAINTS:

CREATE VIEW INFORMATION_SCHEMA.DEFAULT_CONSTRAINTS 
AS 
SELECT 
     DB_NAME() AS CONSTRAINT_CATALOG 
    ,csch.name AS CONSTRAINT_SCHEMA
    ,dc.name AS CONSTRAINT_NAME 
    ,DB_NAME() AS TABLE_CATALOG 
    ,sch.name AS TABLE_SCHEMA 
    ,syst.name AS TABLE_NAME 
    ,sysc.name AS COLUMN_NAME 
    ,COLUMNPROPERTY(sysc.object_id, sysc.name, 'ordinal') AS ORDINAL_POSITION 
    ,dc.type_desc AS CONSTRAINT_TYPE 
    ,dc.definition AS COLUMN_DEFAULT 

    -- ,dc.create_date 
    -- ,dc.modify_date 
FROM sys.columns AS sysc -- 46918 / 3892 with inner joins + where 
-- FROM sys.all_columns AS sysc -- 55429 / 3892 with inner joins + where 

INNER JOIN sys.tables AS syst 
    ON syst.object_id = sysc.object_id 

INNER JOIN sys.schemas AS sch
    ON sch.schema_id = syst.schema_id 

INNER JOIN sys.default_constraints AS dc 
    ON sysc.default_object_id = dc.object_id

INNER JOIN sys.schemas AS csch
    ON csch.schema_id = dc.schema_id 

WHERE (1=1) 
AND dc.is_ms_shipped = 0 

/*
WHERE (1=1) 
AND sch.name = 'dbo'
AND syst.name = 'tablename'
AND sysc.name = 'columnname'
*/

How to check if a table exists in a given schema

It depends on what you want to test exactly.

Information schema?

To find "whether the table exists" (no matter who's asking), querying the information schema (information_schema.tables) is incorrect, strictly speaking, because (per documentation):

Only those tables and views are shown that the current user has access to (by way of being the owner or having some privilege).

The query provided by @kong can return FALSE, but the table can still exist. It answers the question:

How to check whether a table (or view) exists, and the current user has access to it?

SELECT EXISTS (
   SELECT FROM information_schema.tables 
   WHERE  table_schema = 'schema_name'
   AND    table_name   = 'table_name'
   );

The information schema is mainly useful to stay portable across major versions and across different RDBMS. But the implementation is slow, because Postgres has to use sophisticated views to comply to the standard (information_schema.tables is a rather simple example). And some information (like OIDs) gets lost in translation from the system catalogs - which actually carry all information.

System catalogs

Your question was:

How to check whether a table exists?

SELECT EXISTS (
   SELECT FROM pg_catalog.pg_class c
   JOIN   pg_catalog.pg_namespace n ON n.oid = c.relnamespace
   WHERE  n.nspname = 'schema_name'
   AND    c.relname = 'table_name'
   AND    c.relkind = 'r'    -- only tables
   );

Use the system catalogs pg_class and pg_namespace directly, which is also considerably faster. However, per documentation on pg_class:

The catalog pg_class catalogs tables and most everything else that has columns or is otherwise similar to a table. This includes indexes (but see also pg_index), sequences, views, materialized views, composite types, and TOAST tables;

For this particular question you can also use the system view pg_tables. A bit simpler and more portable across major Postgres versions (which is hardly of concern for this basic query):

SELECT EXISTS (
   SELECT FROM pg_tables
   WHERE  schemaname = 'schema_name'
   AND    tablename  = 'table_name'
   );

Identifiers have to be unique among all objects mentioned above. If you want to ask:

How to check whether a name for a table or similar object in a given schema is taken?

SELECT EXISTS (
   SELECT FROM pg_catalog.pg_class c
   JOIN   pg_catalog.pg_namespace n ON n.oid = c.relnamespace
   WHERE  n.nspname = 'schema_name'
   AND    c.relname = 'table_name'
   );

Alternative: cast to regclass

SELECT 'schema_name.table_name'::regclass

This raises an exception if the (optionally schema-qualified) table (or other object occupying that name) does not exist.

If you do not schema-qualify the table name, a cast to regclass defaults to the search_path and returns the OID for the first table found - or an exception if the table is in none of the listed schemas. Note that the system schemas pg_catalog and pg_temp (the schema for temporary objects of the current session) are automatically part of the search_path.

You can use that and catch a possible exception in a function. Example:

A query like above avoids possible exceptions and is therefore slightly faster.

to_regclass(rel_name) in Postgres 9.4+

Much simpler now:

SELECT to_regclass('schema_name.table_name');

Same as the cast, but it returns ...

... null rather than throwing an error if the name is not found

Creating a PDF from a RDLC Report in the Background

This is easy to do, you can render the report as a PDF, and save the resulting byte array as a PDF file on disk. To do this in the background, that's more a question of how your app is written. You can just spin up a new thread, or use a BackgroundWorker (if this is a WinForms app), etc. There, of course, may be multithreading issues to be aware of.

Warning[] warnings;
string[] streamids;
string mimeType;
string encoding;
string filenameExtension;

byte[] bytes = reportViewer.LocalReport.Render(
    "PDF", null, out mimeType, out encoding, out filenameExtension,
    out streamids, out warnings);

using (FileStream fs = new FileStream("output.pdf", FileMode.Create))
{
    fs.Write(bytes, 0, bytes.Length);
}

Fatal error: Class 'SoapClient' not found

On Centos 7.8 and PHP 7.3

yum install php-soap
service httpd restart

redirect while passing arguments

I found that none of the answers here applied to my specific use case, so I thought I would share my solution.

I was looking to redirect an unauthentciated user to public version of an app page with any possible URL params. Example:

/app/4903294/my-great-car?email=coolguy%40gmail.com to

/public/4903294/my-great-car?email=coolguy%40gmail.com

Here's the solution that worked for me.

return redirect(url_for('app.vehicle', vid=vid, year_make_model=year_make_model, **request.args))

Hope this helps someone!

Adding value to input field with jQuery

You can do it as below.

$(this).prev('input').val("hello world");

Live Demo

Simplest way to restart service on a remote computer

There will be so many instances where the service will go in to "stop pending".The Operating system will complain that it was "Not able to stop the service xyz." In case you want to make absolutely sure the service is restarted you should kill the process instead. You can do that by doing the following in a bat file

taskkill /F /IM processname.exe
timeout 20
sc start servicename

To find out which process is associated with your service, go to task manager--> Services tab-->Right Click on your Service--> Go to process.

Note that this should be a work around until you figure out why your service had to be restarted in the first place. You should look for memory leaks, infinite loops and other such conditions for your service to have become unresponsive.

How to check if a list is empty in Python?

if not myList:
  print "Nothing here"

How to increase font size in NeatBeans IDE?

In OS X, Netbeans 8.0

  1. Use Command + , to open the options
  2. Select Fonts & Colors tab
  3. Click the button in the Font section (button is next to the Font textbox)
  4. Change the Font, style and size as needed

enter image description here

How to center HTML5 Videos?

I found this page while trying to center align a pair of videos. So, if I enclose both videos in a center div (which I've called central), the margin trick works, but the width is important (2 videos at 400 + padding etc)

<div class=central>
    <video id="vid1" width="400" controls>
        <source src="Carnival01.mp4" type="video/mp4">
    </video> 

    <video id="vid2" width="400" controls>
        <source src="Carnival02.mp4" type="video/mp4">
    </video>
</div>

<style>
div.central { 
  margin: 0 auto;
  width: 880px; <!--this value must be larger than both videos + padding etc-->
}
</style>

Worked for me!

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

First of all, a caveat. Why do you want to use telnet? telnet is an old protocol, unsafe and impractical for remote access. It's been (almost)totally replaced by ssh.

To answer your questions, it depends. It depends on the telnet client you use. If you use microsoft telnet, you can't. Microsoft telnet does not have any mean to send commands from a batch file or a command line.

How to view kafka message

I work for a company with hundreds of developers who obviously need to check Kafka messages on a regular basis. Employees come and go and therefore we want to avoid the setup (dedicated SASL credentials, certificates, ACLs, ...) for each new employee.

Our platform teams operate a deployment of Kowl (https://github.com/cloudhut/kowl) so that everyone can access it without going through the usual setup. We also use it when developing locally using a docker-compose file.

Kowl Messages List

How to find duplicate records in PostgreSQL

From "Find duplicate rows with PostgreSQL" here's smart solution:

select * from (
  SELECT id,
  ROW_NUMBER() OVER(PARTITION BY column1, column2 ORDER BY id asc) AS Row
  FROM tbl
) dups
where 
dups.Row > 1

How do I change the owner of a SQL Server database?

To change database owner:

ALTER AUTHORIZATION ON DATABASE::YourDatabaseName TO sa

As of SQL Server 2014 you can still use sp_changedbowner as well, even though Microsoft promised to remove it in the "future" version after SQL Server 2012. They removed it from SQL Server 2014 BOL though.

Join vs. sub-query

Taken from the MySQL manual (13.2.10.11 Rewriting Subqueries as Joins):

A LEFT [OUTER] JOIN can be faster than an equivalent subquery because the server might be able to optimize it better—a fact that is not specific to MySQL Server alone.

So subqueries can be slower than LEFT [OUTER] JOIN, but in my opinion their strength is slightly higher readability.

How to simulate a click with JavaScript?

document.getElementById("#elment").click()

Simply select the element from the DOM. The node has a click function, which you can call.

How to run regasm.exe from command line other than Visual Studio command prompt?

Like Cheeso said:

You don't need the directory on your path. You could put it on your path, but you don't NEED to do that. If you are calling regasm rarely, or calling it from a batch file, you may find it is simpler to just invoke regasm via the fully-qualified pathname on the exe, eg:

%SystemRoot%\Microsoft.NET\Framework\v2.0.50727\regasm.exe MyAssembly.dll

Setting Environment Variables for Node to retrieve

Came across a nice tool for doing this.

node-env-file

Parses and loads environment files (containing ENV variable exports) into Node.js environment, i.e. process.env - Uses this style:

.env

# some env variables

FOO=foo1
BAR=bar1
BAZ=1
QUX=
# QUUX=

Enterprise app deployment doesn't work on iOS 7.1

I can confirm it works, But You have to put html AND plist on dropbox. It works also for non-enterprise OTA, i.e. You want to share app with your dev. team.

I did:

a) on my site I made a page with this link:

.. href="https://dl.dropboxusercontent.com/u//(your DB id)/ipa.html">MyApp

b) on DropBox I wrote another HTML page:

.. https://dl.dropboxusercontent.com/u/(your DB id)/MyApp.plist"> Tap to Install MyApp

c) moved plist on DropBox but leaving it to POINT to my old server (no https)

Focusable EditText inside ListView

This saved my life--->

  1. set this line

    ListView.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);

  2. Then in your manifest in activity tag type this-->

    <activity android:windowSoftInputMode="adjustPan">

Your usual intent

How to Correctly Check if a Process is running and Stop it

@jmp242 - the generic System.Object type does not contain the CloseMainWindow method, but statically casting the System.Diagnostics.Process type when collecting the ProcessList variable works for me. Updated code (from this answer) with this casting (and looping changed to use ForEach-Object) is below.

function Stop-Processes {
    param(
        [parameter(Mandatory=$true)] $processName,
                                     $timeout = 5
    )
    [System.Diagnostics.Process[]]$processList = Get-Process $processName -ErrorAction SilentlyContinue

    ForEach ($Process in $processList) {
        # Try gracefully first
        $Process.CloseMainWindow() | Out-Null
    }

    # Check the 'HasExited' property for each process
    for ($i = 0 ; $i -le $timeout; $i++) {
        $AllHaveExited = $True
        $processList | ForEach-Object {
            If (-NOT $_.HasExited) {
                $AllHaveExited = $False
            }                    
        }
        If ($AllHaveExited -eq $true){
            Return
        }
        Start-Sleep 1
    }
    # If graceful close has failed, loop through 'Stop-Process'
    $processList | ForEach-Object {
        If (Get-Process -ID $_.ID -ErrorAction SilentlyContinue) {
            Stop-Process -Id $_.ID -Force -Verbose
        }
    }
}

Is generator.next() visible in Python 3?

If your code must run under Python2 and Python3, use the 2to3 six library like this:

import six

six.next(g)  # on PY2K: 'g.next()' and onPY3K: 'next(g)'

Nested jQuery.each() - continue/break

return true not work

return false working

found = false;
query = "foo";

$('.items').each(function()
{
  if($(this).text() == query)
  {
    found = true;
    return false;
  }
});

Difference between array_push() and $array[] =

array_push — Push one or more elements onto the end of array

Take note of the words "one or more elements onto the end" to do that using $arr[] you would have to get the max size of the array

How to use *ngIf else?

Here's some nice and clean syntax on Angular's NgIf and using the else statement. In short, you will declare an ElementRef on an element and then reference it in the else block:

<div *ngIf="isLoggedIn; else loggedOut">
   Welcome back, friend.
</div>

<ng-template #loggedOut>
  Please friend, login.
</ng-template>

I've taken this example from NgIf, Else, Then which I found to be really well explained.

It also demonstrates using the <ng-template> syntax:

<ng-template [ngIf]="isLoggedIn" [ngIfElse]="loggedOut">
  <div>
    Welcome back, friend.
  </div>
</ng-template>

<ng-template #loggedOut>
  <div>
    Please friend, login.
  </div>
</ng-template>

And also using <ng-container> if that's what you're after:

<ng-container
  *ngIf="isLoggedIn; then loggedIn; else loggedOut">
</ng-container>

<ng-template #loggedIn>
  <div>
    Welcome back, friend.
  </div>
</ng-template>
<ng-template #loggedOut>
  <div>
    Please friend, login.
  </div>
</ng-template>

Source is taken from here on Angular's NgIf and Else syntax. I hope this helped! Enjoy.

How to remove a TFS Workspace Mapping?

I ran into the same problem, and was able to fix it by manually deleting all the files in the TFS cache, located here:

%LocalAppData%\Microsoft\Team Foundation\3.0\Cache

or 4.0, 5.0, etc.

alternative to "!is.null()" in R

The shiny package provides the convenient functions validate() and need() for checking that variables are both available and valid. need() evaluates an expression. If the expression is not valid, then an error message is returned. If the expression is valid, NULL is returned. One can use this to check if a variable is valid. See ?need for more information.

I suggest defining a function like this:

is.valid <- function(x) {
  require(shiny)
  is.null(need(x, message = FALSE))  
}

This function is.valid() will return FALSE if x is FALSE, NULL, NA, NaN, an empty string "", an empty atomic vector, a vector containing only missing values, a logical vector containing only FALSE, or an object of class try-error. In all other cases, it returns TRUE.

That means, need() (and is.valid()) covers a really broad range of failure cases. Instead of writing:

if (!is.null(x) && !is.na(x) && !is.nan(x)) {
  ...
}

one can write simply:

if (is.valid(x)) {
  ...
}

With the check for class try-error, it can even be used in conjunction with a try() block to silently catch errors: (see https://csgillespie.github.io/efficientR/programming.html#communicating-with-the-user)

bad = try(1 + "1", silent = TRUE)
if (is.valid(bad)) {
  ...
}

Submit two forms with one button

if you want to submit two forms with one button you need to do this:

1- use setTimeout()

2- allow show pop up

<script>
function myFunction() {
setTimeout(function(){ document.getElementById("form1").submit();}, 3000);   
setTimeout(function(){ document.getElementById("form2").submit();}, 6000);   
}
</script>
<form  target="_blank" id="form1">
<input type="text">
<input type="submit">
</form>
<form target="_blank" id="form2">
<input type="text">
<input type="submit">
</form>

javascript doesn't submit two forms at the same time. we submit two forms with one button not at the same time but after secounds.

edit: when we use this code, browser doesn't allow pop up.
if you use this code for your software like me just set browser for show pop up but if you use it in designing site, browser is a barrier and code doesn't run.

How can I declare and use Boolean variables in a shell script?

My receipe to (my own) idiocy:

# setting ----------------
commonMode=false
if [[ $something == 'COMMON' ]]; then
    commonMode=true
fi

# using ----------------
if $commonMode; then
    echo 'YES, Common Mode'
else
    echo 'NO, no Common Mode'
fi

$commonMode && echo 'commonMode is ON  ++++++'
$commonMode || echo 'commonMode is OFF xxxxxx'

How to solve "Connection reset by peer: socket write error"?

I've got the same exception and in my case the problem was in a renegotiation procecess. In fact my client closed a connection when the server tried to change a cipher suite. After digging it appears that in the jdk 1.6 update 22 renegotiation process is disabled by default. If your security constraints can effort this, try to enable the unsecure renegotiation by setting the sun.security.ssl.allowUnsafeRenegotiation system property to true. Here is some information about the process:

Session renegotiation is a mechanism within the SSL protocol that allows the client or the server to trigger a new SSL handshake during an ongoing SSL communication. Renegotiation was initially designed as a mechanism to increase the security of an ongoing SSL channel, by triggering the renewal of the crypto keys used to secure that channel. However, this security measure isn't needed with modern cryptographic algorithms. Additionally, renegotiation can be used by a server to request a client certificate (in order to perform client authentication) when the client tries to access specific, protected resources on the server.

Additionally there is the excellent post about this issue in details and written in (IMHO) understandable language.

CSS :not(:last-child):after selector

Your example as written works perfectly in Chrome 11 for me. Perhaps your browser just doesn't support the :not() selector?

You may need to use JavaScript or similar to accomplish this cross-browser. jQuery implements :not() in its selector API.

Using BeautifulSoup to extract text without tags

Just loop through all the <strong> tags and use next_sibling to get what you want. Like this:

for strong_tag in soup.find_all('strong'):
    print(strong_tag.text, strong_tag.next_sibling)

Demo:

from bs4 import BeautifulSoup

html = '''
<p>
  <strong class="offender">YOB:</strong> 1987<br />
  <strong class="offender">RACE:</strong> WHITE<br />
  <strong class="offender">GENDER:</strong> FEMALE<br />
  <strong class="offender">HEIGHT:</strong> 5'05''<br />
  <strong class="offender">WEIGHT:</strong> 118<br />
  <strong class="offender">EYE COLOR:</strong> GREEN<br />
  <strong class="offender">HAIR COLOR:</strong> BROWN<br />
</p>
'''

soup = BeautifulSoup(html)

for strong_tag in soup.find_all('strong'):
    print(strong_tag.text, strong_tag.next_sibling)

This gives you:

YOB:  1987
RACE:  WHITE
GENDER:  FEMALE
HEIGHT:  5'05''
WEIGHT:  118
EYE COLOR:  GREEN
HAIR COLOR:  BROWN

JavaScript seconds to time string with format hh:mm:ss

Using the amazing moment.js library:

function humanizeDuration(input, units ) { 
  // units is a string with possible values of y, M, w, d, h, m, s, ms
  var duration = moment().startOf('day').add(units, input),
    format = "";

  if(duration.hour() > 0){ format += "H [hours] "; }

  if(duration.minute() > 0){ format += "m [minutes] "; }

  format += " s [seconds]";

  return duration.format(format);
}

This allows you to specify any duration be it hours, minutes, seconds, mills, and returns a human readable version.

Getting list of pixel values from PIL

I assume you are getting an error like.. TypeError: 'PixelAccess' object is not iterable...?

See the Image.load documentation for how to access pixels..

Basically, to get the list of pixels in an image, using PIL:

from PIL import Image
i = Image.open("myfile.png")

pixels = i.load() # this is not a list, nor is it list()'able
width, height = i.size

all_pixels = []
for x in range(width):
    for y in range(height):
        cpixel = pixels[x, y]
        all_pixels.append(cpixel)

That appends every pixel to the all_pixels - if the file is an RGB image (even if it only contains a black-and-white image) these will be a tuple, for example:

(255, 255, 255)

To convert the image to monochrome, you just average the three values - so, the last three lines of code would become..

cpixel = pixels[x, y]
bw_value = int(round(sum(cpixel) / float(len(cpixel))))
# the above could probably be bw_value = sum(cpixel)/len(cpixel)
all_pixels.append(bw_value)

Or to get the luminance (weighted average):

cpixel = pixels[x, y]
luma = (0.3 * cpixel[0]) + (0.59 * cpixel[1]) + (0.11 * cpixel[2])
all_pixels.append(luma)

Or pure 1-bit looking black and white:

cpixel = pixels[x, y]
if round(sum(cpixel)) / float(len(cpixel)) > 127:
    all_pixels.append(255)
else:
    all_pixels.append(0)

There is probably methods within PIL to do such RGB -> BW conversions quicker, but this works, and isn't particularly slow.

If you only want to perform calculations on each row, you could skip adding all the pixels to an intermediate list.. For example, to calculate the average value of each row:

from PIL import Image
i = Image.open("myfile.png")

pixels = i.load() # this is not a list
width, height = i.size
row_averages = []
for y in range(height):
    cur_row_ttl = 0
    for x in range(width):
        cur_pixel = pixels[x, y]
        cur_pixel_mono = sum(cur_pixel) / len(cur_pixel)
        cur_row_ttl += cur_pixel_mono

    cur_row_avg = cur_row_ttl / width
    row_averages.append(cur_row_avg)

print "Brighest row:",
print max(row_averages)

How to programmatically take a screenshot on Android?

Call this method, passing in the outer most ViewGroup that you want a screen shot of:

public Bitmap screenShot(View view) {
    Bitmap bitmap = Bitmap.createBitmap(view.getWidth(),
            view.getHeight(), Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    view.draw(canvas);
    return bitmap;
}

OS X Framework Library not loaded: 'Image not found'

For me this was the solution, after many hours of searching!!

For some reason, well into the development of a Swift 2.3 custom Framework, Xcode 8 had removed the DYLIB_INSTALL_NAME_BASE setting from the project.pbxproj file. A little walk into the Build Settings / Dynamic Library Install Name Base setting back to @rpath fixed it.

(from https://forums.developer.apple.com/thread/4687)

matplotlib: colorbars and its text labels

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import ListedColormap

#discrete color scheme
cMap = ListedColormap(['white', 'green', 'blue','red'])

#data
np.random.seed(42)
data = np.random.rand(4, 4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=cMap)

#legend
cbar = plt.colorbar(heatmap)

cbar.ax.get_yaxis().set_ticks([])
for j, lab in enumerate(['$0$','$1$','$2$','$>3$']):
    cbar.ax.text(.5, (2 * j + 1) / 8.0, lab, ha='center', va='center')
cbar.ax.get_yaxis().labelpad = 15
cbar.ax.set_ylabel('# of contacts', rotation=270)


# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False)
ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False)
ax.invert_yaxis()

#labels
column_labels = list('ABCD')
row_labels = list('WXYZ')
ax.set_xticklabels(column_labels, minor=False)
ax.set_yticklabels(row_labels, minor=False)

plt.show()

You were very close. Once you have a reference to the color bar axis, you can do what ever you want to it, including putting text labels in the middle. You might want to play with the formatting to make it more visible.

demo

What is the python "with" statement designed for?

In python generally “with” statement is used to open a file, process the data present in the file, and also to close the file without calling a close() method. “with” statement makes the exception handling simpler by providing cleanup activities.

General form of with:

with open(“file name”, “mode”) as file-var:
    processing statements

note: no need to close the file by calling close() upon file-var.close()

How to use Checkbox inside Select Option

The best plugin so far is Bootstrap Multiselect

<html xmlns="http://www.w3.org/1999/xhtml">
<head>

<title>jQuery Multi Select Dropdown with Checkboxes</title>

<link rel="stylesheet" href="css/bootstrap-3.1.1.min.css" type="text/css" />
<link rel="stylesheet" href="css/bootstrap-multiselect.css" type="text/css" />

<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript" src="js/bootstrap-3.1.1.min.js"></script>
<script type="text/javascript" src="js/bootstrap-multiselect.js"></script>

</head>

<body>

<form id="form1">

<div style="padding:20px">

<select id="chkveg" multiple="multiple">

    <option value="cheese">Cheese</option>
    <option value="tomatoes">Tomatoes</option>
    <option value="mozarella">Mozzarella</option>
    <option value="mushrooms">Mushrooms</option>
    <option value="pepperoni">Pepperoni</option>
    <option value="onions">Onions</option>

</select>

<br /><br />

<input type="button" id="btnget" value="Get Selected Values" />

<script type="text/javascript">

$(function() {

    $('#chkveg').multiselect({

        includeSelectAllOption: true
    });

    $('#btnget').click(function(){

        alert($('#chkveg').val());
    });
});

</script>

</div>

</form>

</body>
</html>

Here's the DEMO

_x000D_
_x000D_
$(function() {_x000D_
_x000D_
  $('#chkveg').multiselect({_x000D_
    includeSelectAllOption: true_x000D_
  });_x000D_
_x000D_
  $('#btnget').click(function() {_x000D_
    alert($('#chkveg').val());_x000D_
  });_x000D_
});
_x000D_
.multiselect-container>li>a>label {_x000D_
  padding: 4px 20px 3px 20px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://davidstutz.de/bootstrap-multiselect/dist/js/bootstrap-multiselect.js"></script>_x000D_
<link href="https://davidstutz.de/bootstrap-multiselect/docs/css/bootstrap-3.3.2.min.css" rel="stylesheet"/>_x000D_
<link href="https://davidstutz.de/bootstrap-multiselect/dist/css/bootstrap-multiselect.css" rel="stylesheet"/>_x000D_
<script src="https://davidstutz.de/bootstrap-multiselect/docs/js/bootstrap-3.3.2.min.js"></script>_x000D_
_x000D_
<form id="form1">_x000D_
  <div style="padding:20px">_x000D_
_x000D_
    <select id="chkveg" multiple="multiple">_x000D_
      <option value="cheese">Cheese</option>_x000D_
      <option value="tomatoes">Tomatoes</option>_x000D_
      <option value="mozarella">Mozzarella</option>_x000D_
      <option value="mushrooms">Mushrooms</option>_x000D_
      <option value="pepperoni">Pepperoni</option>_x000D_
      <option value="onions">Onions</option>_x000D_
    </select>_x000D_
    _x000D_
    <br /><br />_x000D_
_x000D_
    <input type="button" id="btnget" value="Get Selected Values" />_x000D_
  </div>_x000D_
</form>
_x000D_
_x000D_
_x000D_

How to access route, post, get etc. parameters in Zend Framework 2

The easisest way to get a posted json string, for example, is to read the contents of 'php://input' and then decode it. For example i had a simple Zend route:

'save-json' => array(
'type' => 'Zend\Mvc\Router\Http\Segment',
            'options' => array(
                'route'    => '/save-json/',
                'defaults' => array(
                    'controller' => 'CDB\Controller\Index',
                    'action'     => 'save-json',
                ),
            ),
        ),

and i wanted to post data to it using Angular's $http.post. The post was fine but the retrive method in Zend

$this->params()->fromPost('paramname'); 

didn't get anything in this case. So my solution was, after trying all kinds of methods like $_POST and the other methods stated above, to read from 'php://':

$content = file_get_contents('php://input');
print_r(json_decode($content));

I got my json array in the end. Hope this helps.

How to open new browser window on button click event?

You can use some code like this, you can adjust a height and width as per your need

    protected void button_Click(object sender, EventArgs e)
    {
        // open a pop up window at the center of the page.
        ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", "var Mleft = (screen.width/2)-(760/2);var Mtop = (screen.height/2)-(700/2);window.open( 'your_page.aspx', null, 'height=700,width=760,status=yes,toolbar=no,scrollbars=yes,menubar=no,location=no,top=\'+Mtop+\', left=\'+Mleft+\'' );", true);
    }

How do I get a file extension in PHP?

The simplest way to get file extension in PHP is to use PHP's built-in function pathinfo.

$file_ext = pathinfo('your_file_name_here', PATHINFO_EXTENSION);
echo ($file_ext); // The output should be the extension of the file e.g., png, gif, or html

CSV file written with Python has blank lines between each row

I'm writing this answer w.r.t. to python 3, as I've initially got the same problem.

I was supposed to get data from arduino using PySerial, and write them in a .csv file. Each reading in my case ended with '\r\n', so newline was always separating each line.

In my case, newline='' option didn't work. Because it showed some error like :

with open('op.csv', 'a',newline=' ') as csv_file:

ValueError: illegal newline value: ''

So it seemed that they don't accept omission of newline here.

Seeing one of the answers here only, I mentioned line terminator in the writer object, like,

writer = csv.writer(csv_file, delimiter=' ',lineterminator='\r')

and that worked for me for skipping the extra newlines.

Does Visual Studio Code have box select/multi-line edit?

On Windows it's holding down Alt while box selecting. Once you have your selection then attempt your edit.

How do I clear my Jenkins/Hudson build history?

If you want to clear the build history of MultiBranchProject (e.g. pipeline), go to your Jenkins home page ? Manage Jenkins ? Script Console and run the following script:

def projectName = "ProjectName"
def project = Jenkins.instance.getItem(projectName)
def jobs = project.getItems().each {
  def job = it
  job.getBuilds().each { it.delete() }
  job.nextBuildNumber = 1
  job.save()
}

The type 'string' must be a non-nullable type in order to use it as parameter T in the generic type or method 'System.Nullable<T>'

Please note that in upcoming version of C# which is 8, the answers are not true.

All the reference types are non-nullable by default and you can actually do the following:

public string? MyNullableString; 
this.MyNullableString = null; //Valid

However,

public string MyNonNullableString; 
this.MyNonNullableString = null; //Not Valid and you'll receive compiler warning. 

The important thing here is to show the intent of your code. If the "intent" is that the reference type can be null, then mark it so otherwise assigning null value to non-nullable would result in compiler warning.

More info

Assigning the output of a command to a variable

You can use a $ sign like:

OUTPUT=$(expression)

Django - limiting query results

Actually I think the LIMIT 10 would be issued to the database so slicing would not occur in Python but in the database.

See limiting-querysets for more information.

Bootstrap 3 modal vertical position center

This works for me:

.modal {
  text-align: center;
  padding: 0!important;
}

.modal:before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  margin-right: -4px;
}

.modal-dialog {
  display: inline-block;
  text-align: left;
  vertical-align: middle;
}

ASP.NET Identity reset password

I think Microsoft guide for ASP.NET Identity is a good start.

https://docs.microsoft.com/en-us/aspnet/identity/overview/features-api/account-confirmation-and-password-recovery-with-aspnet-identity

Note:

If you do not use AccountController and wan't to reset your password, use Request.GetOwinContext().GetUserManager<ApplicationUserManager>();. If you dont have the same OwinContext you need to create a new DataProtectorTokenProvider like the one OwinContext uses. By default look at App_Start -> IdentityConfig.cs. Should look something like new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));.

Could be created like this:

Without Owin:

[HttpGet]
[AllowAnonymous]
[Route("testReset")]
public IHttpActionResult TestReset()
{
    var db = new ApplicationDbContext();
    var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(db));
    var provider = new DpapiDataProtectionProvider("SampleAppName");
    manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(
        provider.Create("SampleTokenName"));

    var email = "[email protected]";

    var user = new ApplicationUser() { UserName = email, Email = email };

    var identityUser = manager.FindByEmail(email);

    if (identityUser == null)
    {
        manager.Create(user);
        identityUser = manager.FindByEmail(email);
    }

    var token = manager.GeneratePasswordResetToken(identityUser.Id);
    return Ok(HttpUtility.UrlEncode(token));
}

[HttpGet]
[AllowAnonymous]
[Route("testReset")]
public IHttpActionResult TestReset(string token)
{
    var db = new ApplicationDbContext();
    var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(db));
    var provider = new DpapiDataProtectionProvider("SampleAppName");
    manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(
        provider.Create("SampleTokenName"));
    var email = "[email protected]";
    var identityUser = manager.FindByEmail(email);
    var valid = Task.Run(() => manager.UserTokenProvider.ValidateAsync("ResetPassword", token, manager, identityUser)).Result;
    var result = manager.ResetPassword(identityUser.Id, token, "TestingTest1!");
    return Ok(result);
}

With Owin:

[HttpGet]
[AllowAnonymous]
[Route("testResetWithOwin")]
public IHttpActionResult TestResetWithOwin()
{
    var manager = Request.GetOwinContext().GetUserManager<ApplicationUserManager>();

    var email = "[email protected]";

    var user = new ApplicationUser() { UserName = email, Email = email };

    var identityUser = manager.FindByEmail(email);

    if (identityUser == null)
    {
        manager.Create(user);
        identityUser = manager.FindByEmail(email);
    }

    var token = manager.GeneratePasswordResetToken(identityUser.Id);
    return Ok(HttpUtility.UrlEncode(token));
}

[HttpGet]
[AllowAnonymous]
[Route("testResetWithOwin")]
public IHttpActionResult TestResetWithOwin(string token)
{
    var manager = Request.GetOwinContext().GetUserManager<ApplicationUserManager>();

    var email = "[email protected]";
    var identityUser = manager.FindByEmail(email);
    var valid = Task.Run(() => manager.UserTokenProvider.ValidateAsync("ResetPassword", token, manager, identityUser)).Result;
    var result = manager.ResetPassword(identityUser.Id, token, "TestingTest1!");
    return Ok(result);
}

The DpapiDataProtectionProvider and DataProtectorTokenProvider needs to be created with the same name for a password reset to work. Using Owin for creating the password reset token and then creating a new DpapiDataProtectionProvider with another name won't work.

Code that I use for ASP.NET Identity:

Web.Config:

<add key="AllowedHosts" value="example.com,example2.com" />

AccountController.cs:

[Route("RequestResetPasswordToken/{email}/")]
[HttpGet]
[AllowAnonymous]
public async Task<IHttpActionResult> GetResetPasswordToken([FromUri]string email)
{
    if (!ModelState.IsValid)
        return BadRequest(ModelState);

    var user = await UserManager.FindByEmailAsync(email);
    if (user == null)
    {
        Logger.Warn("Password reset token requested for non existing email");
        // Don't reveal that the user does not exist
        return NoContent();
    }

    //Prevent Host Header Attack -> Password Reset Poisoning. 
    //If the IIS has a binding to accept connections on 80/443 the host parameter can be changed.
    //See https://security.stackexchange.com/a/170759/67046
    if (!ConfigurationManager.AppSettings["AllowedHosts"].Split(',').Contains(Request.RequestUri.Host)) {
            Logger.Warn($"Non allowed host detected for password reset {Request.RequestUri.Scheme}://{Request.Headers.Host}");
            return BadRequest();
    }

    Logger.Info("Creating password reset token for user id {0}", user.Id);

    var host = $"{Request.RequestUri.Scheme}://{Request.Headers.Host}";
    var token = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
    var callbackUrl = $"{host}/resetPassword/{HttpContext.Current.Server.UrlEncode(user.Email)}/{HttpContext.Current.Server.UrlEncode(token)}";

    var subject = "Client - Password reset.";
    var body = "<html><body>" +
               "<h2>Password reset</h2>" +
               $"<p>Hi {user.FullName}, <a href=\"{callbackUrl}\"> please click this link to reset your password </a></p>" +
               "</body></html>";

    var message = new IdentityMessage
    {
        Body = body,
        Destination = user.Email,
        Subject = subject
    };

    await UserManager.EmailService.SendAsync(message);

    return NoContent();
}

[HttpPost]
[Route("ResetPassword/")]
[AllowAnonymous]
public async Task<IHttpActionResult> ResetPasswordAsync(ResetPasswordRequestModel model)
{
    if (!ModelState.IsValid)
        return NoContent();

    var user = await UserManager.FindByEmailAsync(model.Email);
    if (user == null)
    {
        Logger.Warn("Reset password request for non existing email");
        return NoContent();
    }            

    if (!await UserManager.UserTokenProvider.ValidateAsync("ResetPassword", model.Token, UserManager, user))
    {
        Logger.Warn("Reset password requested with wrong token");
        return NoContent();
    }

    var result = await UserManager.ResetPasswordAsync(user.Id, model.Token, model.NewPassword);

    if (result.Succeeded)
    {
        Logger.Info("Creating password reset token for user id {0}", user.Id);

        const string subject = "Client - Password reset success.";
        var body = "<html><body>" +
                   "<h1>Your password for Client was reset</h1>" +
                   $"<p>Hi {user.FullName}!</p>" +
                   "<p>Your password for Client was reset. Please inform us if you did not request this change.</p>" +
                   "</body></html>";

        var message = new IdentityMessage
        {
            Body = body,
            Destination = user.Email,
            Subject = subject
        };

        await UserManager.EmailService.SendAsync(message);
    }

    return NoContent();
}

public class ResetPasswordRequestModel
{
    [Required]
    [Display(Name = "Token")]
    public string Token { get; set; }

    [Required]
    [Display(Name = "Email")]
    public string Email { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 10)]
    [DataType(DataType.Password)]
    [Display(Name = "New password")]
    public string NewPassword { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm new password")]
    [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }
}

Yahoo Finance API

You may use YQL however yahoo.finance.* tables are not the core yahoo tables. It is an open data table which uses the 'csv api' and converts it to json or xml format. It is more convenient to use but it's not always reliable. I could not use it just a while ago because it the table hits its storage limit or something...

You may use this php library to get historical data / quotes using YQL https://github.com/aygee/php-yql-finance

.autocomplete is not a function Error

You are calling the function before the page loads jQuery. It is always advisable to use jQuery inside

$(document).ready(function(){ //Your code here });

In your case:

$(document).ready(function(){
   $(function(){
      $( "#searcharea" ).autocomplete({
         source: "suggestions.php"
      });
      $( "#searchcat" ).autocomplete({
         source: "suggestions1.php"
      });
   });
});

Will the IE9 WebBrowser Control Support all of IE9's features, including SVG?

I had the same problem, and the registry answers here didn't work.

I had a browser control in new version of my program that worked fine on XP, failed in Windows 7 (64 bit). The old version worked on both XP and Windows 7.

The webpage displayed in the browser uses some strange plugin for showing old SVG maps (I think its a Java applet).

Turns out the problem is related to DEP protection in Windows 7.

Old versions of dotnet 2 didn't set the DEP required flag in the exe, but from dotnet 2, SP 1 onwards it did (yep, the compiling behaviour and hence runtime behaviour of exe changed depending on which machine you compiled on, nice ...).

It is documented on a MSDN blog NXCOMPAT and the C# compiler. To quote : This will undoubtedly surprise a few developers...download a framework service pack, recompile, run your app, and you're now getting IP_ON_HEAP exceptions.

Adding the following to the post build in Visual Studio, turns DEP off for the exe, and everything works as expected:

all "$(DevEnvDir)..\tools\vsvars32.bat"
editbin.exe /NXCOMPAT:NO "$(TargetPath)"

How do I use Join-Path to combine more than two strings into a file path?

Since PowerShell 6.0, Join-Path has a new parameter called -AdditionalChildPath and can combine multiple parts of a path out-of-the-box. Either by providing the extra parameter or by just supplying a list of elements.

Example from the documentation:

Join-Path a b c d e f g
a\b\c\d\e\f\g

So in PowerShell 6.0 and above your variant

$path = Join-Path C: "Program Files" "Microsoft Office"

works as expected!

How to check if a line is blank using regex

Full credit to bchr02 for this answer. However, I had to modify it a bit to catch the scenario for lines that have */ (end of comment) followed by an empty line. The regex was matching the non empty line with */.

New: (^(\r\n|\n|\r)$)|(^(\r\n|\n|\r))|^\s*$/gm

All I did is add ^ as second character to signify the start of line.

Push git commits & tags simultaneously

Maybe this helps someone:

git tag 0.0.1                    # creates tag locally     
git push origin 0.0.1            # pushes tag to remote

git tag --delete 0.0.1           # deletes tag locally    
git push --delete origin 0.0.1   # deletes remote tag

Validating URL in Java

The java.net.URL class is in fact not at all a good way of validating URLs. MalformedURLException is not thrown on all malformed URLs during construction. Catching IOException on java.net.URL#openConnection().connect() does not validate URL either, only tell wether or not the connection can be established.

Consider this piece of code:

    try {
        new URL("http://.com");
        new URL("http://com.");
        new URL("http:// ");
        new URL("ftp://::::@example.com");
    } catch (MalformedURLException malformedURLException) {
        malformedURLException.printStackTrace();
    }

..which does not throw any exceptions.

I recommend using some validation API implemented using a context free grammar, or in very simplified validation just use regular expressions. However I need someone to suggest a superior or standard API for this, I only recently started searching for it myself.

Note It has been suggested that URL#toURI() in combination with handling of the exception java.net. URISyntaxException can facilitate validation of URLs. However, this method only catches one of the very simple cases above.

The conclusion is that there is no standard java URL parser to validate URLs.

Can anyone explain me StandardScaler?

Intro: I assume that you have a matrix X where each row/line is a sample/observation and each column is a variable/feature (this is the expected input for any sklearn ML function by the way -- X.shape should be [number_of_samples, number_of_features]).


Core of method: The main idea is to normalize/standardize i.e. µ = 0 and s = 1 your features/variables/columns of X, individually, before applying any machine learning model.

StandardScaler() will normalize the features i.e. each column of X, INDIVIDUALLY, so that each column/feature/variable will have µ = 0 and s = 1.


P.S: I find the most upvoted answer on this page, wrong. I am quoting "each value in the dataset will have the sample mean value subtracted" -- This is neither true nor correct.


See also: How and why to Standardize your data: A python tutorial


Example:

from sklearn.preprocessing import StandardScaler
import numpy as np

# 4 samples/observations and 2 variables/features
data = np.array([[0, 0], [1, 0], [0, 1], [1, 1]])
scaler = StandardScaler()
scaled_data = scaler.fit_transform(data)

print(data)
[[0, 0],
 [1, 0],
 [0, 1],
 [1, 1]])

print(scaled_data)
[[-1. -1.]
 [ 1. -1.]
 [-1.  1.]
 [ 1.  1.]]

Verify that the mean of each feature (column) is 0:

scaled_data.mean(axis = 0)
array([0., 0.])

Verify that the std of each feature (column) is 1:

scaled_data.std(axis = 0)
array([1., 1.])

The maths:

enter image description here


UPDATE 08/2020: Concerning the input parameters with_mean and with_std to False/True, I have provided an answer here: StandardScaler difference between “with_std=False or True” and “with_mean=False or True”

IF a cell contains a string

You can use OR() to group expressions (as well as AND()):

=IF(OR(condition1, condition2), true, false)

=IF(AND(condition1, condition2), true, false)

So if you wanted to test for "cat" and "22":

=IF(AND(SEARCH("cat",a1),SEARCH("22",a1)),"cat and 22","none")

Running java with JAVA_OPTS env variable has no effect

I don't know of any JVM that actually checks the JAVA_OPTS environment variable. Usually this is used in scripts which launch the JVM and they usually just add it to the java command-line.

The key thing to understand here is that arguments to java that come before the -jar analyse.jar bit will only affect the JVM and won't be passed along to your program. So, modifying the java line in your script to:

java $JAVA_OPTS -jar analyse.jar $*

Should "just work".

Is there a way to get element by XPath using JavaScript in Selenium WebDriver?

public class JSElementLocator {

    @Test
    public void locateElement() throws InterruptedException{
        WebDriver driver = WebDriverProducerFactory.getWebDriver("firefox");

        driver.get("https://www.google.co.in/");


        WebElement searchbox = null;

        Thread.sleep(1000);
        searchbox = (WebElement) (((JavascriptExecutor) driver).executeScript("return document.getElementById('lst-ib');", searchbox));
        searchbox.sendKeys("hello");
    }
}

Make sure you are using the right locator for it.

JavaScript/jQuery: replace part of string?

It should be like this

$(this).text($(this).text().replace('N/A, ', ''))

SQL Server : login success but "The database [dbName] is not accessible. (ObjectExplorer)"

Really stupid solution but I'll add it here in case anyone gets here from a Google search.

I'd just restarted the SQL service and was getting this error and in my case, just waiting 10 minutes was enough and it was fine again. Seems this is the error you get when it is just starting up.

What is __init__.py for?

It facilitates importing other python files. When you placed this file in a directory (say stuff)containing other py files, then you can do something like import stuff.other.

root\
    stuff\
         other.py

    morestuff\
         another.py

Without this __init__.py inside the directory stuff, you couldn't import other.py, because Python doesn't know where the source code for stuff is and unable to recognize it as a package.

How do you stash an untracked file?

As has been said elsewhere, the answer is to git add the file. e.g.:

git add path/to/untracked-file
git stash

However, the question is also raised in another answer: What if you don't really want to add the file? Well, as far as I can tell, you have to. And the following will NOT work:

git add -N path/to/untracked/file     # note: -N is short for --intent-to-add
git stash

this will fail, as follows:

path/to/untracked-file: not added yet
fatal: git-write-tree: error building trees
Cannot save the current index state

So, what can you do? Well, you have to truly add the file, however, you can effectively un-add it later, with git rm --cached:

git add path/to/untracked-file
git stash save "don't forget to un-add path/to/untracked-file" # stash w/reminder
# do some other work
git stash list
# shows:
# stash@{0}: On master: don't forget to un-add path/to/untracked-file
git stash pop   # or apply instead of pop, to keep the stash available
git rm --cached path/to/untracked-file

And then you can continue working, in the same state as you were in before the git add (namely with an untracked file called path/to/untracked-file; plus any other changes you might have had to tracked files).

Another possibility for a workflow on this would be something like:

git ls-files -o > files-to-untrack
git add `cat files-to-untrack` # note: files-to-untrack will be listed, itself!
git stash
# do some work
git stash pop
git rm --cached `cat files-to-untrack`
rm files-to-untrack

[Note: As mentioned in a comment from @mancocapac, you may wish to add --exclude-standard to the git ls-files command (so, git ls-files -o --exclude-standard).]

... which could also be easily scripted -- even aliases would do (presented in zsh syntax; adjust as needed) [also, I shortened the filename so it all fits on the screen without scrolling in this answer; feel free to substitute an alternate filename of your choosing]:

alias stashall='git ls-files -o > .gftu; git add `cat .gftu`; git stash'
alias unstashall='git stash pop; git rm --cached `cat .gftu`; rm .gftu'

Note that the latter might be better as a shell script or function, to allow parameters to be supplied to git stash, in case you don't want pop but apply, and/or want to be able to specify a specific stash, rather than just taking the top one. Perhaps this (instead of the second alias, above) [whitespace stripped to fit without scrolling; re-add for increased legibility]:

function unstashall(){git stash "${@:-pop}";git rm --cached `cat .gftu`;rm .gftu}

Note: In this form, you need to supply an action argument as well as the identifier if you're going to supply a stash identifier, e.g. unstashall apply stash@{1} or unstashall pop stash@{1}

Which of course you'd put in your .zshrc or equivalent to make exist long-term.

Hopefully this answer is helpful to someone, putting everything together all in one answer.

Installing SciPy and NumPy using pip

Since the previous instructions for installing with yum are broken here are the updated instructions for installing on something like fedora. I've tested this on "Amazon Linux AMI 2016.03"

sudo yum install atlas-devel lapack-devel blas-devel libgfortran
pip install scipy

onClick not working on mobile (touch)

better to use touchstart event with .on() jQuery method:

$(window).load(function() { // better to use $(document).ready(function(){
    $('.List li').on('click touchstart', function() {
        $('.Div').slideDown('500');
    });
});

And i don't understand why you are using $(window).load() method because it waits for everything on a page to be loaded, this tend to be slow, while you can use $(document).ready() method which does not wait for each element on the page to be loaded first.

Javascript String to int conversion

Although parseInt is the official function to do this, you can achieve the same with this code:

number*1

The advantage is that you save some characters, which might save bandwidth if your code has to lots of such conversations.

HTML5 <video> element on Android

Roman's answer worked fine for me - or at least, it gave me what I was expecting. Opening the video in the phone's native application is exactly the same as what the iPhone does.

It's probably worth adjusting your viewpoint and expect video to be played fullscreen in its own application, and coding for that. It's frustrating that clicking the video isn't sufficient to get it playing in the same way as the iPhone does, but seeing as it only takes an onclick attribute to launch it, it's not the end of the world.

My advice, FWIW, is to use a poster image, and make it obvious that it will play the video. I'm working on a project at the moment that does precisely that, and the clients are happy with it - and also that they're getting the Android version of a web app for free, of course, because the contract was only for an iPhone web app.

Just for illustration, a working Android video tag is below. Nice and simple.

<video src="video/placeholder.m4v" poster="video/placeholder.jpg" onclick="this.play();"/>

Creating an instance of class

   /* 1 */ Foo* foo1 = new Foo ();

Creates an object of type Foo in dynamic memory. foo1 points to it. Normally, you wouldn't use raw pointers in C++, but rather a smart pointer. If Foo was a POD-type, this would perform value-initialization (it doesn't apply here).

   /* 2 */ Foo* foo2 = new Foo;

Identical to before, because Foo is not a POD type.

   /* 3 */ Foo foo3;

Creates a Foo object called foo3 in automatic storage.

   /* 4 */ Foo foo4 = Foo::Foo();

Uses copy-initialization to create a Foo object called foo4 in automatic storage.

   /* 5 */ Bar* bar1 = new Bar ( *new Foo() );

Uses Bar's conversion constructor to create an object of type Bar in dynamic storage. bar1 is a pointer to it.

   /* 6 */ Bar* bar2 = new Bar ( *new Foo );

Same as before.

   /* 7 */ Bar* bar3 = new Bar ( Foo foo5 );

This is just invalid syntax. You can't declare a variable there.

   /* 8 */ Bar* bar3 = new Bar ( Foo::Foo() );

Would work and work by the same principle to 5 and 6 if bar3 wasn't declared on in 7.

5 & 6 contain memory leaks.

Syntax like new Bar ( Foo::Foo() ); is not usual. It's usually new Bar ( (Foo()) ); - extra parenthesis account for most-vexing parse. (corrected)

Java Reflection Performance

In the doReflection() is the overhead because of Class.forName("misc.A") (that would require a class lookup, potentially scanning the class path on the filsystem), rather than the newInstance() called on the class. I am wondering what the stats would look like if the Class.forName("misc.A") is done only once outside the for-loop, it doesn't really have to be done for every invocation of the loop.

Error LNK2019: Unresolved External Symbol in Visual Studio

When you have everything #included, an unresolved external symbol is often a missing * or & in the declaration or definition of a function.

Upload Image using POST form data in Python-requests

import requests

image_file_descriptor = open('test.jpg', 'rb')
# Requests makes it simple to upload Multipart-encoded files 
files = {'media': image_file_descriptor}
url = '...'
requests.post(url, files=files)
image_file_descriptor.close()

Don't forget to close the descriptor, it prevents bugs: Is explicitly closing files important?

How to print a list in Python "nicely"

As other answers have mentioned, pprint is a great module that will do what you want. However if you don't want to import it and just want to print debugging output during development, you can approximate its output.

Some of the other answers work fine for strings, but if you try them with a class object it will give you the error TypeError: sequence item 0: expected string, instance found.

For more complex objects, make sure the class has a __repr__ method that prints the property information you want:

class Foo(object):
    def __init__(self, bar):
        self.bar = bar

    def __repr__(self):
        return "Foo - (%r)" % self.bar

And then when you want to print the output, simply map your list to the str function like this:

l = [Foo(10), Foo(20), Foo("A string"), Foo(2.4)]
print "[%s]" % ",\n ".join(map(str,l))

outputs:

 [Foo - (10),
  Foo - (20),
  Foo - ('A string'),
  Foo - (2.4)]

You can also do things like override the __repr__ method of list to get a form of nested pretty printing:

class my_list(list):
    def __repr__(self):
        return "[%s]" % ",\n ".join(map(str, self))

a = my_list(["first", 2, my_list(["another", "list", "here"]), "last"])
print a

gives

[first,
 2,
 [another,
 list,
 here],
 last]

Unfortunately no second-level indentation but for a quick debug it can be useful.

CSS border less than 1px

A pixel is the smallest unit value to render something with, but you can trick thickness with optical illusions by modifying colors (the eye can only see up to a certain resolution too).

Here is a test to prove this point:

_x000D_
_x000D_
div { border-color: blue; border-style: solid; margin: 2px; }

div.b1 { border-width: 1px; }
div.b2 { border-width: 0.1em; }
div.b3 { border-width: 0.01em; }
div.b4 { border-width: 1px; border-color: rgb(160,160,255); }
_x000D_
<div class="b1">Some text</div>
<div class="b2">Some text</div>
<div class="b3">Some text</div>
<div class="b4">Some text</div>
_x000D_
_x000D_
_x000D_

Output

enter image description here

Which gives the illusion that the last DIV has a smaller border width, because the blue border blends more with the white background.


Edit: Alternate solution

Alpha values may also be used to simulate the same effect, without the need to calculate and manipulate RGB values.

_x000D_
_x000D_
.container {
  border-style: solid;
  border-width: 1px;
  
  margin-bottom: 10px;
}

.border-100 { border-color: rgba(0,0,255,1); }
.border-75 { border-color: rgba(0,0,255,0.75); }
.border-50 { border-color: rgba(0,0,255,0.5); }
.border-25 { border-color: rgba(0,0,255,0.25); }
_x000D_
<div class="container border-100">Container 1 (alpha = 1)</div>
<div class="container border-75">Container 2 (alpha = 0.75)</div>
<div class="container border-50">Container 3 (alpha = 0.5)</div>
<div class="container border-25">Container 4 (alpha = 0.25)</div>
_x000D_
_x000D_
_x000D_

Concatenate columns in Apache Spark DataFrame

Here is a suggestion for when you don't know the number or name of the columns in the Dataframe.

val dfResults = dfSource.select(concat_ws(",",dfSource.columns.map(c => col(c)): _*))

Difference between volatile and synchronized in Java

It's important to understand that there are two aspects to thread safety.

  1. execution control, and
  2. memory visibility

The first has to do with controlling when code executes (including the order in which instructions are executed) and whether it can execute concurrently, and the second to do with when the effects in memory of what has been done are visible to other threads. Because each CPU has several levels of cache between it and main memory, threads running on different CPUs or cores can see "memory" differently at any given moment in time because threads are permitted to obtain and work on private copies of main memory.

Using synchronized prevents any other thread from obtaining the monitor (or lock) for the same object, thereby preventing all code blocks protected by synchronization on the same object from executing concurrently. Synchronization also creates a "happens-before" memory barrier, causing a memory visibility constraint such that anything done up to the point some thread releases a lock appears to another thread subsequently acquiring the same lock to have happened before it acquired the lock. In practical terms, on current hardware, this typically causes flushing of the CPU caches when a monitor is acquired and writes to main memory when it is released, both of which are (relatively) expensive.

Using volatile, on the other hand, forces all accesses (read or write) to the volatile variable to occur to main memory, effectively keeping the volatile variable out of CPU caches. This can be useful for some actions where it is simply required that visibility of the variable be correct and order of accesses is not important. Using volatile also changes treatment of long and double to require accesses to them to be atomic; on some (older) hardware this might require locks, though not on modern 64 bit hardware. Under the new (JSR-133) memory model for Java 5+, the semantics of volatile have been strengthened to be almost as strong as synchronized with respect to memory visibility and instruction ordering (see http://www.cs.umd.edu/users/pugh/java/memoryModel/jsr-133-faq.html#volatile). For the purposes of visibility, each access to a volatile field acts like half a synchronization.

Under the new memory model, it is still true that volatile variables cannot be reordered with each other. The difference is that it is now no longer so easy to reorder normal field accesses around them. Writing to a volatile field has the same memory effect as a monitor release, and reading from a volatile field has the same memory effect as a monitor acquire. In effect, because the new memory model places stricter constraints on reordering of volatile field accesses with other field accesses, volatile or not, anything that was visible to thread A when it writes to volatile field f becomes visible to thread B when it reads f.

-- JSR 133 (Java Memory Model) FAQ

So, now both forms of memory barrier (under the current JMM) cause an instruction re-ordering barrier which prevents the compiler or run-time from re-ordering instructions across the barrier. In the old JMM, volatile did not prevent re-ordering. This can be important, because apart from memory barriers the only limitation imposed is that, for any particular thread, the net effect of the code is the same as it would be if the instructions were executed in precisely the order in which they appear in the source.

One use of volatile is for a shared but immutable object is recreated on the fly, with many other threads taking a reference to the object at a particular point in their execution cycle. One needs the other threads to begin using the recreated object once it is published, but does not need the additional overhead of full synchronization and it's attendant contention and cache flushing.

// Declaration
public class SharedLocation {
    static public SomeObject someObject=new SomeObject(); // default object
    }

// Publishing code
// Note: do not simply use SharedLocation.someObject.xxx(), since although
//       someObject will be internally consistent for xxx(), a subsequent 
//       call to yyy() might be inconsistent with xxx() if the object was 
//       replaced in between calls.
SharedLocation.someObject=new SomeObject(...); // new object is published

// Using code
private String getError() {
    SomeObject myCopy=SharedLocation.someObject; // gets current copy
    ...
    int cod=myCopy.getErrorCode();
    String txt=myCopy.getErrorText();
    return (cod+" - "+txt);
    }
// And so on, with myCopy always in a consistent state within and across calls
// Eventually we will return to the code that gets the current SomeObject.

Speaking to your read-update-write question, specifically. Consider the following unsafe code:

public void updateCounter() {
    if(counter==1000) { counter=0; }
    else              { counter++; }
    }

Now, with the updateCounter() method unsynchronized, two threads may enter it at the same time. Among the many permutations of what could happen, one is that thread-1 does the test for counter==1000 and finds it true and is then suspended. Then thread-2 does the same test and also sees it true and is suspended. Then thread-1 resumes and sets counter to 0. Then thread-2 resumes and again sets counter to 0 because it missed the update from thread-1. This can also happen even if thread switching does not occur as I have described, but simply because two different cached copies of counter were present in two different CPU cores and the threads each ran on a separate core. For that matter, one thread could have counter at one value and the other could have counter at some entirely different value just because of caching.

What's important in this example is that the variable counter was read from main memory into cache, updated in cache and only written back to main memory at some indeterminate point later when a memory barrier occurred or when the cache memory was needed for something else. Making the counter volatile is insufficient for thread-safety of this code, because the test for the maximum and the assignments are discrete operations, including the increment which is a set of non-atomic read+increment+write machine instructions, something like:

MOV EAX,counter
INC EAX
MOV counter,EAX

Volatile variables are useful only when all operations performed on them are "atomic", such as my example where a reference to a fully formed object is only read or written (and, indeed, typically it's only written from a single point). Another example would be a volatile array reference backing a copy-on-write list, provided the array was only read by first taking a local copy of the reference to it.

Import python package from local directory into interpreter

Using sys.path should include current directory already.

Try:

import .

or:

from . import sth

however it may be not a good practice, so why not just use:

import mypackage

How can I make a SQL temp table with primary key and auto-incrementing field?

If you're just doing some quick and dirty temporary work, you can also skip typing out an explicit CREATE TABLE statement and just make the temp table with a SELECT...INTO and include an Identity field in the select list.

select IDENTITY(int, 1, 1) as ROW_ID,
       Name
into #tmp
from (select 'Bob' as Name union all
      select 'Susan' as Name union all
      select 'Alice' as Name) some_data

select *
from #tmp

Get the week start date and week end date from week number

I have a way other, It is select day Start and day End of Week Current:

DATEADD(d, -(DATEPART(dw, GETDATE()-2)), GETDATE()) is date time Start

and

DATEADD(day,7-(DATEPART(dw,GETDATE()-1)),GETDATE()) is date time End

Cross compile Go on OSX?

If you use Homebrew on OS X, then you have a simpler solution:

$ brew install go --with-cc-common # Linux, Darwin, and Windows

or..

$ brew install go --with-cc-all # All the cross-compilers

Use reinstall if you already have go installed.

Wpf DataGrid Add new row

Try this MSDN blog

Also, try the following example:

Xaml:

   <DataGrid AutoGenerateColumns="False" Name="DataGridTest" CanUserAddRows="True" ItemsSource="{Binding TestBinding}" Margin="0,50,0,0" >
        <DataGrid.Columns>
            <DataGridTextColumn Header="Line" IsReadOnly="True" Binding="{Binding Path=Test1}" Width="50"></DataGridTextColumn>
            <DataGridTextColumn Header="Account" IsReadOnly="True"  Binding="{Binding Path=Test2}" Width="130"></DataGridTextColumn>
        </DataGrid.Columns>
    </DataGrid>
    <Button Content="Add new row" HorizontalAlignment="Left" Margin="0,10,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_1"/>

CS:

 /// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        var data = new Test { Test1 = "Test1", Test2 = "Test2" };

        DataGridTest.Items.Add(data);
    }
}

public class Test
{
    public string Test1 { get; set; }
    public string Test2 { get; set; }
}

How do I connect to a specific Wi-Fi network in Android programmatically?

Before connecting WIFI network you need to check security type of the WIFI network ScanResult class has a capabilities. This field gives you type of network

Refer: https://developer.android.com/reference/android/net/wifi/ScanResult.html#capabilities

There are three types of WIFI networks.

First, instantiate a WifiConfiguration object and fill in the network’s SSID (note that it has to be enclosed in double quotes), set the initial state to disabled, and specify the network’s priority (numbers around 40 seem to work well).

WifiConfiguration wfc = new WifiConfiguration();

wfc.SSID = "\"".concat(ssid).concat("\"");
wfc.status = WifiConfiguration.Status.DISABLED;
wfc.priority = 40;

Now for the more complicated part: we need to fill several members of WifiConfiguration to specify the network’s security mode. For open networks.

wfc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
wfc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
wfc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
wfc.allowedAuthAlgorithms.clear();
wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);

For networks using WEP; note that the WEP key is also enclosed in double quotes.

wfc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
wfc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
wfc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
wfc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
wfc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);

if (isHexString(password)) wfc.wepKeys[0] = password;
else wfc.wepKeys[0] = "\"".concat(password).concat("\"");
wfc.wepTxKeyIndex = 0;

For networks using WPA and WPA2, we can set the same values for either.

wfc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
wfc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
wfc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);

wfc.preSharedKey = "\"".concat(password).concat("\"");

Finally, we can add the network to the WifiManager’s known list

WifiManager wfMgr = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
int networkId = wfMgr.addNetwork(wfc);
if (networkId != -1) {
 // success, can call wfMgr.enableNetwork(networkId, true) to connect
} 

How to declare a variable in a template in Angular

Here is a directive I wrote that expands on the use of the exportAs decorator parameter, and allows you to use a dictionary as a local variable.

import { Directive, Input } from "@angular/core";
@Directive({
    selector:"[localVariables]",
    exportAs:"localVariables"
})
export class LocalVariables {
    @Input("localVariables") set localVariables( struct: any ) {
        if ( typeof struct === "object" ) {
            for( var variableName in struct ) {
                this[variableName] = struct[variableName];
            }
        }
    }
    constructor( ) {
    }
}

You can use it as follows in a template:

<div #local="localVariables" [localVariables]="{a: 1, b: 2, c: 3+2}">
   <span>a = {{local.a}}</span>
   <span>b = {{local.b}}</span>
   <span>c = {{local.c}}</span>
</div>

Of course #local can be any valid local variable name.

sed with literal string--not input file

My version using variables in a bash script:

Find any backslashes and replace with forward slashes:

input="This has a backslash \\"

output=$(echo "$input" | sed 's,\\,/,g')

echo "$output"

What is the difference between ApplicationContext and WebApplicationContext in Spring MVC?

The accepted answer is through but there is official explanation on this:

The WebApplicationContext is an extension of the plain ApplicationContext that has some extra features necessary for web applications. It differs from a normal ApplicationContext in that it is capable of resolving themes (see Using themes), and that it knows which Servlet it is associated with (by having a link to the ServletContext). The WebApplicationContext is bound in the ServletContext, and by using static methods on the RequestContextUtils class you can always look up the WebApplicationContext if you need access to it.

Cited from Spring web framework reference

By the way servlet and root context are both webApplicationContext:

Typical context hierarchy in Spring Web MVC

Imported a csv-dataset to R but the values becomes factors

Both the data import function (here: read.csv()) as well as a global option offer you to say stringsAsFactors=FALSE which should fix this.

setState() inside of componentDidUpdate()

The componentDidUpdate signature is void::componentDidUpdate(previousProps, previousState). With this you will be able to test which props/state are dirty and call setState accordingly.

Example:

componentDidUpdate(previousProps, previousState) {
    if (previousProps.data !== this.props.data) {
        this.setState({/*....*/})
    }
}

How should I cast in VB.NET?

According to the certification exam you should use Convert.ToXXX() whenever possible for simple conversions because it optimizes performance better than CXXX conversions.

Creating a Plot Window of a Particular Size

This will depend on the device you're using. If you're using a pdf device, you can do this:

pdf( "mygraph.pdf", width = 11, height = 8 )
plot( x, y )

You can then divide up the space in the pdf using the mfrow parameter like this:

par( mfrow = c(2,2) )

That makes a pdf with four panels available for plotting. Unfortunately, some of the devices take different units than others. For example, I think that X11 uses pixels, while I'm certain that pdf uses inches. If you'd just like to create several devices and plot different things to them, you can use dev.new(), dev.list(), and dev.next().

Other devices that might be useful include:

There's a list of all of the devices here.

Button text toggle in jquery

You could also use .toggle() like so:

$(".pushme").toggle(function() {
    $(this).text("DON'T PUSH ME");
}, function() {
    $(this).text("PUSH ME");
});

More info at http://api.jquery.com/toggle-event/.

This way also makes it pretty easy to change the text or add more than just 2 differing states.

How to debug JavaScript / jQuery event bindings with Firebug or similar tools?

Here's a plugin which can list all event handlers for any given element/event:

$.fn.listHandlers = function(events, outputFunction) {
    return this.each(function(i){
        var elem = this,
            dEvents = $(this).data('events');
        if (!dEvents) {return;}
        $.each(dEvents, function(name, handler){
            if((new RegExp('^(' + (events === '*' ? '.+' : events.replace(',','|').replace(/^on/i,'')) + ')$' ,'i')).test(name)) {
               $.each(handler, function(i,handler){
                   outputFunction(elem, '\n' + i + ': [' + name + '] : ' + handler );
               });
           }
        });
    });
};

Use it like this:

// List all onclick handlers of all anchor elements:
$('a').listHandlers('onclick', console.info);

// List all handlers for all events of all elements:
$('*').listHandlers('*', console.info);

// Write a custom output function:
$('#whatever').listHandlers('click',function(element,data){
    $('body').prepend('<br />' + element.nodeName + ': <br /><pre>' + data + '<\/pre>');
});

Src: (my blog) -> http://james.padolsey.com/javascript/debug-jquery-events-with-listhandlers/

How to get the last day of the month?

Here is a solution based python lambdas:

next_month = lambda y, m, d: (y, m + 1, 1) if m + 1 < 13 else ( y+1 , 1, 1)
month_end  = lambda dte: date( *next_month( *dte.timetuple()[:3] ) ) - timedelta(days=1)

The next_month lambda finds the tuple representation of the first day of the next month, and rolls over to the next year. The month_end lambda transforms a date (dte) to a tuple, applies next_month and creates a new date. Then the "month's end" is just the next month's first day minus timedelta(days=1).

Clear text field value in JQuery

For the most part you just set the .val() method. All of the answers are pretty accurate, just wanted to post my results to anyone who may need to set the value via the client id that gets rendered.

 $('#' + '<%= doc_title.ClientID %>').val(null);

Install .ipa to iPad with or without iTunes

Since Apple released iTunes 12, you must use Apple Configurator 2 app to install ipa in your iPhone and iPad.

Download from this link: https://itunes.apple.com/br/app/apple-configurator-2/id1037126344?mt=12

How to move a git repository into another directory and make that directory a git repository?

It's very simple. Git doesn't care about what's the name of its directory. It only cares what's inside. So you can simply do:

# copy the directory into newrepo dir that exists already (else create it)
$ cp -r gitrepo1 newrepo

# remove .git from old repo to delete all history and anything git from it
$ rm -rf gitrepo1/.git

Note that the copy is quite expensive if the repository is large and with a long history. You can avoid it easily too:

# move the directory instead
$ mv gitrepo1 newrepo

# make a copy of the latest version
# Either:
$ mkdir gitrepo1; cp -r newrepo/* gitrepo1/  # doesn't copy .gitignore (and other hidden files)

# Or:
$ git clone --depth 1 newrepo gitrepo1; rm -rf gitrepo1/.git

# Or (look further here: http://stackoverflow.com/q/1209999/912144)
$ git archive --format=tar --remote=<repository URL> HEAD | tar xf -

Once you create newrepo, the destination to put gitrepo1 could be anywhere, even inside newrepo if you want it. It doesn't change the procedure, just the path you are writing gitrepo1 back.

Convert string to Date in java

String str_date="13-09-2011";
DateFormat formatter ; 
Date date ; 
formatter = new SimpleDateFormat("dd-MM-yyyy");
date = (Date)formatter.parse(str_date); 
System.out.println("Today is " +date.getTime());

Try this

Use ASP.NET MVC validation with jquery ajax?

Here's a rather simple solution:

In the controller we return our errors like this:

if (!ModelState.IsValid)
        {
            return Json(new { success = false, errors = ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage).ToList() }, JsonRequestBehavior.AllowGet);
        }

Here's some of the client script:

function displayValidationErrors(errors)
{
    var $ul = $('div.validation-summary-valid.text-danger > ul');

    $ul.empty();
    $.each(errors, function (idx, errorMessage) {
        $ul.append('<li>' + errorMessage + '</li>');
    });
}

That's how we handle it via ajax:

$.ajax({
    cache: false,
    async: true,
    type: "POST",
    url: form.attr('action'),
    data: form.serialize(),
    success: function (data) {
        var isSuccessful = (data['success']);

        if (isSuccessful) {
            $('#partial-container-steps').html(data['view']);
            initializePage();
        }
        else {
            var errors = data['errors'];

            displayValidationErrors(errors);
        }
    }
});

Also, I render partial views via ajax in the following way:

var view = this.RenderRazorViewToString(partialUrl, viewModel);
        return Json(new { success = true, view }, JsonRequestBehavior.AllowGet);

RenderRazorViewToString method:

public string RenderRazorViewToString(string viewName, object model)
    {
        ViewData.Model = model;
        using (var sw = new StringWriter())
        {
            var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,
                                                                     viewName);
            var viewContext = new ViewContext(ControllerContext, viewResult.View,
                                         ViewData, TempData, sw);
            viewResult.View.Render(viewContext, sw);
            viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
            return sw.GetStringBuilder().ToString();
        }
    }

frequent issues arising in android view, Error parsing XML: unbound prefix

As you mention, you need to specify the right namespace. You also see this error with an incorrect namespace.

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns="http://schemas.android.com/apk/res/android"
         android:layout_width="fill_parent"
         android:layout_height="fill_parent"
         android:padding="10dip">

will not work.

Change:

xmlns="http://schemas.android.com/apk/res/android"

to

xmlns:android="http://schemas.android.com/apk/res/android"

The error message is referring to everything that starts "android:" as the XML does not know what the "android:" namespace is.

xmlns:android defines it.

How to print the values of slices

fmt.Printf() is fine, but sometimes I like to use pretty print package.

import "github.com/kr/pretty"
pretty.Print(...)

Search File And Find Exact Match And Print Line?

It's very easy:

numb = raw_input('Input Line: ')
fiIn = open('file.txt').readlines()
for lines in fiIn:
   if numb == lines[0]:
      print lines

Convert hex string (char []) to int?

I know this is really old but I think the solutions looked too complicated. Try this in VB:

Public Function HexToInt(sHEX as String) as long
Dim iLen as Integer
Dim i as Integer 
Dim SumValue as Long 
Dim iVal as long
Dim AscVal as long

    iLen = Len(sHEX)
    For i = 1 to Len(sHEX)
      AscVal = Asc(UCase(Mid$(sHEX, i,  1)))
      If AscVal >= 48 And AscVal  <= 57 Then
        iVal  = AscVal - 48
      ElseIf AscVal >= 65 And AscVal <= 70 Then
        iVal = AscVal - 55
      End If 
      SumValue = SumValue + iVal * 16 ^ (iLen- i)
    Next i 
    HexToInt  = SumValue
End Function 

C# DateTime to "YYYYMMDDHHMMSS" format

I am surprised no one has a link for this . any format can be created using the guidelines here:

Custom Date and Time Format Strings

For your specific example (As others have indicated) use something like

my_format="yyyyMMddHHmmss";
DateTime.Now.ToString(my_format);

Where my_format can be any string combination of y,M,H,m,s,f,F and more! Check out the link.

Provide password to ssh command inside bash script, Without the usage of public keys and Expect

For security reasons you must avoid providing password on a command line otherwise anyone running ps command can see your password. Better to use sshpass utility like this:

#!/bin/bash

export SSHPASS="your-password"
sshpass -e ssh -oBatchMode=no sshUser@remoteHost

You might be interested in How to run the sftp command with a password from Bash script?

jQuery UI DatePicker - Change Date Format

$("#datepicker").datepicker({ dateFormat: "yy-mm-dd" }).val()

Jquery: Checking to see if div contains text, then action

Why not simply

var item = $('.field-item');
for (var i = 0; i <= item.length; i++) {
       if ($(item[i]).text() == 'someText') {
             $(item[i]).addClass('thisClass');
             //do some other stuff here
          }
     }

What is the difference between the kernel space and the user space?

Kernel Space and User Space are logical spaces.

Most of the modern processors are designed to run in different privileged mode. x86 machines can run in 4 different privileged modes. enter image description here

And a particular machine instruction can be executed when in/above particular privileged mode.

Because of this design you are giving a system protection or sand-boxing the execution environment.

Kernel is a piece of code, which manages your hardware and provide system abstraction. So it needs to have access for all the machine instruction. And it is most trusted piece of software. So i should be executed with the highest privilege. And Ring level 0 is the most privileged mode. So Ring Level 0 is also called as Kernel Mode.

User Application are piece of software which comes from any third party vendor, and you can't completely trust them. Someone with malicious intent can write a code to crash your system if he had complete access to all the machine instruction. So application should be provided with access to limited set of instructions. And Ring Level 3 is the least privileged mode. So all your application run in that mode. Hence that Ring Level 3 is also called User Mode.

Note: I am not getting Ring Levels 1 and 2. They are basically modes with intermediate privilege. So may be device driver code are executed with this privilege. AFAIK, linux uses only Ring Level 0 and 3 for kernel code execution and user application respectively.

So any operation happening in kernel mode can be considered as kernel space. And any operation happening in user mode can be considered as user space.

Running an executable in Mac Terminal

To run an executable in mac

1). Move to the path of the file:

cd/PATH_OF_THE_FILE

2). Run the following command to set the file's executable bit using the chmod command:

chmod +x ./NAME_OF_THE_FILE

3). Run the following command to execute the file:

./NAME_OF_THE_FILE

Once you have run these commands, going ahead you just have to run command 3, while in the files path.

How can I see an the output of my C programs using Dev-C++?

Use #include conio.h

Then add getch(); before return 0;

Prevent redirect after form is submitted

Probably you will have to do just an Ajax request to your page. And doing return false there is doing not what you think it is doing.

Set up DNS based URL forwarding in Amazon Route53

I was running into the exact same problem that Saurav described, but I really needed to find a solution that did not require anything other than Route 53 and S3. I created a how-to guide for my blog detailing what I did.

Here is what I came up with.


Objective

Using only the tools available in Amazon S3 and Amazon Route 53, create a URL Redirect that automatically forwards http://url-redirect-example.vivekmchawla.com to the AWS Console sign-in page aliased to "MyAccount", located at https://myaccount.signin.aws.amazon.com/console/ .

This guide will teach you set up URL forwarding to any URL, not just ones from Amazon. You will learn how to set up forwarding to specific folders (like "/console" in my example), and how to change the protocol of the redirect from HTTP to HTTPS (or vice versa).


Step One: Create Your S3 Bucket

Open the S3 Management Console and click "Create Bucket"

Open the S3 management console and click "Create Bucket".


Step Two: Name Your S3 Bucket

Name your S3 Bucket

  1. Choose a Bucket Name. This step is really important! You must name the bucket EXACTLY the same as the URL you want to set up for forwarding. For this guide, I'll use the name "url-redirect-example.vivekmchawla.com".

  2. Select whatever region works best for you. If you don't know, keep the default.

  3. Don't worry about setting up logging. Just click the "Create" button when you're ready.


Step 3: Enable Static Website Hosting and Specify Routing Rules

Enable Static Website Hosting and Specify Routing Rules

  1. In the properties window, open the settings for "Static Website Hosting".
  2. Select the option to "Enable website hosting".
  3. Enter a value for the "Index Document". This object (document) will never be served by S3, and you never have to upload it. Just use any name you want.
  4. Open the settings for "Edit Redirection Rules".
  5. Paste the following XML snippet in it's entirety.

    <RoutingRules>
      <RoutingRule>
        <Redirect>
          <Protocol>https</Protocol>
          <HostName>myaccount.signin.aws.amazon.com</HostName>
          <ReplaceKeyPrefixWith>console/</ReplaceKeyPrefixWith>
          <HttpRedirectCode>301</HttpRedirectCode>
        </Redirect>
      </RoutingRule>
    </RoutingRules>
    

If you're curious about what the above XML is doing, visit the AWM Documentation for "Syntax for Specifying Routing Rules". A bonus technique (not covered here) is forwarding to specific pages at the destination host, for example http://redirect-destination.com/console/special-page.html. Read about the <ReplaceKeyWith> element if you need this functionality.


Step 4: Make Note of Your Redirect Bucket's "Endpoint"

Make a note of your Redirect Bucket's Endpoint

Make note of the Static Website Hosting "endpoint" that Amazon automatically created for this bucket. You'll need this for later, so highlight the entire URL, then copy and paste it to notepad.

CAUTION! At this point you can actually click this link to check to see if your Redirection Rules were entered correctly, but be careful! Here's why...

Let's say you entered the wrong value inside the <Hostname> tags in your Redirection Rules. Maybe you accidentally typed myaccount.amazon.com, instead of myaccount.signin.aws.amazon.com. If you click the link to test the Endpoint URL, AWS will happily redirect your browser to the wrong address!

After noticing your mistake, you will probably edit the <Hostname> in your Redirection Rules to fix the error. Unfortunately, when you try to click the link again, you'll most likely end up being redirected back to the wrong address! Even though you fixed the <Hostname> entry, your browser is caching the previous (incorrect!) entry. This happens because we're using an HTTP 301 (permanent) redirect, which browsers like Chrome and Firefox will cache by default.

If you copy and paste the Endpoint URL to a different browser (or clear the cache in your current one), you'll get another chance to see if your updated <Hostname> entry is finally the correct one.

To be safe, if you want to test your Endpoint URL and Redirect Rules, you should open a private browsing session, like "Incognito Mode" in Chrome. Copy, paste, and test the Endpoint URL in Incognito Mode and anything cached will go away once you close the session.


Step 5: Open the Route53 Management Console and Go To the Record Sets for Your Hosted Zone (Domain Name)

Open the Route 53 Management Console to Add Record Sets to your Hosted Zone

  1. Select the Hosted Zone (domain name) that you used when you created your bucket. Since I named my bucket "url-redirect-example.vivekmchawla.com", I'm going to select the vivekmchawla.com Hosted Zone.
  2. Click on the "Go to Record Sets" button.

Step 6: Click the "Create Record Set" Button

Click the Create Record Set button

Clicking "Create Record Set" will open up the Create Record Set window on the right side of the Route53 Management Console.


Step 7: Create a CNAME Record Set

Create a CNAME Record Set

  1. In the Name field, enter the hostname portion of the URL that you used when naming your S3 bucket. The "hostname portion" of the URL is everything to the LEFT of your Hosted Zone's name. I named my S3 bucket "url-redirect-example.vivekmchawla.com", and my Hosted Zone is "vivekmchawla.com", so the hostname portion I need to enter is "url-redirect-example".

  2. Select "CNAME - Canonical name" for the Type of this Record Set.

  3. For the Value, paste in the Endpoint URL of the S3 bucket we created back in Step 3.

  4. Click the "Create Record Set" button. Assuming there are no errors, you'll now be able to see a new CNAME record in your Hosted Zone's list of Record Sets.


Step 8: Test Your New URL Redirect

Open up a new browser tab and type in the URL that we just set up. For me, that's http://url-redirect-example.vivekmchawla.com. If everything worked right, you should be sent directly to an AWS sign-in page.

Because we used the myaccount.signin.aws.amazon.com alias as our redirect's destination URL, Amazon knows exactly which account we're trying to access, and takes us directly there. This can be very handy if you want to give a short, clean, branded AWS login link to employees or contractors.

All done! Your URL forwarding should take you to the AWS sign-in page.


Conclusions

I personally love the various AWS services, but if you've decided to migrate DNS management to Amazon Route 53, the lack of easy URL forwarding can be frustrating. I hope this guide helped make setting up URL forwarding for your Hosted Zones a bit easier.

If you'd like to learn more, please take a look at the following pages from the AWS Documentation site.

Cheers!

Excel formula is only showing the formula rather than the value within the cell in Office 2010

Make sure you include the = sign in addition to passing the arguments to the function. I.E.

=SUM(A1:A3) //this would give you the sum of cells A1, A2, and A3.

Hot to get all form elements values using jQuery?

If you want to use $(formName).serializeArray() or $(formName).serialize(), you must add name='inputName' on your input element. or will not work!

"Couldn't read dependencies" error with npm

It's simple, you're just not in the right directory.

Go to the C:\Program Files\nodejs\node_modules\npm and you should be able to run this command properly.

Converting Varchar Value to Integer/Decimal Value in SQL Server

You are getting arithmetic overflow. this means you are trying to make a conversion impossible to be made. This error is thrown when you try to make a conversion and the destiny data type is not enough to convert the origin data. For example:

If you try to convert 100.52 to decimal(4,2) you will get this error. The number 100.52 requires 5 positions and 2 of them are decimal.

Try to change the decimal precision to something like 16,2 or higher. Try with few records first then use it to all your select.

How do I delete from multiple tables using INNER JOIN in SQL server

You can use JOIN syntax in FROM clause in DELETE in SQL Server but you still delete from first table only and it's proprietary Transact-SQL extension which is alternative to sub-query.

From example here:

 -- Transact-SQL extension
 DELETE 
   FROM Sales.SalesPersonQuotaHistory 
     FROM Sales.SalesPersonQuotaHistory AS spqh INNER JOIN 
          Sales.SalesPerson AS sp ON spqh.BusinessEntityID = sp.BusinessEntityID
    WHERE sp.SalesYTD > 2500000.00;

Pycharm and sys.argv arguments

On PyCharm Community or Professional Edition 2019.1+ :

  1. From the menu bar click Run -> Edit Configurations
  2. Add your arguments in the Parameters textbox (for example file2.txt file3.txt, or --myFlag myArg --anotherFlag mySecondArg)
  3. Click Apply
  4. Click OK

How to embed new Youtube's live video permanent URL?

The embed URL for a channel's live stream is:

https://www.youtube.com/embed/live_stream?channel=CHANNEL_ID

You can find your CHANNEL_ID at https://www.youtube.com/account_advanced

Carriage return in C?

Step-by-step:

[newline]ab

ab

[backspace]si

asi

[carriage-return]ha

hai

Carriage return, does not cause a newline. Under some circumstances a single CR or LF may be translated to a CR-LF pair. This is console and/or stream dependent.

C# Break out of foreach loop after X number of items

int processed = 0;
foreach(ListViewItem lvi in listView.Items)
{
   //do stuff
   if (++processed == 50) break;
}

or use LINQ

foreach( ListViewItem lvi in listView.Items.Cast<ListViewItem>().Take(50))
{
    //do stuff
}

or just use a regular for loop (as suggested by @sgriffinusa and @Eric J.)

for(int i = 0; i < 50 && i < listView.Items.Count; i++)
{
    ListViewItem lvi = listView.Items[i];
}

Java: parse int value from a char

String element = "el5";
int x = element.charAt(2) - 48;

Subtracting ascii value of '0' = 48 from char

How to test if a string contains one of the substrings in a list, in pandas?

One option is just to use the regex | character to try to match each of the substrings in the words in your Series s (still using str.contains).

You can construct the regex by joining the words in searchfor with |:

>>> searchfor = ['og', 'at']
>>> s[s.str.contains('|'.join(searchfor))]
0    cat
1    hat
2    dog
3    fog
dtype: object

As @AndyHayden noted in the comments below, take care if your substrings have special characters such as $ and ^ which you want to match literally. These characters have specific meanings in the context of regular expressions and will affect the matching.

You can make your list of substrings safer by escaping non-alphanumeric characters with re.escape:

>>> import re
>>> matches = ['$money', 'x^y']
>>> safe_matches = [re.escape(m) for m in matches]
>>> safe_matches
['\\$money', 'x\\^y']

The strings with in this new list will match each character literally when used with str.contains.

Performing user authentication in Java EE / JSF using j_security_check

I suppose you want form based authentication using deployment descriptors and j_security_check.

You can also do this in JSF by just using the same predefinied field names j_username and j_password as demonstrated in the tutorial.

E.g.

<form action="j_security_check" method="post">
    <h:outputLabel for="j_username" value="Username" />
    <h:inputText id="j_username" />
    <br />
    <h:outputLabel for="j_password" value="Password" />
    <h:inputSecret id="j_password" />
    <br />
    <h:commandButton value="Login" />
</form>

You could do lazy loading in the User getter to check if the User is already logged in and if not, then check if the Principal is present in the request and if so, then get the User associated with j_username.

package com.stackoverflow.q2206911;

import java.io.IOException;
import java.security.Principal;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

@ManagedBean
@SessionScoped
public class Auth {

    private User user; // The JPA entity.

    @EJB
    private UserService userService;

    public User getUser() {
        if (user == null) {
            Principal principal = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();
            if (principal != null) {
                user = userService.find(principal.getName()); // Find User by j_username.
            }
        }
        return user;
    }

}

The User is obviously accessible in JSF EL by #{auth.user}.

To logout do a HttpServletRequest#logout() (and set User to null!). You can get a handle of the HttpServletRequest in JSF by ExternalContext#getRequest(). You can also just invalidate the session altogether.

public String logout() {
    FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
    return "login?faces-redirect=true";
}

For the remnant (defining users, roles and constraints in deployment descriptor and realm), just follow the Java EE 6 tutorial and the servletcontainer documentation the usual way.


Update: you can also use the new Servlet 3.0 HttpServletRequest#login() to do a programmatic login instead of using j_security_check which may not per-se be reachable by a dispatcher in some servletcontainers. In this case you can use a fullworthy JSF form and a bean with username and password properties and a login method which look like this:

<h:form>
    <h:outputLabel for="username" value="Username" />
    <h:inputText id="username" value="#{auth.username}" required="true" />
    <h:message for="username" />
    <br />
    <h:outputLabel for="password" value="Password" />
    <h:inputSecret id="password" value="#{auth.password}" required="true" />
    <h:message for="password" />
    <br />
    <h:commandButton value="Login" action="#{auth.login}" />
    <h:messages globalOnly="true" />
</h:form>

And this view scoped managed bean which also remembers the initially requested page:

@ManagedBean
@ViewScoped
public class Auth {

    private String username;
    private String password;
    private String originalURL;

    @PostConstruct
    public void init() {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        originalURL = (String) externalContext.getRequestMap().get(RequestDispatcher.FORWARD_REQUEST_URI);

        if (originalURL == null) {
            originalURL = externalContext.getRequestContextPath() + "/home.xhtml";
        } else {
            String originalQuery = (String) externalContext.getRequestMap().get(RequestDispatcher.FORWARD_QUERY_STRING);

            if (originalQuery != null) {
                originalURL += "?" + originalQuery;
            }
        }
    }

    @EJB
    private UserService userService;

    public void login() throws IOException {
        FacesContext context = FacesContext.getCurrentInstance();
        ExternalContext externalContext = context.getExternalContext();
        HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();

        try {
            request.login(username, password);
            User user = userService.find(username, password);
            externalContext.getSessionMap().put("user", user);
            externalContext.redirect(originalURL);
        } catch (ServletException e) {
            // Handle unknown username/password in request.login().
            context.addMessage(null, new FacesMessage("Unknown login"));
        }
    }

    public void logout() throws IOException {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        externalContext.invalidateSession();
        externalContext.redirect(externalContext.getRequestContextPath() + "/login.xhtml");
    }

    // Getters/setters for username and password.
}

This way the User is accessible in JSF EL by #{user}.

How to export iTerm2 Profiles

I didn't touch the "save to a folder" option. I just copied the two files/directories you mentioned in your question to the new machine, then ran defaults read com.googlecode.iterm2.

See https://apple.stackexchange.com/a/111559

Drop primary key using script in SQL Server database

The answer I got is that variables and subqueries will not work and we have to user dynamic SQL script. The following works:

DECLARE @SQL VARCHAR(4000)
SET @SQL = 'ALTER TABLE dbo.Student DROP CONSTRAINT |ConstraintName| '

SET @SQL = REPLACE(@SQL, '|ConstraintName|', ( SELECT   name
                                               FROM     sysobjects
                                               WHERE    xtype = 'PK'
                                                        AND parent_obj =        OBJECT_ID('Student')))

EXEC (@SQL)

How to get the range of occupied cells in excel sheet

These two lines on their own wasnt working for me:

xlWorkSheet.Columns.ClearFormats();
xlWorkSheet.Rows.ClearFormats();

You can test by hitting ctrl+end in the sheet and seeing which cell is selected.

I found that adding this line after the first two solved the problem in all instances I've encountered:

Excel.Range xlActiveRange = WorkSheet.UsedRange;

Return only string message from Spring MVC 3 Controller

@ResponseBody
@RequestMapping(value="/get-text", produces="text/plain")
public String myMethod() {
     return "Response!";
}
  • You see that @ResponseBody ?

It's telling that the method returns some text and not to interpret it as a view etc.

  • You see that produces="text/plain" ?

It's just a good practice as it tells what will be returned from the method :)

C++ Double Address Operator? (&&)

&& is new in C++11. int&& a means "a" is an r-value reference. && is normally only used to declare a parameter of a function. And it only takes a r-value expression. If you don't know what an r-value is, the simple explanation is that it doesn't have a memory address. E.g. the number 6, and character 'v' are both r-values. int a, a is an l-value, however (a+2) is an r-value. For example:

void foo(int&& a)
{
    //Some magical code...
}

int main()
{
    int b;
    foo(b); //Error. An rValue reference cannot be pointed to a lValue.
    foo(5); //Compiles with no error.
    foo(b+3); //Compiles with no error.

    int&& c = b; //Error. An rValue reference cannot be pointed to a lValue.
    int&& d = 5; //Compiles with no error.
}

Hope that is informative.

Sorting a Data Table

After setting the sort expression on the DefaultView (table.DefaultView.Sort = "Town ASC, Cutomer ASC" ) you should loop over the table using the DefaultView not the DataTable instance itself

foreach(DataRowView r in table.DefaultView)
{
    //... here you get the rows in sorted order
    Console.WriteLine(r["Town"].ToString());
}

Using the Select method of the DataTable instead, produces an array of DataRow. This array is sorted as from your request, not the DataTable

DataRow[] rowList = table.Select("", "Town ASC, Cutomer ASC");
foreach(DataRow r in rowList)
{
    Console.WriteLine(r["Town"].ToString());
}

Find all table names with column name?

Please try the below query. Use sys.columns to get the details :-

SELECT c.name AS ColName, t.name AS TableName
FROM sys.columns c
    JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name LIKE '%MyCol%';

NSNotificationCenter addObserver in Swift

A nice way of doing this is to use the addObserver(forName:object:queue:using:) method rather than the addObserver(_:selector:name:object:) method that is often used from Objective-C code. The advantage of the first variant is that you don't have to use the @objc attribute on your method:

    func batteryLevelChanged(notification: Notification) {
        // do something useful with this information
    }

    let observer = NotificationCenter.default.addObserver(
        forName: NSNotification.Name.UIDeviceBatteryLevelDidChange,
        object: nil, queue: nil,
        using: batteryLevelChanged)

and you can even just use a closure instead of a method if you want:

    let observer = NotificationCenter.default.addObserver(
        forName: NSNotification.Name.UIDeviceBatteryLevelDidChange,
        object: nil, queue: nil) { _ in print("") }

You can use the returned value to stop listening for the notification later:

    NotificationCenter.default.removeObserver(observer)

There used to be another advantage in using this method, which was that it doesn't require you to use selector strings which couldn't be statically checked by the compiler and so were fragile to breaking if the method is renamed, but Swift 2.2 and later include #selector expressions that fix that problem.

How to get file's last modified date on Windows command line?

Useful reference to get file properties using a batch file, included is the last modified time:

FOR %%? IN ("C:\somefile\path\file.txt") DO (
    ECHO File Name Only       : %%~n?
    ECHO File Extension       : %%~x?
    ECHO Name in 8.3 notation : %%~sn?
    ECHO File Attributes      : %%~a?
    ECHO Located on Drive     : %%~d?
    ECHO File Size            : %%~z?
    ECHO Last-Modified Date   : %%~t?
    ECHO Drive and Path       : %%~dp?
    ECHO Drive                : %%~d?
    ECHO Fully Qualified Path : %%~f?
    ECHO FQP in 8.3 notation  : %%~sf?
    ECHO Location in the PATH : %%~dp$PATH:?
)

How to detect online/offline event cross-browser?

Currently in 2011, the various browser vendors cannot agree on how to define offline. Some browsers have a Work Offline feature, which they consider separate to a lack of network access, which again is different to internet access. The whole thing is a mess. Some browser vendors update the navigator.onLine flag when actual network access is lost, others don't.

From the spec:

Returns false if the user agent is definitely offline (disconnected from the network). Returns true if the user agent might be online.

The events online and offline are fired when the value of this attribute changes.

The navigator.onLine attribute must return false if the user agent will not contact the network when the user follows links or when a script requests a remote page (or knows that such an attempt would fail), and must return true otherwise.

Finally, the spec notes:

This attribute is inherently unreliable. A computer can be connected to a network without having Internet access.

How to filter wireshark to see only dns queries that are sent/received from/by my computer?

Rather than using a DisplayFilter you could use a very simple CaptureFilter like

port 53

See the "Capture only DNS (port 53) traffic" example on the CaptureFilters wiki.

How to call Stored Procedure in Entity Framework 6 (Code-First)?

This is what EF (DB first) generates in the DbContext class:

public ObjectResult<int> Insert_Department(string department)
{
    var departmentParameter = new ObjectParameter("department", department);

    return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<int>("insert_department", departmentParameter);
}

Difference between Date(dateString) and new Date(dateString)

I recently ran into this as well and this was a helpful post. I took the above Topera a step further and this works for me in both chrome and firefox:

var temp = new Date(  Date("2010-08-17 12:09:36")   );
alert(temp);

the internal call to Date() returns a string that new Date() can parse.

Xcode 6 iPhone Simulator Application Support location

This worked for me in swift:

let dirPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
println("App Path: \(dirPaths)")

How to call a method in another class in Java?

class A{
  public void methodA(){
    new B().methodB();
    //or
    B.methodB1();
  }
}

class B{
  //instance method
  public void methodB(){
  }
  //static method
  public static  void methodB1(){
  }
}

How to set background color of HTML element using css properties in JavaScript

Javascript:

document.getElementById("ID").style.background = "colorName"; //JS ID

document.getElementsByClassName("ClassName")[0].style.background = "colorName"; //JS Class

Jquery:

$('#ID/.className').css("background","colorName") // One style

$('#ID/.className').css({"background":"colorName","color":"colorname"}); //Multiple style

Is true == 1 and false == 0 in JavaScript?

Ah, the dreaded loose comparison operator strikes again. Never use it. Always use strict comparison, === or !== instead.

Bonus fact: 0 == ''

List files with certain extensions with ls and grep

Here is one example that worked for me.

find <mainfolder path> -name '*myfiles.java' | xargs -n 1 basename

Passing route control with optional parameter after root in express?

That would work depending on what client.get does when passed undefined as its first parameter.

Something like this would be safer:

app.get('/:key?', function(req, res, next) {
    var key = req.params.key;
    if (!key) {
        next();
        return;
    }
    client.get(key, function(err, reply) {
        if(client.get(reply)) {
            res.redirect(reply);
        }
        else {
            res.render('index', {
                link: null
            });
        }
    });
});

There's no problem in calling next() inside the callback.

According to this, handlers are invoked in the order that they are added, so as long as your next route is app.get('/', ...) it will be called if there is no key.

Is it possible to use pip to install a package from a private GitHub repository?

It also works with Bitbucket:

pip install git+ssh://[email protected]/username/projectname.git

Pip will use your SSH keys in this case.

Codeigniter $this->db->order_by(' ','desc') result is not complete

$this->db1->where('tennant_id', $tennant_id);
$this->db1->order_by('id', 'DESC');
return $this->db1->get('courses')->result();

How do you rename a MongoDB database?

There is no mechanism to re-name databases. The currently accepted answer at time of writing is factually correct and offers some interesting background detail as to the excuse upstream, but offers no suggestions for replicating the behavior. Other answers point at copyDatabase, which is no longer an option as the functionality has been removed in 4.0. I've updated SERVER-701 with my notes and incredulity.

Equivalent behavior involves mongodump and mongorestore in a bit of a dance:

  1. Export your data, making note of the "namespaces" in use. For example, on one of my datasets, I have a collection with the namespace byzmcbehoomrfjcs9vlj.Analytics — that prefix (actually the database name) will be needed in the next step.

  2. Import your data, supplying --nsFrom and --nsTo arguments. (Documentation.) Continuing with my above hypothetical (and extremely unreadable) example, to restore to a more sensical name, I invoke:

mongorestore --archive=backup.agz --gzip --drop \
    --nsFrom 'byzmcbehoomrfjcs9vlj.*' --nsTo 'rita.*'

Some may also point at the --db argument to mongorestore, however this, too, is deprecated and triggers a warning against use on non-BSON folder backups with a completely erroneous suggestion to "use --nsInclude instead". The above namespace translation is equivalent to use of the --db option, and is the correct namespace manipulation setup to use as we are not attempting to filter what is being restored.

Configure hibernate to connect to database via JNDI Datasource

Tomcat-7 JNDI configuration:

Steps:

  1. Open the server.xml in the tomcat-dir/conf
  2. Add below <Resource> tag with your DB details inside <GlobalNamingResources>
<Resource name="jdbc/mydb"
          global="jdbc/mydb"
          auth="Container"
          type="javax.sql.DataSource"
          driverClassName="com.mysql.jdbc.Driver"
          url="jdbc:mysql://localhost:3306/test"
          username="root"
          password=""
          maxActive="10"
          maxIdle="10"
          minIdle="5"
          maxWait="10000"/>
  1. Save the server.xml file
  2. Open the context.xml in the tomcat-dir/conf
  3. Add the below <ResourceLink> inside the <Context> tag.
<ResourceLink name="jdbc/mydb" 
              global="jdbc/mydb"
              auth="Container"
              type="javax.sql.DataSource" />
  1. Save the context.xml
  2. Open the hibernate-cfg.xml file and add and remove below properties.
Adding:
-------
<property name="connection.datasource">java:comp/env/jdbc/mydb</property>

Removing:
--------
<!--<property name="connection.url">jdbc:mysql://localhost:3306/mydb</property> -->
<!--<property name="connection.username">root</property> -->
<!--<property name="connection.password"></property> -->
  1. Save the file and put latest .WAR file in tomcat.
  2. Restart the tomcat. the DB connection will work.

What is the documents directory (NSDocumentDirectory)?

Aside from the Documents folder, iOS also lets you save files to the temp and Library folders.

For more information on which one to use, see this link from the documentation:

invalid byte sequence for encoding "UTF8"

psql=# copy tmp from '/path/to/file.csv' with delimiter ',' csv header encoding 'windows-1251';

Adding encoding option worked in my case.

React Native fixed footer

Off the top of my head you could do this with a ScrollView. Your top-level container could be a flex container, inside that have a ScrollView at the top and your footer at the bottom. Then inside the ScrollView just put the rest of your app as normal.

Mysql where id is in array

Your query translates to:

SELECT name FROM users WHERE id IN ('Array');

Or something to that affect.

Try using prepared queries instead, something like:

$numbers = explode(',', $string);
$prepare = array_map(function(){ return '?'; }, $numbers);
$statement = mysqli_prepare($link , "SELECT name FROM users WHERE id IN ('".implode(',', $prepare)."')");
if($statement) {
   $ints = array_map(function(){ return 'i'; }, $numbers);
   call_user_func_array("mysqli_stmt_bind_param", array_merge(
      array($statement, implode('', $ints)), $numbers
   ));
   $results = mysqli_stmt_execute($statement);
   // do something with results 
   // ...
}

Convert Enumeration to a Set/List

I needed same thing and this solution work fine, hope it can help someone also

Enumeration[] array = Enumeration.values();
List<Enumeration> list = Arrays.asList(array);

then you can get the .name() of your enumeration.

How do you update a DateTime field in T-SQL?

Normally, it should work.

But can you try this? I don't have SQL on my home PC, I can't try myself

UPDATE table
SET EndDate = '2009-05-25 00:00:00.000'
WHERE Id = 1

Create an Android GPS tracking application

The source code for the Android mobile application open-gpstracker which you appreciated is available here.

You can checkout the code using SVN client application or via Git:

Debugging the source code will surely help you.

PHP: Show yes/no confirmation dialog

You can handle the attribute onClick for both i.e. 'ok' & 'cancel' condition like ternary operator

Scenario: Here is the scenario that I wants to show confirm box which will ask for 'ok' or 'cancel' while performing a delete action. In that I want if user click on 'ok' then the form action will redirect to page location and on cancel page will not respond.

Adding further explanation i'm having one button with type="submit" which is originally use default form action of form tag. and I want above scenario on delete button with same input type.

So below code is working properly for me

onClick="return confirm('Are you sure you want to Delete ?')?this.form.action='<?php echo $_SERVER['PHP_SELF'] ?>':false;"

Full code

<input type="submit" name="action" id="Delete" value="Delete" onClick="return confirm('Are you sure you want to Delete ?')?this.form.action='<?php echo $_SERVER['PHP_SELF'] ?>':false;">

And by the way I'm implementing this code as inline in html element using PHP. so that's why I used 'echo $_SERVER['PHP_SELF']'.

I hope it will work for you also. Thank You

C# refresh DataGridView when updating or inserted on another form

Create a small function and use it anywhere

public SqlConnection con = "Your connection string"; 
public void gridviewUpdate()
{
    con.Open();
    string select = "SELECT * from table_name";
    SqlDataAdapter da = new SqlDataAdapter(select, con);
    DataSet ds = new DataSet();
    da.Fill(ds, "table_name");
    datagridview.DataSource = ds;
    datagridview.DataMember = "table_name";
    con.Close();
}

jQuery textbox change event

The change event only fires after the input loses focus (and was changed).

removeEventListener on anonymous functions in JavaScript

window.document.removeEventListener("keydown", getEventListeners(window.document.keydown[0].listener));  

May be several anonymous functions, keydown1

Warning: only works in Chrome Dev Tools & cannot be used in code: link

Error: Cannot Start Container: stat /bin/sh: no such file or directory"

You have no shell at /bin/sh? Have you tried docker run -it pensu/busybox /usr/bin/sh ?

How to remove duplicate values from an array in PHP

<?php
$a=array("1"=>"302","2"=>"302","3"=>"276","4"=>"301","5"=>"302");
print_r(array_values(array_unique($a)));
?>//`output -> Array ( [0] => 302 [1] => 276 [2] => 301 )`

Get input value from TextField in iOS alert in Swift

Updated for Swift 3 and above:

//1. Create the alert controller.
let alert = UIAlertController(title: "Some Title", message: "Enter a text", preferredStyle: .alert)

//2. Add the text field. You can configure it however you need.
alert.addTextField { (textField) in
    textField.text = "Some default text"
}

// 3. Grab the value from the text field, and print it when the user clicks OK.
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in
    let textField = alert.textFields![0] // Force unwrapping because we know it exists.
    print("Text field: \(textField.text)")
}))

// 4. Present the alert.
self.present(alert, animated: true, completion: nil)

Swift 2.x

Assuming you want an action alert on iOS:

//1. Create the alert controller.            
var alert = UIAlertController(title: "Some Title", message: "Enter a text", preferredStyle: .Alert)

//2. Add the text field. You can configure it however you need.
alert.addTextFieldWithConfigurationHandler({ (textField) -> Void in
    textField.text = "Some default text."
})

//3. Grab the value from the text field, and print it when the user clicks OK. 
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { [weak alert] (action) -> Void in
    let textField = alert.textFields![0] as UITextField
    println("Text field: \(textField.text)")
}))

// 4. Present the alert.
self.presentViewController(alert, animated: true, completion: nil)

IPython/Jupyter Problems saving notebook as PDF

notebook-as-pdfInstall python -m pip install notebook-as-pdf pyppeteer-install

Use it You can also use it with nbconvert:

jupyter-nbconvert --to PDFviaHTML filename.ipynb

which will create a file called filename.pdf.

or pip install notebook-as-pdf

create pdf from notebook jupyter-nbconvert-toPDFviaHTML

JSON formatter in C#?

This worked for me using System.Text.Json in .Net Core 3.1

 public string PrettyJson(string unPrettyJson)
 {
     var options = new JsonSerializerOptions(){
         WriteIndented = true
     };

     var jsonElement = JsonSerializer.Deserialize<JsonElement>(unPrettyJson);

     return JsonSerializer.Serialize(jsonElement, options);
 }

Python - Locating the position of a regex match in a string?

You could use .find("is"), it would return position of "is" in the string

or use .start() from re

>>> re.search("is", String).start()
2

Actually its match "is" from "This"

If you need to match per word, you should use \b before and after "is", \b is the word boundary.

>>> re.search(r"\bis\b", String).start()
5
>>>

for more info about python regular expressions, docs here

How to change the version of the 'default gradle wrapper' in IntelliJ IDEA?

./gradlew wrapper --gradle-version=5.4.1 --distribution-type=bin

https://gradle.org/install/#manually

To check:

 ./gradlew tasks

To input it without command:

go to-> gradle/wrapper/gradle-wrapper.properties distribution url and change it to the updated zip version

output:

 ./gradlew tasks
Downloading https://services.gradle.org/distributions/gradle-5.4.1-bin.zip
...................................................................................

Welcome to Gradle 5.4.1!

Here are the highlights of this release:
 - Run builds with JDK12
 - New API for Incremental Tasks
 - Updates to native projects, including Swift 5 support

For more details see https://docs.gradle.org/5.4.1/release-notes.html

Starting a Gradle Daemon (subsequent builds will be faster)

> Starting Daemon 

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

For any method in a Spring CrudRepository you should be able to specify the @Query yourself. Something like this should work:

@Query( "select o from MyObject o where inventoryId in :ids" )
List<MyObject> findByInventoryIds(@Param("ids") List<Long> inventoryIdList);

Val and Var in Kotlin

Simply, var (mutable) and val (immutable values like in Java (final modifier))

var x:Int=3
x *= x

//gives compilation error (val cannot be re-assigned)
val y: Int = 6
y*=y

Dynamically Changing log4j log level

I have used this method with success to reduce the verbosity of the "org.apache.http" logs:

ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("org.apache.http");
logger.setLevel(Level.TRACE);
logger.setAdditive(false);

Bootstrap Alert Auto Close

I found this to be a better solution

$(".alert-dismissible").fadeTo(2000, 500).slideUp(500, function(){
    $(".alert-dismissible").alert('close');
});

How do I get my solution in Visual Studio back online in TFS?

i found another way without much effort.

Just simply right click your solution and then click undo pending changes.

Next, VS will ask you for acutally changed file where you want to undo or not specific file.

In this you can click no for such a file where actual change is happende, rest is just undoing. This will not lost your actual changes

What does 'var that = this;' mean in JavaScript?

This is a hack to make inner functions (functions defined inside other functions) work more like they should. In javascript when you define one function inside another this automatically gets set to the global scope. This can be confusing because you expect this to have the same value as in the outer function.

var car = {};
car.starter = {};

car.start = function(){
    var that = this;

    // you can access car.starter inside this method with 'this'
    this.starter.active = false;

    var activateStarter = function(){
        // 'this' now points to the global scope
        // 'this.starter' is undefined, so we use 'that' instead.
        that.starter.active = true;

        // you could also use car.starter, but using 'that' gives
        // us more consistency and flexibility
    };

    activateStarter();

};

This is specifically a problem when you create a function as a method of an object (like car.start in the example) then create a function inside that method (like activateStarter). In the top level method this points to the object it is a method of (in this case, car) but in the inner function this now points to the global scope. This is a pain.

Creating a variable to use by convention in both scopes is a solution for this very general problem with javascript (though it's useful in jquery functions, too). This is why the very general sounding name that is used. It's an easily recognizable convention for overcoming a shortcoming in the language.

Like El Ronnoco hints at Douglas Crockford thinks this is a good idea.

Detect encoding and make everything UTF-8

Ÿ is Mojibake for ß. In your database, you may have hex

DF if the column is "latin1",
C39F if the column is utf8 -- OR -- it is latin1, but "double-encoded"
C383C5B8 if double-encoded into a utf8 column

You should not use any encoding/decoding functions in PHP; instead, you should set up the database and the connection to it correctly.

If MySQL is involved, see: Trouble with utf8 characters; what I see is not what I stored

Simple GUI Java calculator

This is the working code...

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

public class JavaCalculator extends JFrame {

    private JButton jbtNum1;
    private JButton jbtNum2;
    private JButton jbtNum3;
    private JButton jbtNum4;
    private JButton jbtNum5;
    private JButton jbtNum6;
    private JButton jbtNum7;
    private JButton jbtNum8;
    private JButton jbtNum9;
    private JButton jbtNum0;
    private JButton jbtEqual;
    private JButton jbtAdd;
    private JButton jbtSubtract;
    private JButton jbtMultiply;
    private JButton jbtDivide;
    private JButton jbtSolve;
    private JButton jbtClear;
    private double TEMP;
    private double SolveTEMP;
    private JTextField jtfResult;

    Boolean addBool = false;
    Boolean subBool = false;
    Boolean divBool = false;
    Boolean mulBool = false;

    String display = "";

    public JavaCalculator() {

        JPanel p1 = new JPanel();
        p1.setLayout(new GridLayout(4, 3));
        p1.add(jbtNum1 = new JButton("1"));
        p1.add(jbtNum2 = new JButton("2"));
        p1.add(jbtNum3 = new JButton("3"));
        p1.add(jbtNum4 = new JButton("4"));
        p1.add(jbtNum5 = new JButton("5"));
        p1.add(jbtNum6 = new JButton("6"));
        p1.add(jbtNum7 = new JButton("7"));
        p1.add(jbtNum8 = new JButton("8"));
        p1.add(jbtNum9 = new JButton("9"));
        p1.add(jbtNum0 = new JButton("0"));
        p1.add(jbtClear = new JButton("C"));

        JPanel p2 = new JPanel();
        p2.setLayout(new FlowLayout());
        p2.add(jtfResult = new JTextField(20));
        jtfResult.setHorizontalAlignment(JTextField.RIGHT);
        jtfResult.setEditable(false);

        JPanel p3 = new JPanel();
        p3.setLayout(new GridLayout(5, 1));
        p3.add(jbtAdd = new JButton("+"));
        p3.add(jbtSubtract = new JButton("-"));
        p3.add(jbtMultiply = new JButton("*"));
        p3.add(jbtDivide = new JButton("/"));
        p3.add(jbtSolve = new JButton("="));

        JPanel p = new JPanel();
        p.setLayout(new GridLayout());
        p.add(p2, BorderLayout.NORTH);
        p.add(p1, BorderLayout.SOUTH);
        p.add(p3, BorderLayout.EAST);

        add(p);

        jbtNum1.addActionListener(new ListenToOne());
        jbtNum2.addActionListener(new ListenToTwo());
        jbtNum3.addActionListener(new ListenToThree());
        jbtNum4.addActionListener(new ListenToFour());
        jbtNum5.addActionListener(new ListenToFive());
        jbtNum6.addActionListener(new ListenToSix());
        jbtNum7.addActionListener(new ListenToSeven());
        jbtNum8.addActionListener(new ListenToEight());
        jbtNum9.addActionListener(new ListenToNine());
        jbtNum0.addActionListener(new ListenToZero());

        jbtAdd.addActionListener(new ListenToAdd());
        jbtSubtract.addActionListener(new ListenToSubtract());
        jbtMultiply.addActionListener(new ListenToMultiply());
        jbtDivide.addActionListener(new ListenToDivide());
        jbtSolve.addActionListener(new ListenToSolve());
        jbtClear.addActionListener(new ListenToClear());
    } //JavaCaluclator()

    class ListenToClear implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            //display = jtfResult.getText();
            jtfResult.setText("");
            addBool = false;
            subBool = false;
            mulBool = false;
            divBool = false;

            TEMP = 0;
            SolveTEMP = 0;
        }
    }

    class ListenToOne implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            display = jtfResult.getText();
            jtfResult.setText(display + "1");
        }
    }

    class ListenToTwo implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            display = jtfResult.getText();
            jtfResult.setText(display + "2");
        }
    }

    class ListenToThree implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            display = jtfResult.getText();
            jtfResult.setText(display + "3");
        }
    }

    class ListenToFour implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            display = jtfResult.getText();
            jtfResult.setText(display + "4");
        }
    }

    class ListenToFive implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            display = jtfResult.getText();
            jtfResult.setText(display + "5");
        }
    }

    class ListenToSix implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            display = jtfResult.getText();
            jtfResult.setText(display + "6");
        }
    }

    class ListenToSeven implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            display = jtfResult.getText();
            jtfResult.setText(display + "7");
        }
    }

    class ListenToEight implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            display = jtfResult.getText();
            jtfResult.setText(display + "8");
        }
    }

    class ListenToNine implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            display = jtfResult.getText();
            jtfResult.setText(display + "9");
        }
    }

    class ListenToZero implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            display = jtfResult.getText();
            jtfResult.setText(display + "0");
        }
    }

    class ListenToAdd implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            TEMP = Double.parseDouble(jtfResult.getText());
            jtfResult.setText("");
            addBool = true;
        }
    }

    class ListenToSubtract implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            TEMP = Double.parseDouble(jtfResult.getText());
            jtfResult.setText("");
            subBool = true;
        }
    }

    class ListenToMultiply implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            TEMP = Double.parseDouble(jtfResult.getText());
            jtfResult.setText("");
            mulBool = true;
        }
    }

    class ListenToDivide implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            TEMP = Double.parseDouble(jtfResult.getText());
            jtfResult.setText("");
            divBool = true;
        }
    }

    class ListenToSolve implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            SolveTEMP = Double.parseDouble(jtfResult.getText());
            if (addBool == true)
                SolveTEMP = SolveTEMP + TEMP;
            else if ( subBool == true)
                SolveTEMP = SolveTEMP - TEMP;
            else if ( mulBool == true)
                SolveTEMP = SolveTEMP * TEMP;
            else if ( divBool == true)
                            SolveTEMP = SolveTEMP / TEMP;
            jtfResult.setText(  Double.toString(SolveTEMP));

            addBool = false;
            subBool = false;
            mulBool = false;
            divBool = false;
        }
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        JavaCalculator calc = new JavaCalculator();
        calc.pack();
        calc.setLocationRelativeTo(null);
                calc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        calc.setVisible(true);
    }

} //JavaCalculator

What is the easiest/best/most correct way to iterate through the characters of a string in Java?

Two options

for(int i = 0, n = s.length() ; i < n ; i++) { 
    char c = s.charAt(i); 
}

or

for(char c : s.toCharArray()) {
    // process c
}

The first is probably faster, then 2nd is probably more readable.

How to ignore ansible SSH authenticity checking?

You can pass it as command line argument while running the playbook:

ansible-playbook play.yml --ssh-common-args='-o StrictHostKeyChecking=no'

passing argument to DialogFragment

as a general way of working with Fragments, as JafarKhQ noted, you should not pass the params in the constructor but with a Bundle.

the built-in method for that in the Fragment class is setArguments(Bundle) and getArguments().

basically, what you do is set up a bundle with all your Parcelable items and send them on.
in turn, your Fragment will get those items in it's onCreate and do it's magic to them.

the way shown in the DialogFragment link was one way of doing this in a multi appearing fragment with one specific type of data and works fine most of the time, but you can also do this manually.

Declare a constant array

An array isn't immutable by nature; you can't make it constant.

The nearest you can get is:

var letter_goodness = [...]float32 {.0817, .0149, .0278, .0425, .1270, .0223, .0202, .0609, .0697, .0015, .0077, .0402, .0241, .0675, .0751, .0193, .0009, .0599, .0633, .0906, .0276, .0098, .0236, .0015, .0197, .0007 }

Note the [...] instead of []: it ensures you get a (fixed size) array instead of a slice. So the values aren't fixed but the size is.

Link vs compile vs controller

I wanted to add also what the O'Reily AngularJS book by the Google Team has to say:

Controller - Create a controller which publishes an API for communicating across directives. A good example is Directive to Directive Communication

Link - Programmatically modify resulting DOM element instances, add event listeners, and set up data binding.

Compile - Programmatically modify the DOM template for features across copies of a directive, as when used in ng-repeat. Your compile function can also return link functions to modify the resulting element instances.

What is copy-on-write?

Just to provide another example, Mercurial uses copy-on-write to make cloning local repositories a really "cheap" operation.

The principle is the same as the other examples, except that you're talking about physical files instead of objects in memory. Initially, a clone is not a duplicate but a hard link to the original. As you change files in the clone, copies are written to represent the new version.

How to convert an Image to base64 string in java?

I think you might want:

String encodedFile = Base64.getEncoder().encodeToString(bytes);

JAVA_HOME directory in Linux

On Linux you can run $(dirname $(dirname $(readlink -f $(which javac))))

On Mac you can run $(dirname $(readlink $(which javac)))/java_home

I'm not sure about windows but I imagine where javac would get you pretty close

setTimeout in React Native

There looks to be an issue when the time of the phone/emulator is different to the one of the server (where react-native packager is running). In my case there was a 1 minute difference between the time of the phone and the computer. After synchronizing them (didn't do anything fancy, the phone was set on manual time, and I just set it to use the network(sim) provided time), everything worked fine. This github issue helped me find the problem.

What order are the Junit @Before/@After called?

I think based on the documentation of the @Before and @After the right conclusion is to give the methods unique names. I use the following pattern in my tests:

public abstract class AbstractBaseTest {

  @Before
  public final void baseSetUp() { // or any other meaningful name
    System.out.println("AbstractBaseTest.setUp");
  }

  @After
  public final void baseTearDown() { // or any other meaningful name
    System.out.println("AbstractBaseTest.tearDown");
  }
}

and

public class Test extends AbstractBaseTest {

  @Before
  public void setUp() {
    System.out.println("Test.setUp");
  }

  @After
  public void tearDown() {
    System.out.println("Test.tearDown");
  }

  @Test
  public void test1() throws Exception {
    System.out.println("test1");
  }

  @Test
  public void test2() throws Exception {
    System.out.println("test2");
  }
}

give as a result

AbstractBaseTest.setUp
Test.setUp
test1
Test.tearDown
AbstractBaseTest.tearDown
AbstractBaseTest.setUp
Test.setUp
test2
Test.tearDown
AbstractBaseTest.tearDown

Advantage of this approach: Users of the AbstractBaseTest class cannot override the setUp/tearDown methods by accident. If they want to, they need to know the exact name and can do it.

(Minor) disadvantage of this approach: Users cannot see that there are things happening before or after their setUp/tearDown. They need to know that these things are provided by the abstract class. But I assume that's the reason why they use the abstract class

How do I calculate someone's age based on a DateTime type birthday?

Here's a little code sample for C# I knocked up, be careful around the edge cases specifically leap years, not all the above solutions take them into account. Pushing the answer out as a DateTime can cause problems as you could end up trying to put too many days into a specific month e.g. 30 days in Feb.

public string LoopAge(DateTime myDOB, DateTime FutureDate)
{
    int years = 0;
    int months = 0;
    int days = 0;

    DateTime tmpMyDOB = new DateTime(myDOB.Year, myDOB.Month, 1);

    DateTime tmpFutureDate = new DateTime(FutureDate.Year, FutureDate.Month, 1);

    while (tmpMyDOB.AddYears(years).AddMonths(months) < tmpFutureDate)
    {
        months++;
        if (months > 12)
        {
            years++;
            months = months - 12;
        }
    }

    if (FutureDate.Day >= myDOB.Day)
    {
        days = days + FutureDate.Day - myDOB.Day;
    }
    else
    {
        months--;
        if (months < 0)
        {
            years--;
            months = months + 12;
        }
        days = days + (DateTime.DaysInMonth(FutureDate.AddMonths(-1).Year, FutureDate.AddMonths(-1).Month) + FutureDate.Day) - myDOB.Day;

    }

    //add an extra day if the dob is a leap day
    if (DateTime.IsLeapYear(myDOB.Year) && myDOB.Month == 2 && myDOB.Day == 29)
    {
        //but only if the future date is less than 1st March
        if(FutureDate >= new DateTime(FutureDate.Year, 3,1))
            days++;
    }

    return "Years: " + years + " Months: " + months + " Days: " + days;
}

Creating an iframe with given HTML dynamically

Allthough your src = encodeURI should work, I would have gone a different way:

var iframe = document.createElement('iframe');
var html = '<body>Foo</body>';
document.body.appendChild(iframe);
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(html);
iframe.contentWindow.document.close();

As this has no x-domain restraints and is completely done via the iframe handle, you may access and manipulate the contents of the frame later on. All you need to make sure of is, that the contents have been rendered, which will (depending on browser type) start during/after the .write command is issued - but not nescessarily done when close() is called.

A 100% compatible way of doing a callback could be this approach:

<html><body onload="parent.myCallbackFunc(this.window)"></body></html>

Iframes has the onload event, however. Here is an approach to access the inner html as DOM (js):

iframe.onload = function() {
   var div=iframe.contentWindow.document.getElementById('mydiv');
};

Cannot find libcrypto in Ubuntu

ld is trying to find libcrypto.sowhich is not present as seen in your locate output. You can make a copy of the libcrypto.so.0.9.8 and name it as libcrypto.so. Put this is your ld path. ( If you do not have root access then you can put it in a local path and specify the path manually )

How to pip or easy_install tkinter on Windows

When installing make sure that under Tcl/Tk you select Will be installed on hard drive. If it is installing with a cross at the left then Tkinter will not be installed.

enter image description here

The same goes for Python 3:

enter image description here

Changing navigation bar color in Swift

If you have customized navigation controller, you can use above code snippet. So in my case, I've used as following code pieces.

Swift 3.0, XCode 8.1 version

navigationController.navigationBar.barTintColor = UIColor.green

Navigation Bar Text:

navigationController.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.orange]

It is very helpful talks.

Is there a way to add/remove several classes in one single instruction with classList?

A better way to add the multiple classes separated by spaces in a string is using the Spread_syntax with the split:

element.classList.add(...classesStr.split(" "));

Prevent scroll-bar from adding-up to the Width of page on Chrome

You can get the scrollbar size and then apply a margin to the container.

Something like this:

var checkScrollBars = function(){
    var b = $('body');
    var normalw = 0;
    var scrollw = 0;
    if(b.prop('scrollHeight')>b.height()){
        normalw = window.innerWidth;
        scrollw = normalw - b.width();
        $('#container').css({marginRight:'-'+scrollw+'px'});
    }
}

CSS for remove the h-scrollbar:

body{
    overflow-x:hidden;
}

Try to take a look at this: http://jsfiddle.net/NQAzt/

Sass .scss: Nesting and multiple classes?

Use &

SCSS

.container {
    background:red;
    color:white;

    &.hello {
        padding-left:50px;
    }
}

https://sass-lang.com/documentation/style-rules/parent-selector

How to insert a line break <br> in markdown

Just adding a new line worked for me if you're to store the markdown in a JavaScript variable. like so

let markdown = `
    1. Apple
    2. Mango
     this is juicy
    3. Orange
`

Get list of all tables in Oracle?

Indeed, it is possible to have the list of tables via SQL queries.it is possible to do that also via tools that allow the generation of data dictionaries, such as ERWIN, Toad Data Modeler or ERBuilder. With these tools, in addition to table names, you will have fields, their types, objects like(triggers, sequences, domain, views...)

Below steps to follow to generate your tables definition:

  1. You have to reverse engineer your database
    • In Toad data modeler: Menu -> File -> reverse engineer -> reverse engineering wizard
    • In ERBuilder data modeler: Menu -> File -> reverse engineer

Your database will be displayed in the software as an Entity Relationship diagram.

  1. Generate your data dictionary that will contain your Tables definition
    • In Toad data modeler: Menu -> Model -> Generate report -> Run
    • In ERBuilder data modeler: Menu -> Tool -> generate model documentation

FontAwesome icons not showing. Why?

To whoever may be checking this out in 2018. I am using font awesome 4.7.0 and I got this issue solved by simply taking out the s in fas as seen in the code <i class="fa fa-[icon-name]"></i>. This was originally <i class="fas fa-[icon-name]"></i>.

Hope this helps.

curl: (35) SSL connect error

If you are using curl versions curl-7.19.7-46.el6.x86_64 or older. Please provide an option as -k1 (small K1).

Sql Server : How to use an aggregate function like MAX in a WHERE clause

The correct way to use max in the having clause is by performing a self join first:

select t1.a, t1.b, t1.c
from table1 t1
join table1 t1_max
  on t1.id = t1_max.id
group by t1.a, t1.b, t1.c
having t1.date = max(t1_max.date)

The following is how you would join with a subquery:

select t1.a, t1.b, t1.c
from table1 t1
where t1.date = (select max(t1_max.date)
                 from table1 t1_max
                 where t1.id = t1_max.id)

Be sure to create a single dataset before using an aggregate when dealing with a multi-table join:

select t1.id, t1.date, t1.a, t1.b, t1.c
into #dataset
from table1 t1
join table2 t2
  on t1.id = t2.id
join table2 t3
  on t1.id = t3.id


select a, b, c
from #dataset d
join #dataset d_max
  on d.id = d_max.id
having d.date = max(d_max.date)
group by a, b, c

Sub query version:

select t1.id, t1.date, t1.a, t1.b, t1.c
into #dataset
from table1 t1
join table2 t2
  on t1.id = t2.id
join table2 t3
  on t1.id = t3.id


select a, b, c
from #dataset d
where d.date = (select max(d_max.date)
                from #dataset d_max
                where d.id = d_max.id)

Returning value that was passed into a method

Even more useful, if you have multiple parameters you can access any/all of them with:

_mock.Setup(x => x.DoSomething(It.IsAny<string>(),It.IsAny<string>(),It.IsAny<string>())
     .Returns((string a, string b, string c) => string.Concat(a,b,c));

You always need to reference all the arguments, to match the method's signature, even if you're only going to use one of them.

Passing a variable from node.js to html

I found the possible way to write.

Server Side -

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

  var name = 'hello';

  res.render(__dirname + "/views/layouts/main.html", {name:name});

});

Client side (main.html) -

<h1><%= name %></h1>