Programs & Examples On #Select into

Creating new table with SELECT INTO in SQL

The syntax for creating a new table is

CREATE TABLE new_table
AS
SELECT *
  FROM old_table

This will create a new table named new_table with whatever columns are in old_table and copy the data over. It will not replicate the constraints on the table, it won't replicate the storage attributes, and it won't replicate any triggers defined on the table.

SELECT INTO is used in PL/SQL when you want to fetch data from a table into a local variable in your PL/SQL block.

Creating Duplicate Table From Existing Table

Use this query to create the new table with the values from existing table

CREATE TABLE New_Table_name AS SELECT * FROM Existing_table_Name; 

Now you can get all the values from existing table into newly created table.

Leaflet - How to find existing markers, and delete markers?

Have you tried layerGroup yet?

Docs here https://leafletjs.com/reference-1.2.0.html#layergroup

Just create a layer, add all marker to this layer, then you can find and destroy marker easily.

var markers = L.layerGroup()
const marker = L.marker([], {})
markers.addLayer(marker)

Django DoesNotExist

I have found the solution to this issue using ObjectDoesNotExist on this way

from django.core.exceptions import ObjectDoesNotExist
......

try:
  # try something
except ObjectDoesNotExist:
  # do something

After this, my code works as I need

Thanks any way, your post help me to solve my issue

Reference to a non-shared member requires an object reference occurs when calling public sub

You either have to make the method Shared or use an instance of the class General:

Dim gen = New General()
gen.updateDynamics(get_prospect.dynamicsID)

or

General.updateDynamics(get_prospect.dynamicsID)

Public Shared Sub updateDynamics(dynID As Int32)
    ' ... '
End Sub

Shared(VB.NET)

WSDL/SOAP Test With soapui

A likely possibility is that your browser reaches your web service through a proxy, and SoapUI is not configured to use that proxy. For example, I work in a corporate environment and while my IE and FireFox can access external websites, my SoapUI can only access internal web services.

The easy solution is to just open the WSDL in a browser, save it to a .xml file, and base your SoapUI project on that. This won't work if your WSDL relies on external XSDs that it can't get to, however.

Easy way to print Perl array? (with a little formatting)

For inspection/debugging check the Data::Printer module. It is meant to do one thing and one thing only:

display Perl variables and objects on screen, properly formatted (to be inspected by a human)

Example usage:

use Data::Printer;  
p @array;  # no need to pass references

The code above might output something like this (with colors!):

   [
       [0] "a",
       [1] "b",
       [2] undef,
       [3] "c",
   ]

How to resolve this System.IO.FileNotFoundException

I came across a similar situation after publishing a ClickOnce application, and one of my colleagues on a different domain reported that it fails to launch.

To find out what was going on, I added a try catch statement inside the MainWindow method as @BradleyDotNET mentioned in one comment on the original post, and then published again.

public MainWindow()
{
    try
    {
        InitializeComponent();
    }
    catch (Exception exc)
    {
        MessageBox.Show(exc.ToString());
    }
}

Then my colleague reported to me the exception detail, and it was a missing reference of a third party framework dll file.

Added the reference and problem solved.

How to get all table names from a database?

@Transactional
@RequestMapping(value = { "/getDatabaseTables" }, method = RequestMethod.GET)
public @ResponseBody String getDatabaseTables() throws Exception{ 

    Connection con = ((SessionImpl) sessionFactory.getCurrentSession()).connection();
    DatabaseMetaData md = con.getMetaData();
    ResultSet rs = md.getTables(null, null, "%", null);
    HashMap<String,List<String>> databaseTables = new HashMap<String,List<String>>();
    List<String> tables = new ArrayList<String>();
    String db = "";
    while (rs.next()) {
        tables.add(rs.getString(3));
        db = rs.getString(1);
    }
    List<String> database = new ArrayList<String>();
    database.add(db);
    databaseTables.put("database", database);
    Collections.reverse(tables);
    databaseTables.put("tables", tables);
    return new ObjectMapper().writeValueAsString(databaseTables);
}

@Transactional
@RequestMapping(value = { "/getTableDetails" }, method = RequestMethod.GET)
public @ResponseBody String getTableDetails(@RequestParam(value="tablename")String tablename) throws Exception{ 
    System.out.println("...tablename......"+tablename);
    Connection con = ((SessionImpl) sessionFactory.getCurrentSession()).connection();       
     Statement st = con.createStatement();
     String sql = "select * from "+tablename;
     ResultSet rs = st.executeQuery(sql);
     ResultSetMetaData metaData = rs.getMetaData();
     int rowCount = metaData.getColumnCount();    
     List<HashMap<String,String>> databaseColumns = new ArrayList<HashMap<String,String>>();
     HashMap<String,String> columnDetails = new HashMap<String,String>();
     for (int i = 0; i < rowCount; i++) {
         columnDetails = new HashMap<String,String>();
         Method method = com.mysql.jdbc.ResultSetMetaData.class.getDeclaredMethod("getField", int.class);
         method.setAccessible(true);
         com.mysql.jdbc.Field field = (com.mysql.jdbc.Field) method.invoke(metaData, i+1);
         columnDetails.put("columnName", field.getName());//metaData.getColumnName(i + 1));
         columnDetails.put("columnType", metaData.getColumnTypeName(i + 1));
         columnDetails.put("columnSize", field.getLength()+"");//metaData.getColumnDisplaySize(i + 1)+"");
         columnDetails.put("columnColl", field.getCollation());
         columnDetails.put("columnNull", ((metaData.isNullable(i + 1)==0)?"NO":"YES"));
         if (field.isPrimaryKey()) {
             columnDetails.put("columnKEY", "PRI");
         } else if(field.isMultipleKey()) {
             columnDetails.put("columnKEY", "MUL");
         } else if(field.isUniqueKey()) {
             columnDetails.put("columnKEY", "UNI");
         } else {
             columnDetails.put("columnKEY", "");
         }
         columnDetails.put("columnAINC", (field.isAutoIncrement()?"AUTO_INC":""));
         databaseColumns.add(columnDetails);
     }
    HashMap<String,List<HashMap<String,String>>> tableColumns = new HashMap<String,List<HashMap<String,String>>>();
    Collections.reverse(databaseColumns);
    tableColumns.put("columns", databaseColumns);
    return new ObjectMapper().writeValueAsString(tableColumns);
}

Smart way to truncate long strings

c_harm's answer is in my opinion the best. Please note that if you want to use

"My string".truncate(n)

you will have to use a regexp object constructor rather than a literal. Also you'll have to escape the \S when converting it.

String.prototype.truncate =
    function(n){
        var p  = new RegExp("^.{0," + n + "}[\\S]*", 'g');
        var re = this.match(p);
        var l  = re[0].length;
        var re = re[0].replace(/\s$/,'');

        if (l < this.length) return re + '&hellip;';
    };

Request exceeded the limit of 10 internal redirects due to probable configuration error

i solved this by http://willcodeforcoffee.com/2007/01/31/cakephp-error-500-too-many-redirects/ just uncomment or add this:

RewriteBase /
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]

to your .htaccess file

Re-render React component when prop changes

componentWillReceiveProps(nextProps) { // your code here}

I think that is the event you need. componentWillReceiveProps triggers whenever your component receive something through props. From there you can have your checking then do whatever you want to do.

PHP Using RegEx to get substring of a string

Unfortunately, you have a malformed url query string, so a regex technique is most appropriate. See what I mean.

There is no need for capture groups. Just match id= then forget those characters with \K, then isolate the following one or more digital characters.

Code (Demo)

$str = 'producturl.php?id=736375493?=tm';
echo preg_match('~id=\K\d+~', $str, $out) ? $out[0] : 'no match';

Output:

736375493

How to redirect to action from JavaScript method?

I struggled with this a little because I wanted to use Knockout to bind the button to the click event. Here's my button and the relevant function from inside my view model.

<a class="btn btn-secondary showBusy" data-bind="click: back">Back to Dashboard</a>

var vm = function () {
...
    self.back = function() {
        window.location.href = '@Url.Action("LicenseDashboard", "Application")';
    }
}

Moving average or running mean

Another approach to find moving average without using numpy, panda

import itertools
sample = [2, 6, 10, 8, 11, 10]
list(itertools.starmap(lambda a,b: b/a, 
               enumerate(itertools.accumulate(sample), 1)))

will print [2.0, 4.0, 6.0, 6.5, 7.4, 7.833333333333333]

asp.net mvc @Html.CheckBoxFor

Html.CheckBoxFor expects a Func<TModel, bool> as the first parameter. Therefore your lambda must return a bool, you are currently returning an instance of List<Checkboxes>:

model => model.EmploymentType

You need to iterate over the List<Checkboxes> to output each checkbox:

@for (int i = 0; i < Model.EmploymentType.Count; i++)
{
    @Html.HiddenFor(m => m.EmploymentType[i].Text)
    @Html.CheckBoxFor(m => m.EmploymentType[i].Checked, 
              new { id = string.Format("employmentType_{0}", i) })
}

How to find patterns across multiple lines using grep?

Grep is not sufficient for this operation.

pcregrep which is found in most of the modern Linux systems can be used as

pcregrep -M  'abc.*(\n|.)*efg' test.txt

where -M, --multiline allow patterns to match more than one line

There is a newer pcre2grep also. Both are provided by the PCRE project.

pcre2grep is available for Mac OS X via Mac Ports as part of port pcre2:

% sudo port install pcre2 

and via Homebrew as:

% brew install pcre

or for pcre2

% brew install pcre2

pcre2grep is also available on Linux (Ubuntu 18.04+)

$ sudo apt install pcre2-utils # PCRE2
$ sudo apt install pcregrep    # Older PCRE

Invalid date in safari

As @nizantz previously mentioned, using Date.parse() wasn't working for me in Safari. After a bit of research, I learned that the lastDateModified property for the File object has been deprecated, and is no longer supported by Safari. Using the lastModified property of the File object resolved my issues. Sure dislike it when bad info is found online.

Thanks to all who contributed to this post that assisted me in going down the path I needed to learn about my issue. Had it not been for this info, I never would have probably figured out my root issue. Maybe this will help someone else in my similar situation.

How do I filter an array with AngularJS and use a property of the filtered object as the ng-model attribute?

<div ng-repeat="subject in results.subjects | filter:{grade:'C'}">
    <input ng-model="subject.title" />
</div>

Getting an error "fopen': This function or variable may be unsafe." when compling

This is not an error, it is a warning from your Microsoft compiler.

Select your project and click "Properties" in the context menu.

In the dialog, chose Configuration Properties -> C/C++ -> Preprocessor

In the field PreprocessorDefinitions add ;_CRT_SECURE_NO_WARNINGS to turn those warnings off.

Python - round up to the nearest ten

This will round down correctly as well:

>>> n = 46
>>> rem = n % 10
>>> if rem < 5:
...     n = int(n / 10) * 10
... else:
...     n = int((n + 10) / 10) * 10
...
>>> 50

Removing display of row names from data frame

My answer is intended for comment though but since i havent got enough reputation, i think it will still be relevant as an answer and help some one.

I find datatable in library DT robust to handle rownames, and columnames

Library DT
datatable(df, rownames = FALSE)  # no row names 

refer to https://rstudio.github.io/DT/ for usage scenarios

Using find to locate files that match one of multiple patterns

This works on AIX korn shell.

find *.cbl *.dms -prune -type f -mtime -1

This is looking for *.cbl or *.dms which are 1 day old, in current directory only, skipping the sub-directories.

How to add images to README.md on GitHub?

There are 2 simple way you can do this ,

1) use HTML img tag ,

2) ![](the path where your image is saved/image-name.png)

the path would you can copy from the URL in the browser while you have opened that image. there might be an issue occur of spacing so make sure if there is any space b/w two words of path or in image name add-> %20. just like browser do.

Both of them will work , if you want to understand more you can check my github -> https://github.com/adityarawat29

PHP: how can I get file creation date?

I know this topic is super old, but, in case if someone's looking for an answer, as me, I'm posting my solution.

This solution works IF you don't mind having some extra data at the beginning of your file.

Basically, the idea is to, if file is not existing, to create it and append current date at the first line. Next, you can read the first line with fgets(fopen($file, 'r')), turn it into a DateTime object or anything (you can obviously use it raw, unless you saved it in a weird format) and voila - you have your creation date! For example my script to refresh my log file every 30 days looks like this:

if (file_exists($logfile)) {
            $now = new DateTime();
            $date_created = fgets(fopen($logfile, 'r'));
            if ($date_created == '') {
                file_put_contents($logfile, date('Y-m-d H:i:s').PHP_EOL, FILE_APPEND | LOCK_EX);
            }
            $date_created = new DateTime($date_created);
            $expiry = $date_created->modify('+ 30 days');
            if ($now >= $expiry) {
                unlink($logfile);
            }
        }

.NET DateTime to SqlDateTime Conversion

If you are checking for DBNULL, converting a SQL Datetime to a .NET DateTime should not be a problem. However, you can run into problems converting a .NET DateTime to a valid SQL DateTime.

SQL Server does not recognize dates prior to 1/1/1753. Thats the year England adopted the Gregorian Calendar. Usually checking for DateTime.MinValue is sufficient, but if you suspect that the data could have years before the 18th century, you need to make another check or use a different data type. (I often wonder what Museums use in their databases)

Checking for max date is not really necessary, SQL Server and .NET DateTime both have a max date of 12/31/9999 It may be a valid business rule but it won't cause a problem.

CSS Positioning Elements Next to each other

If you want them to be displayed side by side, why is sideContent the child of mainContent? make them siblings then use:

float:left; display:inline; width: 49%;

on both of them.

#mainContent, #sideContent {float:left; display:inline; width: 49%;}

Cross-reference (named anchor) in markdown

As we see (from the answers), there is no standard way for this; and different markdown processors would differ in their markdown extension that offer this kind of possibilities.

With pandoc, you can get what you asked for like this:

Take me to [pookie](#pookie)

...

[this is pookie]{#pookie}

This gives (with pandoc-2.9.2.1):

<p>Take me to <a href="#pookie">pookie</a></p>
<p>…</p>
<p><span id="pookie">this is pookie</span></p>

One can also make an empty span with an anchor id:

Take me to [pookie](#pookie)

...

this is pookie []{#pookie}

which would produce:

<p>Take me to <a href="#pookie">pookie</a></p>
<p>…</p>
<p>this is pookie <span id="pookie"></span></p>

Apart from this, for pandoc and for most common markdown generators, you have a simple self generated anchor in each header. (See that and other answers here for convenient ways to (auto)generate and refernce such anchors.)

Error retrieving parent for item: No resource found that matches the given name after upgrading to AppCompat v23

on module: app (Gradle)

apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

    defaultConfig {
        applicationId "com.namepack.nameappxxxxx"
        minSdkVersion 16
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:21.0.3'
}

project: nameAppXXXX (Gradle)

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.2.3'

    }
}

allprojects {
    repositories {
        jcenter()
    }
}

and edit your activity of AppCompatActivity to for example Activity:

package com.namepack.nameappxxxxx;


import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;

public class NameClass extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
    }


}

getActionBar() returns null

Try extending your Activity class from ActionBarActivity. This solved it for me. Do something like the following:

public class MyActivity extends ActionBarActivity
{
  . . .

In my case the class was extending only from Activity.

changing the owner of folder in linux

Use chown to change ownership and chmod to change rights.

use the -R option to apply the rights for all files inside of a directory too.

Note that both these commands just work for directories too. The -R option makes them also change the permissions for all files and directories inside of the directory.

For example

sudo chown -R username:group directory

will change ownership (both user and group) of all files and directories inside of directory and directory itself.

sudo chown username:group directory

will only change the permission of the folder directory but will leave the files and folders inside the directory alone.

you need to use sudo to change the ownership from root to yourself.

Edit:

Note that if you use chown user: file (Note the left-out group), it will use the default group for that user.

Also You can change the group ownership of a file or directory with the command:

chgrp group_name file/directory_name

You must be a member of the group to which you are changing ownership to.

You can find group of file as follows

# ls -l file
-rw-r--r-- 1 root family 0 2012-05-22 20:03 file

# chown sujit:friends file

User 500 is just a normal user. Typically user 500 was the first user on the system, recent changes (to /etc/login.defs) has altered the minimum user id to 1000 in many distributions, so typically 1000 is now the first (non root) user.

What you may be seeing is a system which has been upgraded from the old state to the new state and still has some processes knocking about on uid 500. You can likely change it by first checking if your distro should indeed now use 1000, and if so alter the login.defs file yourself, the renumber the user account in /etc/passwd and chown/chgrp all their files, usually in /home/, then reboot.

But in answer to your question, no, you should not really be worried about this in all likelihood. It'll be showing as "500" instead of a username because o user in /etc/passwd has a uid set of 500, that's all.

Also you can show your current numbers using id i'm willing to bet it comes back as 1000 for you.

How Can I Resolve:"can not open 'git-upload-pack' " error in eclipse?

to fix SSL issue you can also try doing this.

Download the NetworkSolutionsDVServerCA2.crt from the bitbucket server and add it to the ca-bundle.crt

ca-bundle.crt needs to be copied from the git install directory and copied to your home directory

cp -r git/mingw64/ssl/certs/ca-bundle.crt ~/

then do this. this worked for me cat NetworkSolutionsDVServerCA2.crt >> ca-bundle.crt

git config --global http.sslCAInfo ~/ca-bundle.crt

git config --global http.sslverify true

Android - Center TextView Horizontally in LinearLayout

Use android:gravity="center" in TextView instead of layout_gravity.

While, Do While, For loops in Assembly Language (emu8086)

For-loops:

For-loop in C:

for(int x = 0; x<=3; x++)
{
    //Do something!
}

The same loop in 8086 assembler:

        xor cx,cx   ; cx-register is the counter, set to 0
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        inc cx      ; Increment
        cmp cx,3    ; Compare cx to the limit
        jle loop1   ; Loop while less or equal

That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:

        mov cx,4    ; 4 iterations
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        loop loop1  ; loop instruction decrements cx and jumps to label if not 0

If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction

times 4 nop

Do-while-loops

Do-while-loop in C:

int x=1;
do{
    //Do something!
}
while(x==1)

The same loop in assembler:

        mov ax,1
loop1   nop         ; Whatever you wanna do goes here
        cmp ax,1    ; Check wether cx is 1
        je loop1    ; And loop if equal

While-loops

While-loop in C:

while(x==1){
    //Do something
}

The same loop in assembler:

        jmp loop1   ; Jump to condition first
cloop1  nop         ; Execute the content of the loop
loop1   cmp ax,1    ; Check the condition
        je cloop1   ; Jump to content of the loop if met

For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.

Working with $scope.$emit and $scope.$on

To send $scope object from one controller to another, I will discuss about $rootScope.$broadcast and $rootScope.$emit here as they are used most.

Case 1:

$rootScope.$broadcast:-

$rootScope.$broadcast('myEvent',$scope.data);//Here `myEvent` is event name

$rootScope.$on('myEvent', function(event, data) {} //listener on `myEvent` event

$rootScope listener are not destroyed automatically. You need to destroy it using $destroy. It is better to use $scope.$on as listeners on $scope are destroyed automatically i.e. as soon as $scope is destroyed.

$scope.$on('myEvent', function(event, data) {}

Or,

  var customeEventListener = $rootScope.$on('myEvent', function(event, data) {

  }
  $scope.$on('$destroy', function() {
        customeEventListener();
  });

Case 2:

$rootScope.$emit:

   $rootScope.$emit('myEvent',$scope.data);

   $rootScope.$on('myEvent', function(event, data) {}//$scope.$on not works

The major difference in $emit and $broadcast is that $rootScope.$emit event must be listened using $rootScope.$on, because the emitted event never comes down through the scope tree..
In this case also you must destroy the listener as in the case of $broadcast.

Edit:

I prefer not to use $rootScope.$broadcast + $scope.$on but use $rootScope.$emit+ $rootScope.$on. The $rootScope.$broadcast + $scope.$on combo can cause serious performance problems. That is because the event will bubble down through all scopes.

Edit 2:

The issue addressed in this answer have been resolved in angular.js version 1.2.7. $broadcast now avoids bubbling over unregistered scopes and runs just as fast as $emit.

Angular 2 two way binding using ngModel is not working

instead of ng-model you can use this code:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `<input #box (keyup)="0">
    <p>{{box.value}}</p>`,
})
export class AppComponent  {}

inside your app.component.ts

Getting Google+ profile picture url with user_id

UPDATE: Google stopped support for this method, that now returns a 404 (not found) error.


All this urls fetch the profile picture of a user:

https://www.google.com/s2/photos/profile/{user_id}
https://plus.google.com/s2/photos/profile/{user_id}
https://profiles.google.com/s2/photos/profile/{user_id}

They redirect to the same image url you get from Google API, an ugly link as
lh6.googleusercontent.com/-x1W2-XNKA-A/AAAAAAAAAAI/AAAAAAAAAAA/ooSNulbLz8U/photo.jpg

The simplest is to directly use like image source:

<img src="https://www.google.com/s2/photos/profile/{user_id}">

Otherwise to obtain exactly the same url of a Google API call you can read image headers,
for example in PHP:

$headers = get_headers("https://www.google.com/s2/photos/profile/{user_id}", 1);
echo "<img src=$headers[Location]>";

as described in article Fetch Google Plus Profile Picture using PHP.

How do I output coloured text to a Linux terminal?

I wrote a cross-platform library color_ostream for this, with the support of ANSI color, 256 color and true color, all you have to do is directly including it and changing cout to rd_cout like this.
| std | basic color | 256 color | true color | | :----: | :----: | :----: | :----: | | std::cout | color_ostream::rd_cout | color_ostream::rd256_cout | color_ostream::rdtrue_cout | | std::wcout | color_ostream::rd_wcout | color_ostream::rd256_wcout | color_ostream::rdtrue_wcout | | std::cerr | color_ostream::rd_cerr | color_ostream::rd256_cerr | color_ostream::rdtrue_cerr | | std::wcerr | color_ostream::rd_wcerr | color_ostream::rd256_wcerr | color_ostream::rdtrue_wcerr | | std::clog | color_ostream::rd_clog | color_ostream::rd256_clog | color_ostream::rdtrue_clog | | std::wclog | color_ostream::rd_wclog | color_ostream::rd256_wclog | color_ostream::rdtrue_wclog |
Here is an simple example:

//hello.cpp
#include "color_ostream.h"

using namespace color_ostream;

int main([[maybe_unused]] int argc, [[maybe_unused]] char *argv[]) {
    rd_wcout.imbue(std::locale(std::locale(),"",LC_CTYPE));
    rd_wcout << L"Hello world\n";
    rd_wcout << L"Hola Mundo\n";
    rd_wcout << L"Bonjour le monde\n";

    rd256_wcout << L"\n256 color" << std::endl;
    rd256_wcout << L"Hello world\n";
    rd256_wcout << L"Hola Mundo\n";
    rd256_wcout << L"Bonjour le monde\n";

    rdtrue_wcout << L"\ntrue color" << std::endl;
    rdtrue_wcout << L"Hello world\n";
    rdtrue_wcout << L"Hola Mundo\n";
    rdtrue_wcout << L"Bonjour le monde\n";
    return 0;
}

NULL values inside NOT IN clause

It may be concluded from answers here that NOT IN (subquery) doesn't handle nulls correctly and should be avoided in favour of NOT EXISTS. However, such a conclusion may be premature. In the following scenario, credited to Chris Date (Database Programming and Design, Vol 2 No 9, September 1989), it is NOT IN that handles nulls correctly and returns the correct result, rather than NOT EXISTS.

Consider a table sp to represent suppliers (sno) who are known to supply parts (pno) in quantity (qty). The table currently holds the following values:

      VALUES ('S1', 'P1', NULL), 
             ('S2', 'P1', 200),
             ('S3', 'P1', 1000)

Note that quantity is nullable i.e. to be able to record the fact a supplier is known to supply parts even if it is not known in what quantity.

The task is to find the suppliers who are known supply part number 'P1' but not in quantities of 1000.

The following uses NOT IN to correctly identify supplier 'S2' only:

WITH sp AS 
     ( SELECT * 
         FROM ( VALUES ( 'S1', 'P1', NULL ), 
                       ( 'S2', 'P1', 200 ),
                       ( 'S3', 'P1', 1000 ) )
              AS T ( sno, pno, qty )
     )
SELECT DISTINCT spx.sno
  FROM sp spx
 WHERE spx.pno = 'P1'
       AND 1000 NOT IN (
                        SELECT spy.qty
                          FROM sp spy
                         WHERE spy.sno = spx.sno
                               AND spy.pno = 'P1'
                       );

However, the below query uses the same general structure but with NOT EXISTS but incorrectly includes supplier 'S1' in the result (i.e. for which the quantity is null):

WITH sp AS 
     ( SELECT * 
         FROM ( VALUES ( 'S1', 'P1', NULL ), 
                       ( 'S2', 'P1', 200 ),
                       ( 'S3', 'P1', 1000 ) )
              AS T ( sno, pno, qty )
     )
SELECT DISTINCT spx.sno
  FROM sp spx
 WHERE spx.pno = 'P1'
       AND NOT EXISTS (
                       SELECT *
                         FROM sp spy
                        WHERE spy.sno = spx.sno
                              AND spy.pno = 'P1'
                              AND spy.qty = 1000
                      );

So NOT EXISTS is not the silver bullet it may have appeared!

Of course, source of the problem is the presence of nulls, therefore the 'real' solution is to eliminate those nulls.

This can be achieved (among other possible designs) using two tables:

  • sp suppliers known to supply parts
  • spq suppliers known to supply parts in known quantities

noting there should probably be a foreign key constraint where spq references sp.

The result can then be obtained using the 'minus' relational operator (being the EXCEPT keyword in Standard SQL) e.g.

WITH sp AS 
     ( SELECT * 
         FROM ( VALUES ( 'S1', 'P1' ), 
                       ( 'S2', 'P1' ),
                       ( 'S3', 'P1' ) )
              AS T ( sno, pno )
     ),
     spq AS 
     ( SELECT * 
         FROM ( VALUES ( 'S2', 'P1', 200 ),
                       ( 'S3', 'P1', 1000 ) )
              AS T ( sno, pno, qty )
     )
SELECT sno
  FROM spq
 WHERE pno = 'P1'
EXCEPT 
SELECT sno
  FROM spq
 WHERE pno = 'P1'
       AND qty = 1000;

How to downgrade Xcode to previous version?

I'm assuming you are having at least OSX 10.7, so go ahead into the applications folder (Click on Finder icon > On the Sidebar, you'll find "Applications", click on it ), delete the "Xcode" icon. That will remove Xcode from your system completely. Restart your mac.

Now go to https://developer.apple.com/download/more/ and download an older version of Xcode, as needed and install. You need an Apple ID to login to that portal.

Convert hours:minutes:seconds into total minutes in excel

Just use the formula

120 = (HOUR(A8)*3600+MINUTE(A8)*60+SECOND(A8))/60

Understanding the difference between Object.create() and new SomeFunction()

Object.create(Constructor.prototype) is the part of new Constructor

this is new Constructor implementation

// 1. define constructor function

      function myConstructor(name, age) {
        this.name = name;
        this.age = age;
      }
      myConstructor.prototype.greet = function(){
        console.log(this.name, this.age)
      };

// 2. new operator implementation

      let newOperatorWithConstructor = function(name, age) {
        const newInstance = new Object(); // empty object
        Object.setPrototypeOf(newInstance, myConstructor.prototype); // set prototype

        const bindedConstructor = myConstructor.bind(newInstance); // this binding
        bindedConstructor(name, age); // execute binded constructor function

        return newInstance; // return instance
      };

// 3. produce new instance

      const instance = new myConstructor("jun", 28);
      const instance2 = newOperatorWithConstructor("jun", 28);
      console.log(instance);
      console.log(instance2);
      

new Constructor implementation contains Object.create method

      newOperatorWithConstructor = function(name, age) {
        const newInstance = Object.create(myConstructor.prototype); // empty object, prototype chaining

        const bindedConstructor = myConstructor.bind(newInstance); // this binding
        bindedConstructor(name, age); // execute binded constructor function

        return newInstance; // return instance
      };

      console.log(newOperatorWithConstructor("jun", 28));

how to add values to an array of objects dynamically in javascript?

You have to instantiate the object first. The simplest way is:

var lab =["1","2","3"];
var val = [42,55,51,22];
var data = [];
for(var i=0; i<4; i++)  {
    data.push({label: lab[i], value: val[i]});
}

Or an other, less concise way, but closer to your original code:

for(var i=0; i<4; i++)  {
   data[i] = {};              // creates a new object
   data[i].label = lab[i];
   data[i].value = val[i];    
}

array() will not create a new array (unless you defined that function). Either Array() or new Array() or just [].

I recommend to read the MDN JavaScript Guide.

Formula to check if string is empty in Crystal Reports

If IsNull({TABLE.FIELD1}) then "NULL" +',' + {TABLE.FIELD2} else {TABLE.FIELD1} + ', ' + {TABLE.FIELD2}

Here I put NULL as string to display the string value NULL in place of the null value in the data field. Hope you understand.

Start redis-server with config file

To start redis with a config file all you need to do is specifiy the config file as an argument:

redis-server /root/config/redis.rb

Instead of using and killing PID's I would suggest creating an init script for your service

I would suggest taking a look at the Installing Redis more properly section of http://redis.io/topics/quickstart. It will walk you through setting up an init script with redis so you can just do something like service redis_server start and service redis_server stop to control your server.

I am not sure exactly what distro you are using, that article describes instructions for a Debian based distro. If you are are using a RHEL/Fedora distro let me know, I can provide you with instructions for the last couple of steps, the config file and most of the other steps will be the same.

How to fluently build JSON in Java?

I got here looking for a nice way to write rest endpoint tests with a fluent json builder. In my case I used JSONObject to construct a specialized builder. It need a bit of instrumentation, but the usage is really nice:

import lombok.SneakyThrows;
import org.json.JSONObject;

public class MemberJson extends JSONObject {

    @SneakyThrows
    public static MemberJson builder() {
        return new MemberJson();
    }

    @SneakyThrows
    public MemberJson name(String name) {
        put("name", name);
        return this;
    }

}
MemberJson.builder().name("Member").toString();

SQL How to replace values of select return?

Replace the value in select statement itself...

(CASE WHEN Mobile LIKE '966%' THEN (select REPLACE(CAST(Mobile AS nvarchar(MAX)),'966','0')) ELSE Mobile END)

Addition for BigDecimal

Just another example to add BigDecimals. Key point is that they are immutable and they can be initialized only in the constructor. Here is the code:

import java.util.*;
import java.math.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc;
        boolean first_right_number = false;
        BigDecimal initBigDecimal = BigDecimal.ZERO;
        BigDecimal add1 = BigDecimal.ZERO;
        BigDecimal add2 = BigDecimal.ZERO;

        while (!first_right_number)
        {
            System.out.print("Enter a first single numeric value: ");
            sc = new Scanner(System.in);
            if (sc.hasNextBigDecimal()) 
            {
                first_right_number = true;
                add1 = sc.nextBigDecimal();
            }
        }

        boolean second_right_number = false;
        while (!second_right_number)
        {
            System.out.print("Enter a second single numeric value: ");
            sc = new Scanner(System.in);
            if (sc.hasNextBigDecimal()) 
            {
                second_right_number = true;
                add2 = sc.nextBigDecimal();
            }
        }
        BigDecimal result = initBigDecimal.add(add1).add(add2);
        System.out.println("Sum of the 2 numbers is: " + result.toString());
    }
}

Is there a null-coalescing (Elvis) operator or safe navigation operator in javascript?

I have a solution for that, tailor it to your own needs, an excerpt from one of my libs:

    elvisStructureSeparator: '.',

    // An Elvis operator replacement. See:
    // http://coffeescript.org/ --> The Existential Operator
    // http://fantom.org/doc/docLang/Expressions.html#safeInvoke
    //
    // The fn parameter has a SPECIAL SYNTAX. E.g.
    // some.structure['with a selector like this'].value transforms to
    // 'some.structure.with a selector like this.value' as an fn parameter.
    //
    // Configurable with tulebox.elvisStructureSeparator.
    //
    // Usage examples: 
    // tulebox.elvis(scope, 'arbitrary.path.to.a.function', fnParamA, fnParamB, fnParamC);
    // tulebox.elvis(this, 'currentNode.favicon.filename');
    elvis: function (scope, fn) {
        tulebox.dbg('tulebox.elvis(' + scope + ', ' + fn + ', args...)');

        var implicitMsg = '....implicit value: undefined ';

        if (arguments.length < 2) {
            tulebox.dbg(implicitMsg + '(1)');
            return undefined;
        }

        // prepare args
        var args = [].slice.call(arguments, 2);
        if (scope === null || fn === null || scope === undefined || fn === undefined 
            || typeof fn !== 'string') {
            tulebox.dbg(implicitMsg + '(2)');
            return undefined;   
        }

        // check levels
        var levels = fn.split(tulebox.elvisStructureSeparator);
        if (levels.length < 1) {
            tulebox.dbg(implicitMsg + '(3)');
            return undefined;
        }

        var lastLevel = scope;

        for (var i = 0; i < levels.length; i++) {
            if (lastLevel[levels[i]] === undefined) {
                tulebox.dbg(implicitMsg + '(4)');
                return undefined;
            }
            lastLevel = lastLevel[levels[i]];
        }

        // real return value
        if (typeof lastLevel === 'function') {
            var ret = lastLevel.apply(scope, args);
            tulebox.dbg('....function value: ' + ret);
            return ret;
        } else {
            tulebox.dbg('....direct value: ' + lastLevel);
            return lastLevel;
        }
    },

works like a charm. Enjoy the less pain!

Query based on multiple where clauses in Firebase

Using Firebase's Query API, you might be tempted to try this:

// !!! THIS WILL NOT WORK !!!
ref
  .orderBy('genre')
  .startAt('comedy').endAt('comedy')
  .orderBy('lead')                  // !!! THIS LINE WILL RAISE AN ERROR !!!
  .startAt('Jack Nicholson').endAt('Jack Nicholson')
  .on('value', function(snapshot) { 
      console.log(snapshot.val()); 
  });

But as @RobDiMarco from Firebase says in the comments:

multiple orderBy() calls will throw an error

So my code above will not work.

I know of three approaches that will work.

1. filter most on the server, do the rest on the client

What you can do is execute one orderBy().startAt()./endAt() on the server, pull down the remaining data and filter that in JavaScript code on your client.

ref
  .orderBy('genre')
  .equalTo('comedy')
  .on('child_added', function(snapshot) { 
      var movie = snapshot.val();
      if (movie.lead == 'Jack Nicholson') {
          console.log(movie);
      }
  });

2. add a property that combines the values that you want to filter on

If that isn't good enough, you should consider modifying/expanding your data to allow your use-case. For example: you could stuff genre+lead into a single property that you just use for this filter.

"movie1": {
    "genre": "comedy",
    "name": "As good as it gets",
    "lead": "Jack Nicholson",
    "genre_lead": "comedy_Jack Nicholson"
}, //...

You're essentially building your own multi-column index that way and can query it with:

ref
  .orderBy('genre_lead')
  .equalTo('comedy_Jack Nicholson')
  .on('child_added', function(snapshot) { 
      var movie = snapshot.val();
      console.log(movie);
  });

David East has written a library called QueryBase that helps with generating such properties.

You could even do relative/range queries, let's say that you want to allow querying movies by category and year. You'd use this data structure:

"movie1": {
    "genre": "comedy",
    "name": "As good as it gets",
    "lead": "Jack Nicholson",
    "genre_year": "comedy_1997"
}, //...

And then query for comedies of the 90s with:

ref
  .orderBy('genre_year')
  .startAt('comedy_1990')
  .endAt('comedy_2000')
  .on('child_added', function(snapshot) { 
      var movie = snapshot.val();
      console.log(movie);
  });

If you need to filter on more than just the year, make sure to add the other date parts in descending order, e.g. "comedy_1997-12-25". This way the lexicographical ordering that Firebase does on string values will be the same as the chronological ordering.

This combining of values in a property can work with more than two values, but you can only do a range filter on the last value in the composite property.

A very special variant of this is implemented by the GeoFire library for Firebase. This library combines the latitude and longitude of a location into a so-called Geohash, which can then be used to do realtime range queries on Firebase.

3. create a custom index programmatically

Yet another alternative is to do what we've all done before this new Query API was added: create an index in a different node:

  "movies"
      // the same structure you have today
  "by_genre"
      "comedy"
          "by_lead"
              "Jack Nicholson"
                  "movie1"
              "Jim Carrey"
                  "movie3"
      "Horror"
          "by_lead"
              "Jack Nicholson"
                  "movie2"
      

There are probably more approaches. For example, this answer highlights an alternative tree-shaped custom index: https://stackoverflow.com/a/34105063


If none of these options work for you, but you still want to store your data in Firebase, you can also consider using its Cloud Firestore database.

Cloud Firestore can handle multiple equality filters in a single query, but only one range filter. Under the hood it essentially uses the same query model, but it's like it auto-generates the composite properties for you. See Firestore's documentation on compound queries.

Why should the static field be accessed in a static way?

Because when you access a static field, you should do so on the class (or in this case the enum). As in

MyUnits.MILLISECONDS;

Not on an instance as in

m.MILLISECONDS;

Edit To address the question of why: In Java, when you declare something as static, you are saying that it is a member of the class, not the object (hence why there is only one). Therefore it doesn't make sense to access it on the object, because that particular data member is associated with the class.

Pandas How to filter a Series

If you like a chained operation, you can also use compress function:

test = pd.Series({
383:    3.000000,
663:    1.000000,
726:    1.000000,
737:    9.000000,
833:    8.166667
})

test.compress(lambda x: x != 1)

# 383    3.000000
# 737    9.000000
# 833    8.166667
# dtype: float64

How do I test a single file using Jest?

Using npm test doesn't mean Jest is installed globally. It just means "test" is mapped to using Jest in your package.json file.

The following is what worked for me, at the root level of the project:

node_modules/.bin/jest [args]

args can be the test file you want to run or the directory containing multiple files.

How do you build a Singleton in Dart?

Here's a concise example that combines the other solutions. Accessing the singleton can be done by:

  • Using a singleton global variable that points to the instance.
  • The common Singleton.instance pattern.
  • Using the default constructor, which is a factory that returns the instance.

Note: You should implement only one of the three options so that code using the singleton is consistent.

Singleton get singleton => Singleton.instance;
ComplexSingleton get complexSingleton => ComplexSingleton._instance;

class Singleton {
  static final Singleton instance = Singleton._private();
  Singleton._private();
  factory Singleton() => instance;
}

class ComplexSingleton {
  static ComplexSingleton _instance;
  static ComplexSingleton get instance => _instance;
  static void init(arg) => _instance ??= ComplexSingleton._init(arg);

  final property;
  ComplexSingleton._init(this.property);
  factory ComplexSingleton() => _instance;
}

If you need to do complex initialization, you'll just have to do so before using the instance later in the program.

Example

void main() {
  print(identical(singleton, Singleton.instance));        // true
  print(identical(singleton, Singleton()));               // true
  print(complexSingleton == null);                        // true
  ComplexSingleton.init(0); 
  print(complexSingleton == null);                        // false
  print(identical(complexSingleton, ComplexSingleton())); // true
}

What's the difference between .NET Core, .NET Framework, and Xamarin?

This is how Microsoft explains it:

.NET Framework, .NET Core, Xamarin

.NET Framework is the "full" or "traditional" flavor of .NET that's distributed with Windows. Use this when you are building a desktop Windows or UWP app, or working with older ASP.NET 4.6+.

.NET Core is cross-platform .NET that runs on Windows, Mac, and Linux. Use this when you want to build console or web apps that can run on any platform, including inside Docker containers. This does not include UWP/desktop apps currently.

Xamarin is used for building mobile apps that can run on iOS, Android, or Windows Phone devices.

Xamarin usually runs on top of Mono, which is a version of .NET that was built for cross-platform support before Microsoft decided to officially go cross-platform with .NET Core. Like Xamarin, the Unity platform also runs on top of Mono.


A common point of confusion is where ASP.NET Core fits in. ASP.NET Core can run on top of either .NET Framework (Windows) or .NET Core (cross-platform), as detailed in this answer: Difference between ASP.NET Core (.NET Core) and ASP.NET Core (.NET Framework)

VSCode regex find & replace submatch math?

For beginners, the accepted answer is correct, but a little terse if you're not that familiar with either VSC or Regex.

So, in case this is your first contact with either:

To find and modify text,

  1. In the "Find" step, you can use regex with "capturing groups," e.g. I want to find (group1) and (group2), using parentheses. This would find the same text as I want to find group1 and group2, but with the difference that you can then reference group1 and group2 in the next step:

  2. In the "Replace" step, you can refer to the capturing groups via $1, $2 etc, so you could change the sentence to I found $1 and $2 having a picnic, which would output I found group1 and group2 having a picnic.

Notes:

  • Instead of just a string, anything inside or outside the () can be a regular expression.

  • $0 refers to the whole match

The maximum value for an int type in Go

From math lib: https://github.com/golang/go/blob/master/src/math/const.go#L39

package main

import (
    "fmt"
    "math"
)

func main() {
    fmt.Printf("max int64: %d\n", math.MaxInt64)
}

How to terminate a python subprocess launched with shell=True

Use a process group so as to enable sending a signal to all the process in the groups. For that, you should attach a session id to the parent process of the spawned/child processes, which is a shell in your case. This will make it the group leader of the processes. So now, when a signal is sent to the process group leader, it's transmitted to all of the child processes of this group.

Here's the code:

import os
import signal
import subprocess

# The os.setsid() is passed in the argument preexec_fn so
# it's run after the fork() and before  exec() to run the shell.
pro = subprocess.Popen(cmd, stdout=subprocess.PIPE, 
                       shell=True, preexec_fn=os.setsid) 

os.killpg(os.getpgid(pro.pid), signal.SIGTERM)  # Send the signal to all the process groups

Should I put input elements inside a label element?

One thing you need to consider is the interaction of checkbox and radio inputs with javascript.

Using below structure:

<label>
  <input onclick="controlCheckbox()" type="checkbox" checked="checkboxState" />
  <span>Label text</span>
</label>

When user clicks on "Label text" controlCheckbox() function will be fired once.

But when input tag is clicked the controlCheckbox() function may be fired twice in some older browsers. That's because both input and label tags trigger onclick event attached to checkbox.

Then you may have some bugs in your checkboxState.

I've run into this issue lately on IE11. I'm not sure if modern browsers have troubles with this structure.

How to exclude subdirectories in the destination while using /mir /xd switch in robocopy

Rather than creating empty directories in source to exclude, you can supply the full destination path to the /XD switch to have the destination directories untouched

robocopy "%SOURCE_PATH%" "%DEST_PATH%" /MIR /XD "%DEST_PATH%"\hq04s2dba301

What is DOM Event delegation?

Event delegation makes use of two often overlooked features of JavaScript events: event bubbling and the target element.When an event is triggered on an element, for example a mouse click on a button, the same event is also triggered on all of that element’s ancestors. This process is known as event bubbling; the event bubbles up from the originating element to the top of the DOM tree.

Imagine an HTML table with 10 columns and 100 rows in which you want something to happen when the user clicks on a table cell. For example, I once had to make each cell of a table of that size editable when clicked. Adding event handlers to each of the 1000 cells would be a major performance problem and, potentially, a source of browser-crashing memory leaks. Instead, using event delegation, you would add only one event handler to the table element, intercept the click event and determine which cell was clicked.

MySql: is it possible to 'SUM IF' or to 'COUNT IF'?

It is worth noting that you can build upon Gavin Toweys answer by using multiple fields from across your query such as

SUM(table.field = 1 AND table2.field = 2)

You can also use this syntax for COUNT and I am sure other functions as well.

SQL: How to get the count of each distinct value in a column?

SELECT
  category,
  COUNT(*) AS `num`
FROM
  posts
GROUP BY
  category

How to convert a file to utf-8 in Python?

You can use the codecs module, like this:

import codecs
BLOCKSIZE = 1048576 # or some other, desired size in bytes
with codecs.open(sourceFileName, "r", "your-source-encoding") as sourceFile:
    with codecs.open(targetFileName, "w", "utf-8") as targetFile:
        while True:
            contents = sourceFile.read(BLOCKSIZE)
            if not contents:
                break
            targetFile.write(contents)

EDIT: added BLOCKSIZE parameter to control file chunk size.

How to set corner radius of imageView?

in swift 3 'CGRectGetWidth' has been replaced by property 'CGRect.width'

    view.layer.cornerRadius = view.frame.width/4.0
    view.clipsToBounds = true

Relative path to absolute path in C#?

Have you tried Server.MapPath method. Here is an example

string relative_path = "/Content/img/Upload/Reports/59/44A0446_59-1.jpg";
string absolute_path = Server.MapPath(relative_path);
//will be c:\users\.....\Content\img\Upload\Reports\59\44A0446_59-1.jpg

Unknown version of Tomcat was specified in Eclipse

Just in case... Apache Tomcat 8.5.X is not compatible with Apache Tomcat 8.0 server selection in eclipse. And it gives this error.

PHP Excel Header

The problem is you typed the wrong file extension for excel file. you used .xsl instead of xls.

I know i came in late but it can help future readers of this post.

jQuery - Trigger event when an element is removed from the DOM

You can bind to the DOMNodeRemoved event (part of DOM Level 3 WC3 spec).

Works in IE9, latest releases of Firefox and Chrome.

Example:

$(document).bind("DOMNodeRemoved", function(e)
{
    alert("Removed: " + e.target.nodeName);
});

You can also get notification when elements are inserting by binding to DOMNodeInserted

What's the difference between isset() and array_key_exists()?

The PHP function array_key_exists() determines if a particular key, or numerical index, exists for an element of an array. However, if you want to determine if a key exists and is associated with a value, the PHP language construct isset() can tell you that (and that the value is not null). array_key_exists()cannot return information about the value of a key/index.

Difference between CLOB and BLOB from DB2 and Oracle Perspective?

BLOB is for binary data (videos, images, documents, other)

CLOB is for large text data (text)

Maximum size on MySQL 2GB

Maximum size on Oracle 128TB

How can I convert a string with dot and comma into a float in Python

Here's a simple way I wrote up for you. :)

>>> number = '123,456,789.908'.replace(',', '') # '123456789.908'
>>> float(number)
123456789.908

How to make bootstrap column height to 100% row height?

@Alan's answer will do what you're looking for, but this solution fails when you use the responsive capabilities of Bootstrap. In your case, you're using the xs sizes so you won't notice, but if you used anything else (e.g. col-sm, col-md, etc), you'd understand.

Another approach is to play with margins and padding. See the updated fiddle: http://jsfiddle.net/jz8j247x/1/

.left-side {
  background-color: blue;
  padding-bottom: 1000px;
  margin-bottom: -1000px;
  height: 100%;
}
.something {
  height: 100%;
  background-color: red;
  padding-bottom: 1000px;
  margin-bottom: -1000px;
  height: 100%;
}
.row {
  background-color: green;
  overflow: hidden;
}

Environment variable in Jenkins Pipeline

You can access the same environment variables from groovy using the same names (e.g. JOB_NAME or env.JOB_NAME).

From the documentation:

Environment variables are accessible from Groovy code as env.VARNAME or simply as VARNAME. You can write to such properties as well (only using the env. prefix):

env.MYTOOL_VERSION = '1.33'
node {
  sh '/usr/local/mytool-$MYTOOL_VERSION/bin/start'
}

These definitions will also be available via the REST API during the build or after its completion, and from upstream Pipeline builds using the build step.

For the rest of the documentation, click the "Pipeline Syntax" link from any Pipeline job enter image description here

jQuery DatePicker with today as maxDate

In recent version, The following works fine:

    $('.selector').datetimepicker({
        maxDate: new Date()
    });

maxDate accepts a Date object as parameter.

The following found in documentation:

Multiple types supported:

  • Date: A date object containing the minimum date.

  • Number: A number of days from today. For example 2 represents two days from today and -1 represents yesterday.

  • String: A string in the format defined by the dateFormat option, or a relative date. Relative dates must contain value and period pairs; valid periods are "y" for years, "m" for months, "w" for weeks, and "d" for days. For example, "+1m +7d" represents one month and seven days from today.

How to get the wsdl file from a webservice's URL

Its only possible to get the WSDL if the webservice is configured to deliver it. Therefor you have to specify a serviceBehavior and enable httpGetEnabled:

<serviceBehaviors>
    <behavior name="BindingBehavior">
        <serviceMetadata httpGetEnabled="true" />
        <serviceDebug includeExceptionDetailInFaults="true" />
    </behavior>
</serviceBehaviors>

In case the webservice is only accessible via https you have to enable httpsGetEnabled instead of httpGetEnabled.

Split and join C# string

Well, here is my "answer". It uses the fact that String.Split can be told hold many items it should split to (which I found lacking in the other answers):

string theString = "Some Very Large String Here";
var array = theString.Split(new [] { ' ' }, 2); // return at most 2 parts
// note: be sure to check it's not an empty array
string firstElem = array[0];
// note: be sure to check length first
string restOfArray = array[1];

This is very similar to the Substring method, just by a different means.

Retrieving the last record in each group - MySQL

Use your subquery to return the correct grouping, because you're halfway there.

Try this:

select
    a.*
from
    messages a
    inner join 
        (select name, max(id) as maxid from messages group by name) as b on
        a.id = b.maxid

If it's not id you want the max of:

select
    a.*
from
    messages a
    inner join 
        (select name, max(other_col) as other_col 
         from messages group by name) as b on
        a.name = b.name
        and a.other_col = b.other_col

This way, you avoid correlated subqueries and/or ordering in your subqueries, which tend to be very slow/inefficient.

PHP Include for HTML?

You don't need to be echoing the info within the php file. A php include will automatically include any HTML within that file.

Make sure you're actually using a index file with a .php extension, .html won't work with php includes. (Unless you're telling your server to treat .html files otherwise)

Make sure your paths are correctly set up. From your description, the way you've set it up your header.php/navbar.php/image.php files should be in your root directory. So your root directory should look like this:

index.php
navbar.php
image.php
header.php

Otherwise if those PHP files are in a folder called /includes/, it should look like so:

<?php include ('includes/headings.php'); ?>

Invalid column name sql error

Code To insert Data in Access Db using c#

Code:-

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace access_db_csharp
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
   public SqlConnection con = new SqlConnection(@"Place Your connection string");
            
           private void Savebutton_Click(object sender, EventArgs e)
    {
         SqlCommand cmd = new SqlCommand("insert into  Data (Name,PhoneNo,Address) values(@parameter1,@parameter2,@parameter3)",con);
                cmd.Parameters.AddWithValue("@parameter1", (textBox1.Text));
                cmd.Parameters.AddWithValue("@parameter2", textBox2.Text);
                cmd.Parameters.AddWithValue("@parameter3", (textBox4.Text));
                cmd.ExecuteNonQuery();

                }

    private void Form1_Load(object sender, EventArgs e)
    {
        con.ConnectionString = connectionstring;
        con.Open();
    }
}
}

How to show one layout on top of the other programmatically in my case?

The answer, given by Alexandru is working quite nice. As he said, it is important that this "accessor"-view is added as the last element. Here is some code which did the trick for me:

        ...

        ...

            </LinearLayout>

        </LinearLayout>

    </FrameLayout>

</LinearLayout>

<!-- place a FrameLayout (match_parent) as the last child -->
<FrameLayout
    android:id="@+id/icon_frame_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</FrameLayout>

</TabHost>

in Java:

final MaterialDialog materialDialog = (MaterialDialog) dialogInterface;

FrameLayout frameLayout = (FrameLayout) materialDialog
        .findViewById(R.id.icon_frame_container);

frameLayout.setOnTouchListener(
        new OnSwipeTouchListener(ShowCardActivity.this) {

How to test for $null array in PowerShell

if($foo -eq $null) { "yes" } else { "no" }

help about_comparison_operators 

displays help and includes this text:

All comparison operators except the containment operators (-contains, -notcontains) and type operators (-is, -isnot) return a Boolean value when the input to the operator (the value on the left side of the operator) is a single value (a scalar). When the input is a collection of values, the containment operators and the type operators return any matching values. If there are no matches in a collection, these operators do not return anything. The containment operators and type operators always return a Boolean value.

Best way to store chat messages in a database?

If you can avoid the need for concurrent writes to a single file, it sounds like you do not need a database to store the chat messages.

Just append the conversation to a text file (1 file per user\conversation). and have a directory/ file structure

Here's a simplified view of the file structure:

chat-1-bob.txt
        201101011029, hi
        201101011030, fine thanks.

chat-1-jen.txt
        201101011030, how are you?
        201101011035, have you spoken to bill recently?

chat-2-bob.txt
        201101021200, hi
        201101021222, about 12:22
chat-2-bill.txt
        201101021201, Hey Bob,
        201101021203, what time do you call this?

You would then only need to store the userid, conversation id (guid ?) & a reference to the file name.

I think you will find it hard to get a more simple scaleable solution.

You can use LOAD_FILE to get the data too see: http://dev.mysql.com/doc/refman/5.0/en/string-functions.html

If you have a requirement to rebuild a conversation you will need to put a value (date time) alongside your sent chat message (in the file) to allow you to merge & sort the files, but at this point it is probably a good idea to consider using a database.

writing a batch file that opens a chrome URL

It's very simple. Just try:

start chrome https://www.google.co.in/

it will open the Google page in the Chrome browser.

If you wish to open the page in Firefox, try:

start firefox https://www.google.co.in/

Have Fun!

Get css top value as number not as string?

You can use the parseInt() function to convert the string to a number, e.g:

parseInt($('#elem').css('top'));

Update: (as suggested by Ben): You should give the radix too:

parseInt($('#elem').css('top'), 10);

Forces it to be parsed as a decimal number, otherwise strings beginning with '0' might be parsed as an octal number (might depend on the browser used).

How to enable multidexing with the new Android Multidex support library

just adding this snipped in the build.gradle also works fine

android {
   compileSdkVersion 22
   buildToolsVersion "23.0.0"

     defaultConfig {
         minSdkVersion 14 //lower than 14 doesn't support multidex
         targetSdkVersion 22

         **// Enabling multidex support.
         **multiDexEnabled true****
     }
}

How to keep Docker container running after starting services?

I just had the same problem and I found out that if you are running your container with the -t and -d flag, it keeps running.

docker run -td <image>

Here is what the flags do (according to docker run --help):

-d, --detach=false         Run container in background and print container ID
-t, --tty=false            Allocate a pseudo-TTY

The most important one is the -t flag. -d just lets you run the container in the background.

How to use Monitor (DDMS) tool to debug application

As far as I know, currently (Android Studio 2.3) there is no way to do this.

As per Android Studio documentation:

"Note: Only one debugger can be connected to your device at a time."

When you attempt to connect Android Device Monitor it disconnects Android Studio's debug session and vice versa, when you attempt to connect Android Studio's debugger, it disconnects Android Device Monitor.

Fortunately the new version of Android Studio (3.0) will feature a Device File Explorer that will allow you to pull files from within Android Studio without the need to open the Android Device Monitor which should resolve the problem.

What exactly is RESTful programming?

REST is a distributed systems (such as WWW) software architecture style, you can imagine that it is a well-designed Web application rules: a group of Internet Web pages (a virtual state machine), in which hyperlink by clicking link (state transition), the result is the next Web page (which means the next state of the application).

REST describes the network system consists of three parts:

  1. data elements (resource, resource identifier, representation)
  2. connectors (client, server, cache, resolver, tunnel)
  3. components (origin server, gateway, proxy, user agent)

REST strictly meet the following conditions:

  1. Status of the application functionality is split into resources
  2. Each resource used as hyperlinks positioning syntax (ie, in the WWW URI)
  3. All resources share a uniform interface between the client with the resource transition state, including:
    1. A limited set of well-defined operations (ie in HTTP GET / POST / PUT / DELETE)
    2. A limited set of content format content types, which may include executable code (ie, in the WWW Javascript)

Difference between save and saveAndFlush in Spring data jpa

On saveAndFlush, changes will be flushed to DB immediately in this command. With save, this is not necessarily true, and might stay just in memory, until flush or commit commands are issued.

But be aware, that even if you flush the changes in transaction and do not commit them, the changes still won't be visible to the outside transactions until the commit in this transaction.

In your case, you probably use some sort of transactions mechanism, which issues commit command for you if everything works out fine.

How do synchronized static methods work in Java and can I use it for loading Hibernate entities?

By using synchronized on a static method lock you will synchronize the class methods and attributes ( as opposed to instance methods and attributes )

So your assumption is correct.

I am wondering if making the method synchronized is the right approach to ensure thread-safety.

Not really. You should let your RDBMS do that work instead. They are good at this kind of stuff.

The only thing you will get by synchronizing the access to the database is to make your application terribly slow. Further more, in the code you posted you're building a Session Factory each time, that way, your application will spend more time accessing the DB than performing the actual job.

Imagine the following scenario:

Client A and B attempt to insert different information into record X of table T.

With your approach the only thing you're getting is to make sure one is called after the other, when this would happen anyway in the DB, because the RDBMS will prevent them from inserting half information from A and half from B at the same time. The result will be the same but only 5 times ( or more ) slower.

Probably it could be better to take a look at the "Transactions and Concurrency" chapter in the Hibernate documentation. Most of the times the problems you're trying to solve, have been solved already and a much better way.

Java LinkedHashMap get first or last entry

It's a bit dirty, but you can override the removeEldestEntry method of LinkedHashMap, which it might suit you to do as a private anonymous member:

private Splat eldest = null;
private LinkedHashMap<Integer, Splat> pastFutures = new LinkedHashMap<Integer, Splat>() {

    @Override
    protected boolean removeEldestEntry(Map.Entry<Integer, Splat> eldest) {

        eldest = eldest.getValue();
        return false;
    }
};

So you will always be able to get the first entry at your eldest member. It will be updated every time you perform a put.

It should also be easy to override put and set youngest ...

    @Override
    public Splat put(Integer key, Splat value) {

        youngest = value;
        return super.put(key, value);
    }

It all breaks down when you start removing entries though; haven't figured out a way to kludge that.

It's very annoying that you can't otherwise get access to head or tail in a sensible way ...

adding onclick event to dynamically added button?

try this:

but.onclick = callJavascriptFunction;

or create the button by wrapping it with another element and use innerHTML:

var span = document.createElement('span');
span.innerHTML = '<button id="but' + inc +'" onclick="callJavascriptFunction()" />';

C# refresh DataGridView when updating or inserted on another form

my datagridview is editonEnter mode . so it refresh only after i leave cell or after i revisit and exit cell twice.

to trigger this iimedately . i unfocus from datagridview . then refocus it.

 this.SelectNextControl(dgv1,true,true,false,true);    
 Application.DoEvents();    //this does magic
 dgv1.Focus();

Reading HTML content from a UIWebView

Note that the NSString stringWithContentsOfURL will report a totally different user-agent string than the UIWebView making the same request. So if your server is user-agent aware, and sending back different html depending on who is asking for it, you may not get correct results this way.

Also note that the @"document.body.innerHTML" mentioned above will only display what is in the body tag. If you use @"document.all[0].innerHTML" you will get both head and body. Which is still not the complete contents of the UIWebView, since it will not get back the !doctype or html tags, but it is a lot closer.

How can I disable inherited css styles?

The simple answer is to change

div.rounded div div div {
    padding: 10px;
}

to

div.rounded div div div {
    background-image: none;
    padding: 10px;
}

The reason is because when you make a rule for div.rounded div div it means every div element nested inside a div inside a div with a class of rounded, regardless of nesting.

If you want to only target a div that's the direct descendent, you can use the syntax div.rounded div > div (though this is only supported by more recent browsers).

Incidentally, you can usually simplify this method to use only two divs (one each for either top and bottom or left and right), by using a technique called Sliding Doors.

Key Shortcut for Eclipse Imports

CTRL + 1 can also be used which will suggest to import.

Checking if a double (or float) is NaN in C++

It seems to me that the best truly cross-platform approach would be to use a union and to test the bit pattern of the double to check for NaNs.

I have not thoroughly tested this solution, and there may be a more efficient way of working with the bit patterns, but I think that it should work.

#include <stdint.h>
#include <stdio.h>

union NaN
{
    uint64_t bits;
    double num;
};

int main()
{
    //Test if a double is NaN
    double d = 0.0 / 0.0;
    union NaN n;
    n.num = d;
    if((n.bits | 0x800FFFFFFFFFFFFF) == 0xFFFFFFFFFFFFFFFF)
    {
        printf("NaN: %f", d);
    }

    return 0;
}

How to Navigate from one View Controller to another using Swift

SWIFT 3.01

let secondViewController = self.storyboard?.instantiateViewController(withIdentifier: "Conversation_VC") as! Conversation_VC
self.navigationController?.pushViewController(secondViewController, animated: true)

Get data from fs.readFile

sync and async file reading way:

//fs module to read file in sync and async way

var fs = require('fs'),
    filePath = './sample_files/sample_css.css';

// this for async way
/*fs.readFile(filePath, 'utf8', function (err, data) {
    if (err) throw err;
    console.log(data);
});*/

//this is sync way
var css = fs.readFileSync(filePath, 'utf8');
console.log(css);

Node Cheat Available at read_file.

Deleting Elements in an Array if Element is a Certain value VBA

here is a sample of code using the CopyMemory function to do the job.

It is supposedly "much faster" (depending of the size and type of the array...).

i am not the author, but i tested it :

Sub RemoveArrayElement_Str(ByRef AryVar() As String, ByVal RemoveWhich As Long) 

'// The size of the array elements
'// In the case of string arrays, they are
'// simply 32 bit pointers to BSTR's.
Dim byteLen As Byte

'// String pointers are 4 bytes
byteLen = 4

'// The copymemory operation is not necessary unless
'// we are working with an array element that is not
'// at the end of the array
If RemoveWhich < UBound(AryVar) Then
    '// Copy the block of string pointers starting at
    ' the position after the
    '// removed item back one spot.
    CopyMemory ByVal VarPtr(AryVar(RemoveWhich)), ByVal _
        VarPtr(AryVar(RemoveWhich + 1)), (byteLen) * _
        (UBound(AryVar) - RemoveWhich)
End If

'// If we are removing the last array element
'// just deinitialize the array
'// otherwise chop the array down by one.
If UBound(AryVar) = LBound(AryVar) Then
    Erase AryVar
Else
    ReDim Preserve AryVar(LBound(AryVar) To UBound(AryVar) - 1)
End If
End Sub

ORA-12514 TNS:listener does not currently know of service requested in connect descriptor

My issue was resolved by replacing the'SID' in URL with 'service name' and correct host.

How to use MySQLdb with Python and Django in OSX 10.6?

I encountered similar situations like yours that I am using python3.7 and django 2.1 in virtualenv on mac osx. Try to run command:

pip install mysql-python
pip install pymysql

And edit __init__.py file in your project folder and add following:

import pymysql

pymysql.install_as_MySQLdb()

Then run: python3 manage.py runserver or python manage.py runserver

See whether an item appears more than once in a database column

try this:

select salesid,count (salesid) from AXDelNotesNoTracking group by salesid having count (salesid) >1

When should you use 'friend' in C++?

With regards to operator<< and operator>> there is no good reason to make these operators friends. It is true that they should not be member functions, but they don't need to be friends, either.

The best thing to do is create public print(ostream&) and read(istream&) functions. Then, write the operator<< and operator>> in terms of those functions. This gives the added benefit of allowing you to make those functions virtual, which provides virtual serialization.

Reading e-mails from Outlook with Python through MAPI

I had the same problem you did - didn't find much that worked. The following code, however, works like a charm.

import win32com.client

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")

inbox = outlook.GetDefaultFolder(6) # "6" refers to the index of a folder - in this case,
                                    # the inbox. You can change that number to reference
                                    # any other folder
messages = inbox.Items
message = messages.GetLast()
body_content = message.body
print body_content

How to use template module with different set of variables?

I had a similar problem to solve, here is a simple solution of how to pass variables to template files, the trick is to write the template file taking advantage of the variable. You need to create a dictionary (list is also possible), which holds the set of variables corresponding to each of the file. Then within the template file access them.

see below:

the template file: test_file.j2
# {{ ansible_managed }} created by [email protected]

{% set dkey  = (item | splitext)[0]  %}
{% set fname = test_vars[dkey].name  %}
{% set fip   = test_vars[dkey].ip    %}
{% set fport = test_vars[dkey].port  %}
filename: {{ fname }}
ip address: {{ fip }}
port: {{ fport }}

the playbook

---
#
# file: template_test.yml
# author: [email protected]
#
# description: playbook to demonstrate passing variables to template files
#
# this playbook will create 3 files from a single template, with different
# variables passed for each of the invocation
#
# usage:
# ansible-playbook -i "localhost," template_test.yml

- name: template variables testing
  hosts: all
  gather_facts: false

  vars:
    ansible_connection: local
    dest_dir: "/tmp/ansible_template_test/"
    test_files:
      - file_01.txt
      - file_02.txt
      - file_03.txt
    test_vars:
      file_01:
        name: file_01.txt
        ip: 10.0.0.1
        port: 8001
      file_02:
        name: file_02.txt
        ip: 10.0.0.2
        port: 8002
      file_03:
        name: file_03.txt
        ip: 10.0.0.3
        port: 8003

  tasks:
    - name: copy the files
      template:
        src: test_file.j2
        dest: "{{ dest_dir }}/{{ item }}"
      with_items:
        - "{{ test_files }}"

Is log(n!) = T(n·log(n))?

http://en.wikipedia.org/wiki/Stirling%27s_approximation Stirling approximation might help you. It is really helpful in dealing with problems on factorials related to huge numbers of the order of 10^10 and above.

enter image description here

How to import XML file into MySQL database table using XML_LOAD(); function

Since ID is auto increment, you can also specify ID=NULL as,

LOAD XML LOCAL INFILE '/pathtofile/file.xml' INTO TABLE my_tablename SET ID=NULL;

Get integer value from string in swift

8:1 Odds(*)

var stringNumb: String = "1357"
var someNumb = Int(stringNumb)

or

var stringNumb: String = "1357"
var someNumb:Int? = Int(stringNumb)

Int(String) returns an optional Int?, not an Int.


Safe use: do not explicitly unwrap

let unwrapped:Int = Int(stringNumb) ?? 0

or

if let stringNumb:Int = stringNumb { ... }

(*) None of the answers actually addressed why var someNumb: Int = Int(stringNumb) was not working.

What is dynamic programming?

Here is a simple python code example of Recursive, Top-down, Bottom-up approach for Fibonacci series:

Recursive: O(2n)

def fib_recursive(n):
    if n == 1 or n == 2:
        return 1
    else:
        return fib_recursive(n-1) + fib_recursive(n-2)


print(fib_recursive(40))

Top-down: O(n) Efficient for larger input

def fib_memoize_or_top_down(n, mem):
    if mem[n] is not 0:
        return mem[n]
    else:
        mem[n] = fib_memoize_or_top_down(n-1, mem) + fib_memoize_or_top_down(n-2, mem)
        return mem[n]


n = 40
mem = [0] * (n+1)
mem[1] = 1
mem[2] = 1
print(fib_memoize_or_top_down(n, mem))

Bottom-up: O(n) For simplicity and small input sizes

def fib_bottom_up(n):
    mem = [0] * (n+1)
    mem[1] = 1
    mem[2] = 1
    if n == 1 or n == 2:
        return 1

    for i in range(3, n+1):
        mem[i] = mem[i-1] + mem[i-2]

    return mem[n]


print(fib_bottom_up(40))

How to remove extension from string (only real extension!)

This works when there is multiple parts to an extension and is both short and efficient:

function removeExt($path)
{
    $basename = basename($path);
    return strpos($basename, '.') === false ? $path : substr($path, 0, - strlen($basename) + strlen(explode('.', $basename)[0]));
}

echo removeExt('https://example.com/file.php');
// https://example.com/file
echo removeExt('https://example.com/file.tar.gz');
// https://example.com/file
echo removeExt('file.tar.gz');
// file
echo removeExt('file');
// file

Finding the length of an integer in C

int intlen(int integer){
    int a;
    for(a = 1; integer /= 10; a++);
    return a;
}

Bundler: Command not found

I got this error rbenv: bundle: command not found after cloning an old rails project I had built a couple on months ago. here is how I went about it: To install a specific version of bundler or just run the following command to install the latest available bundler:

run gem install bundler

then I installed the exact version of bundler I wanted with this command:

$ gem install bundler -v "$(grep -A 1 "BUNDLED WITH" Gemfile.lock | tail -n 1)"

[check this article for more details](https://www.aloucaslabs.com/miniposts/rbenv-bundle-command-not-found#:~:text=When%20you%20get%20the%20rbenv,to%20install%20the%20Bundler%20gem check this article for more details

get the listen to work by issuing this command

echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p

Where's my JSON data in my incoming Django request?

Using Angular you should add header to request or add it to module config headers: {'Content-Type': 'application/x-www-form-urlencoded'}

$http({
    url: url,
    method: method,
    timeout: timeout,
    data: data,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})

Javascript String to int conversion

If you are sure id.substring(indexPos) is a number, you can do it like so:

var number = Number(id.substring(indexPos)) + 1;

Otherwise I suggest checking if the Number function evaluates correctly.

Maven in Eclipse: step by step installation

I have just include Maven integration plug-in with Eclipse:

Just follow the bellow steps:

In eclipse, from upper menu item select- Help ->click on Install New Software..-> then click on Add button.

set the MavenAPI at name text box and http://download.eclipse.org/technology/m2e/releases at location text box.

press OK and select the Maven project and install by clicking next.

How to add/update child entities when updating a parent entity in EF

Because the model that gets posted to the WebApi controller is detached from any entity-framework (EF) context, the only option is to load the object graph (parent including its children) from the database and compare which children have been added, deleted or updated. (Unless you would track the changes with your own tracking mechanism during the detached state (in the browser or wherever) which in my opinion is more complex than the following.) It could look like this:

public void Update(UpdateParentModel model)
{
    var existingParent = _dbContext.Parents
        .Where(p => p.Id == model.Id)
        .Include(p => p.Children)
        .SingleOrDefault();

    if (existingParent != null)
    {
        // Update parent
        _dbContext.Entry(existingParent).CurrentValues.SetValues(model);

        // Delete children
        foreach (var existingChild in existingParent.Children.ToList())
        {
            if (!model.Children.Any(c => c.Id == existingChild.Id))
                _dbContext.Children.Remove(existingChild);
        }

        // Update and Insert children
        foreach (var childModel in model.Children)
        {
            var existingChild = existingParent.Children
                .Where(c => c.Id == childModel.Id && c.Id != default(int))
                .SingleOrDefault();

            if (existingChild != null)
                // Update child
                _dbContext.Entry(existingChild).CurrentValues.SetValues(childModel);
            else
            {
                // Insert child
                var newChild = new Child
                {
                    Data = childModel.Data,
                    //...
                };
                existingParent.Children.Add(newChild);
            }
        }

        _dbContext.SaveChanges();
    }
}

...CurrentValues.SetValues can take any object and maps property values to the attached entity based on the property name. If the property names in your model are different from the names in the entity you can't use this method and must assign the values one by one.

Compare integer in bash, unary operator expected

Your piece of script works just great. Are you sure you are not assigning anything else before the if to "i"?

A common mistake is also not to leave a space after and before the square brackets.

Android. WebView and loadData

use this: String customHtml =text ;

           wb.loadDataWithBaseURL(null,customHtml,"text/html", "UTF-8", null);

What is __stdcall?

__stdcall is the calling convention used for the function. This tells the compiler the rules that apply for setting up the stack, pushing arguments and getting a return value.

There are a number of other calling conventions, __cdecl, __thiscall, __fastcall and the wonderfully named __declspec(naked). __stdcall is the standard calling convention for Win32 system calls.

Wikipedia covers the details.

It primarily matters when you are calling a function outside of your code (e.g. an OS API) or the OS is calling you (as is the case here with WinMain). If the compiler doesn't know the correct calling convention then you will likely get very strange crashes as the stack will not be managed correctly.

Display a angular variable in my html page

In your template, you have access to all the variables that are members of the current $scope. So, tobedone should be $scope.tobedone, and then you can display it with {{tobedone}}, or [[tobedone]] in your case.

Python - converting a string of numbers into a list of int

You can also use list comprehension on splitted string

[ int(x) for x in example_string.split(',') ]

jQuery .on('change', function() {} not triggering for dynamically created inputs

You can use 'input' event, that occurs when an element gets user input.

$(document).on('input', '#input_id', function() {
  // this will fire all possible change actions
});

documentation from w3

Decode HTML entities in Python string?

I had a similar encoding issue. I used the normalize() method. I was getting a Unicode error using the pandas .to_html() method when exporting my data frame to an .html file in another directory. I ended up doing this and it worked...

    import unicodedata 

The dataframe object can be whatever you like, let's call it table...

    table = pd.DataFrame(data,columns=['Name','Team','OVR / POT'])
    table.index+= 1

encode table data so that we can export it to out .html file in templates folder(this can be whatever location you wish :))

     #this is where the magic happens
     html_data=unicodedata.normalize('NFKD',table.to_html()).encode('ascii','ignore')

export normalized string to html file

    file = open("templates/home.html","w") 

    file.write(html_data) 

    file.close() 

Reference: unicodedata documentation

If statement within Where clause

CASE might help you out:

SELECT t.first_name,
       t.last_name,
       t.employid,
       t.status
  FROM employeetable t
 WHERE t.status = (CASE WHEN status_flag = STATUS_ACTIVE THEN 'A'
                        WHEN status_flag = STATUS_INACTIVE THEN 'T'
                        ELSE null END)
   AND t.business_unit = (CASE WHEN source_flag = SOURCE_FUNCTION THEN 'production'
                               WHEN source_flag = SOURCE_USER THEN 'users'
                               ELSE null END)
   AND t.first_name LIKE firstname
   AND t.last_name LIKE lastname
   AND t.employid LIKE employeeid;

The CASE statement evaluates multiple conditions to produce a single value. So, in the first usage, I check the value of status_flag, returning 'A', 'T' or null depending on what it's value is, and compare that to t.status. I do the same for the business_unit column with a second CASE statement.

Storing Images in DB - Yea or Nay?

Another benefit of storing the images in the file system is that you don't have to do anything special to have the client cache them...

...unless of course the image isn't accessible via the document root (e.g. authentication barrier), in which case you'll need to check the cache-control headers your code is sending.

Mipmap drawables for icons

Since I was looking for an clarifying answer to this to determine the right type for notification icons, I'd like to add this clear statement to the topic. It's from http://developer.android.com/tools/help/image-asset-studio.html#saving

Note: Launcher icon files reside in a different location from that of other icons. They are located in the mipmap/ folder. All other icon files reside in the drawable/ folder of your project.

Spring Boot application.properties value not populating

Actually, For me below works fine.

@Component
public class MyBean {

   public static String prop;

   @Value("${some.prop}")
   public void setProp(String prop) {
      this.prop= prop;
   }

   public MyBean() {

   }

   @PostConstruct
   public void init() {
      System.out.println("================== " + prop + "================== ");
   }

}

Now whereever i want, just invoke

MyBean.prop

it will return value.

how to have two headings on the same line in html

The following code will allow you to have two headings on the same line, the first left-aligned and the second right-aligned, and has the added advantage of keeping both headings on the same baseline.

The HTML Part:

<h1 class="text-left-right">
    <span class="left-text">Heading Goes Here</span>
    <span class="byline">Byline here</span>
</h1>

And the CSS:

.text-left-right {
    text-align: right;
    position: relative;
}
.left-text {
    left: 0;
    position: absolute;
}
.byline {
    font-size: 16px;
    color: rgba(140, 140, 140, 1);
}

Typescript empty object for a typed variable

Note that using const user = {} as UserType just provides intellisense but at runtime user is empty object {} and has no property inside. that means user.Email will give undefined instead of ""

type UserType = {
    Username: string;
    Email: string;
}

So, use class with constructor for actually creating objects with default properties.

type UserType = {
  Username: string;
  Email: string;
};

class User implements UserType {
  constructor() {
    this.Username = "";
    this.Email = "";
  }

  Username: string;
  Email: string;
}

const myUser = new User();
console.log(myUser); // output: {Username: "", Email: ""}
console.log("val: "+myUser.Email); // output: ""

You can also use interface instead of type

interface UserType {
  Username: string;
  Email: string;
};

...and rest of code remains same.


Actually, you can even skip the constructor part and use it like this:

class User implements UserType {
      Username = ""; // will be added to new obj
      Email: string; // will not be added
}

const myUser = new User();
console.log(myUser); // output: {Username: ""}

Can I add jars to maven 2 build classpath without installing them?

This doesn't answer how to add them to your POM, and may be a no brainer, but would just adding the lib dir to your classpath work? I know that is what I do when I need an external jar that I don't want to add to my Maven repos.

Hope this helps.

How to run a script file remotely using SSH

If you want to execute a local script remotely without saving that script remotely you can do it like this:

cat local_script.sh | ssh user@remotehost 'bash -'

It works like a charm for me.

I do that even from Windows to Linux given that you have MSYS installed on your Windows computer.

Prevent Default on Form Submit jQuery

$('#cpa-form input[name="Next"]').on('click', function(e){
    e.preventDefault();
});

Escaping single quotes in JavaScript string for JavaScript evaluation

Only this worked for me:

searchKeyword.replace(/'/g, "\\\'");//searchKeyword contains "d'av"

So, the result variable will contain "d\'av".

I don't know why with the RegEx didn't work, maybe because of the JS framework that I'm using (Backbone.js)

Increment value in mysql update query

Who needs to update string and numbers SET @a = 0; UPDATE obj_disposition SET CODE = CONCAT('CD_', @a:=@a+1);

Changing precision of numeric column in Oracle

If the table is compressed this will work:

alter table EVAPP_FEES add AMOUNT_TEMP NUMBER(14,2);

update EVAPP_FEES set AMOUNT_TEMP = AMOUNT;

update EVAPP_FEES set AMOUNT = null;

alter table EVAPP_FEES modify AMOUNT NUMBER(14,2);

update EVAPP_FEES set AMOUNT = AMOUNT_TEMP;

alter table EVAPP_FEES move nocompress;

alter table EVAPP_FEES drop column AMOUNT_TEMP;

alter table EVAPP_FEES compress;

Check if event exists on element

I wrote a plugin called hasEventListener which exactly does that.

Hope this helps.

mysql error 1364 Field doesn't have a default values

Before every insert action I added below line and solved my issue,

SET SQL_MODE = '';

I'm not sure if this is the best solution,

SET SQL_MODE = ''; INSERT INTO  `mytable` (  `field1` ,  `field2`) VALUES ('value1',  'value2');

using facebook sdk in Android studio

Facebook has indeed added the SDK to the Maven Central repositories. To configure your project using the maven repo's instance, you'll need to do 2 things:

  1. In your projects top-level build.gradle file, add the Maven Central repositories. Mine looks like this:

    repositories {
        jcenter()       // This is the default repo
        mavenCentral()  //  This is the Maven Central repo
    }
    
  2. In the app-level build.grade file, add the Facebook sdk dependency:

    dependencies {
    
        compile 'com.facebook.android:facebook-android-sdk:4.5.0' // Adjust the version accordingly
        // All your other dependencies.
    }
    

You can also adjust the specific Facebook SDK version as well. For a list of available versions in the maven repository click this link.

Fully custom validation error message with Rails

In the custom validation method use:

errors.add(:base, "Custom error message")

as add_to_base has been deprecated.

errors.add_to_base("Custom error message")

jQuery post() with serialize and extra data

You could have the form contain the additional data as hidden fields which you would set right before sending the AJAX request to the corresponding values.

Another possibility consists into using this little gem to serialize your form into a javascript object (instead of string) and add the missing data:

var data = $('#myForm').serializeObject();
// now add some additional stuff
data['wordlist'] = wordlist;
$.post('/page.php', data);

Aliases in Windows command prompt

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

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

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

alias nameOfYourAlias commands to run 

And after that you can type in comman line

nameOfYourAlias 

this will execute

commands to run 

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

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

And now I run sublime as

subl index.html

How to pass List from Controller to View in MVC 3

You can use the dynamic object ViewBag to pass data from Controllers to Views.

Add the following to your controller:

ViewBag.MyList = myList;

Then you can acces it from your view:

@ViewBag.MyList

// e.g.
@foreach (var item in ViewBag.MyList) { ... }

Regex Letters, Numbers, Dashes, and Underscores

Your expression should already match dashes, because the final - will not be interpreted as a range operator (since the range has no end). To add underscores as well, try:

([A-Za-z0-9_-]+)

Difference between SET autocommit=1 and START TRANSACTION in mysql (Have I missed something?)

Being aware of the transaction (autocommit, explicit and implicit) handling for your database can save you from having to restore data from a backup.

Transactions control data manipulation statement(s) to ensure they are atomic. Being "atomic" means the transaction either occurs, or it does not. The only way to signal the completion of the transaction to database is by using either a COMMIT or ROLLBACK statement (per ANSI-92, which sadly did not include syntax for creating/beginning a transaction so it is vendor specific). COMMIT applies the changes (if any) made within the transaction. ROLLBACK disregards whatever actions took place within the transaction - highly desirable when an UPDATE/DELETE statement does something unintended.

Typically individual DML (Insert, Update, Delete) statements are performed in an autocommit transaction - they are committed as soon as the statement successfully completes. Which means there's no opportunity to roll back the database to the state prior to the statement having been run in cases like yours. When something goes wrong, the only restoration option available is to reconstruct the data from a backup (providing one exists). In MySQL, autocommit is on by default for InnoDB - MyISAM doesn't support transactions. It can be disabled by using:

SET autocommit = 0

An explicit transaction is when statement(s) are wrapped within an explicitly defined transaction code block - for MySQL, that's START TRANSACTION. It also requires an explicitly made COMMIT or ROLLBACK statement at the end of the transaction. Nested transactions is beyond the scope of this topic.

Implicit transactions are slightly different from explicit ones. Implicit transactions do not require explicity defining a transaction. However, like explicit transactions they require a COMMIT or ROLLBACK statement to be supplied.

Conclusion

Explicit transactions are the most ideal solution - they require a statement, COMMIT or ROLLBACK, to finalize the transaction, and what is happening is clearly stated for others to read should there be a need. Implicit transactions are OK if working with the database interactively, but COMMIT statements should only be specified once results have been tested & thoroughly determined to be valid.

That means you should use:

SET autocommit = 0;

START TRANSACTION;
  UPDATE ...;

...and only use COMMIT; when the results are correct.

That said, UPDATE and DELETE statements typically only return the number of rows affected, not specific details. Convert such statements into SELECT statements & review the results to ensure correctness prior to attempting the UPDATE/DELETE statement.

Addendum

DDL (Data Definition Language) statements are automatically committed - they do not require a COMMIT statement. IE: Table, index, stored procedure, database, and view creation or alteration statements.

How to write data to a JSON file using Javascript

You have to be clear on what you mean by "JSON".

Some people use the term JSON incorrectly to refer to a plain old JavaScript object, such as [{a: 1}]. This one happens to be an array. If you want to add a new element to the array, just push it, as in

var arr = [{a: 1}];
arr.push({b: 2});

< [{a: 1}, {b: 2}]

The word JSON may also be used to refer to a string which is encoded in JSON format:

var json = '[{"a": 1}]';

Note the (single) quotation marks indicating that this is a string. If you have such a string that you obtained from somewhere, you need to first parse it into a JavaScript object, using JSON.parse:

var obj = JSON.parse(json);

Now you can manipulate the object any way you want, including push as shown above. If you then want to put it back into a JSON string, then you use JSON.stringify:

var new_json = JSON.stringify(obj.push({b: 2}));
'[{"a": 1}, {"b": 1}]'

JSON is also used as a common way to format data for transmission of data to and from a server, where it can be saved (persisted). This is where ajax comes in. Ajax is used both to obtain data, often in JSON format, from a server, and/or to send data in JSON format up to to the server. If you received a response from an ajax request which is JSON format, you may need to JSON.parse it as described above. Then you can manipulate the object, put it back into JSON format with JSON.stringify, and use another ajax call to send the data to the server for storage or other manipulation.

You use the term "JSON file". Normally, the word "file" is used to refer to a physical file on some device (not a string you are dealing with in your code, or a JavaScript object). The browser has no access to physical files on your machine. It cannot read or write them. Actually, the browser does not even really have the notion of a "file". Thus, you cannot just read or write some JSON file on your local machine. If you are sending JSON to and from a server, then of course, the server might be storing the JSON as a file, but more likely the server would be constructing the JSON based on some ajax request, based on data it retrieves from a database, or decoding the JSON in some ajax request, and then storing the relevant data back into its database.

Do you really have a "JSON file", and if so, where does it exist and where did you get it from? Do you have a JSON-format string, that you need to parse, mainpulate, and turn back into a new JSON-format string? Do you need to get JSON from the server, and modify it and then send it back to the server? Or is your "JSON file" actually just a JavaScript object, that you simply need to manipulate with normal JavaScript logic?

Property getters and setters

To elaborate on GoZoner's answer:

Your real issue here is that you are recursively calling your getter.

var x:Int
    {
        set
        {
            x = newValue * 2 // This isn't a problem
        }
        get {
            return x / 2 // Here is your real issue, you are recursively calling 
                         // your x property's getter
        }
    }

Like the code comment suggests above, you are infinitely calling the x property's getter, which will continue to execute until you get a EXC_BAD_ACCESS code (you can see the spinner in the bottom right corner of your Xcode's playground environment).

Consider the example from the Swift documentation:

struct Point {
    var x = 0.0, y = 0.0
}
struct Size {
    var width = 0.0, height = 0.0
}
struct AlternativeRect {
    var origin = Point()
    var size = Size()
    var center: Point {
        get {
            let centerX = origin.x + (size.width / 2)
            let centerY = origin.y + (size.height / 2)
            return Point(x: centerX, y: centerY)
        }
        set {
            origin.x = newValue.x - (size.width / 2)
            origin.y = newValue.y - (size.height / 2)
        }
    }
}

Notice how the center computed property never modifies or returns itself in the variable's declaration.

Laravel - Pass more than one variable to view

For passing multiple array data from controller to view, try it. It is working. In this example, I am passing subject details from a table and subject details contain category id, the details like name if category id is fetched from another table category.

$category = Category::all();
$category = Category::pluck('name', 'id');
$item = Subject::find($id);
return View::make('subject.edit')->with(array('item'=>$item, 'category'=>$category));

Run cron job only if it isn't already running

This one never failed me:

one.sh:

LFILE=/tmp/one-`echo "$@" | md5sum | cut -d\  -f1`.pid
if [ -e ${LFILE} ] && kill -0 `cat ${LFILE}`; then
   exit
fi

trap "rm -f ${LFILE}; exit" INT TERM EXIT
echo $$ > ${LFILE}

$@

rm -f ${LFILE}

cron job:

* * * * * /path/to/one.sh <command>

phpMyAdmin on MySQL 8.0

 mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'rootpassword';

Login through the command line, it will work after that.

How does spring.jpa.hibernate.ddl-auto property exactly work in Spring?

For the record, the spring.jpa.hibernate.ddl-auto property is Spring Data JPA specific and is their way to specify a value that will eventually be passed to Hibernate under the property it knows, hibernate.hbm2ddl.auto.

The values create, create-drop, validate, and update basically influence how the schema tool management will manipulate the database schema at startup.

For example, the update operation will query the JDBC driver's API to get the database metadata and then Hibernate compares the object model it creates based on reading your annotated classes or HBM XML mappings and will attempt to adjust the schema on-the-fly.

The update operation for example will attempt to add new columns, constraints, etc but will never remove a column or constraint that may have existed previously but no longer does as part of the object model from a prior run.

Typically in test case scenarios, you'll likely use create-drop so that you create your schema, your test case adds some mock data, you run your tests, and then during the test case cleanup, the schema objects are dropped, leaving an empty database.

In development, it's often common to see developers use update to automatically modify the schema to add new additions upon restart. But again understand, this does not remove a column or constraint that may exist from previous executions that is no longer necessary.

In production, it's often highly recommended you use none or simply don't specify this property. That is because it's common practice for DBAs to review migration scripts for database changes, particularly if your database is shared across multiple services and applications.

RS256 vs HS256: What's the difference?

short answer, specific to OAuth2,

  • HS256 user client secret to generate the token signature and same secret is required to validate the token in back-end. So you should have a copy of that secret in your back-end server to verify the signature.
  • RS256 use public key encryption to sign the token.Signature(hash) will create using private key and it can verify using public key. So, no need of private key or client secret to store in back-end server, but back-end server will fetch the public key from openid configuration url in your tenant (https://[tenant]/.well-known/openid-configuration) to verify the token. KID parameter inside the access_toekn will use to detect the correct key(public) from openid-configuration.

combining results of two select statements

While it is possible to combine the results, I would advise against doing so.

You have two fundamentally different types of queries that return a different number of rows, a different number of columns and different types of data. It would be best to leave it as it is - two separate queries.

Remove substring from the string

If you only have one occurrence of the target string you can use:

str[target] = ''

or

str.sub(target, '')

If you have multiple occurrences of target use:

str.gsub(target, '')

For instance:

asdf = 'foo bar'
asdf['bar'] = ''
asdf #=> "foo "

asdf = 'foo bar'
asdf.sub('bar', '') #=> "foo "
asdf = asdf + asdf #=> "foo barfoo bar"
asdf.gsub('bar', '') #=> "foo foo "

If you need to do in-place substitutions use the "!" versions of gsub! and sub!.

Can I pass an array as arguments to a method with variable arguments in Java?

Yes, a T... is only a syntactic sugar for a T[].

JLS 8.4.1 Format parameters

The last formal parameter in a list is special; it may be a variable arity parameter, indicated by an elipsis following the type.

If the last formal parameter is a variable arity parameter of type T, it is considered to define a formal parameter of type T[]. The method is then a variable arity method. Otherwise, it is a fixed arity method. Invocations of a variable arity method may contain more actual argument expressions than formal parameters. All the actual argument expressions that do not correspond to the formal parameters preceding the variable arity parameter will be evaluated and the results stored into an array that will be passed to the method invocation.

Here's an example to illustrate:

public static String ezFormat(Object... args) {
    String format = new String(new char[args.length])
        .replace("\0", "[ %s ]");
    return String.format(format, args);
}
public static void main(String... args) {
    System.out.println(ezFormat("A", "B", "C"));
    // prints "[ A ][ B ][ C ]"
}

And yes, the above main method is valid, because again, String... is just String[]. Also, because arrays are covariant, a String[] is an Object[], so you can also call ezFormat(args) either way.

See also


Varargs gotchas #1: passing null

How varargs are resolved is quite complicated, and sometimes it does things that may surprise you.

Consider this example:

static void count(Object... objs) {
    System.out.println(objs.length);
}

count(null, null, null); // prints "3"
count(null, null); // prints "2"
count(null); // throws java.lang.NullPointerException!!!

Due to how varargs are resolved, the last statement invokes with objs = null, which of course would cause NullPointerException with objs.length. If you want to give one null argument to a varargs parameter, you can do either of the following:

count(new Object[] { null }); // prints "1"
count((Object) null); // prints "1"

Related questions

The following is a sample of some of the questions people have asked when dealing with varargs:


Vararg gotchas #2: adding extra arguments

As you've found out, the following doesn't "work":

    String[] myArgs = { "A", "B", "C" };
    System.out.println(ezFormat(myArgs, "Z"));
    // prints "[ [Ljava.lang.String;@13c5982 ][ Z ]"

Because of the way varargs work, ezFormat actually gets 2 arguments, the first being a String[], the second being a String. If you're passing an array to varargs, and you want its elements to be recognized as individual arguments, and you also need to add an extra argument, then you have no choice but to create another array that accommodates the extra element.

Here are some useful helper methods:

static <T> T[] append(T[] arr, T lastElement) {
    final int N = arr.length;
    arr = java.util.Arrays.copyOf(arr, N+1);
    arr[N] = lastElement;
    return arr;
}
static <T> T[] prepend(T[] arr, T firstElement) {
    final int N = arr.length;
    arr = java.util.Arrays.copyOf(arr, N+1);
    System.arraycopy(arr, 0, arr, 1, N);
    arr[0] = firstElement;
    return arr;
}

Now you can do the following:

    String[] myArgs = { "A", "B", "C" };
    System.out.println(ezFormat(append(myArgs, "Z")));
    // prints "[ A ][ B ][ C ][ Z ]"

    System.out.println(ezFormat(prepend(myArgs, "Z")));
    // prints "[ Z ][ A ][ B ][ C ]"

Varargs gotchas #3: passing an array of primitives

It doesn't "work":

    int[] myNumbers = { 1, 2, 3 };
    System.out.println(ezFormat(myNumbers));
    // prints "[ [I@13c5982 ]"

Varargs only works with reference types. Autoboxing does not apply to array of primitives. The following works:

    Integer[] myNumbers = { 1, 2, 3 };
    System.out.println(ezFormat(myNumbers));
    // prints "[ 1 ][ 2 ][ 3 ]"

How to change line color in EditText

Use this method.. and modify it according to ur view names. This code works great.

 private boolean validateMobilenumber() {
            if (mobilenumber.getText().toString().trim().isEmpty() || mobilenumber.getText().toString().length() < 10) {
                input_layout_mobilenumber.setErrorEnabled(true);
                input_layout_mobilenumber.setError(getString(R.string.err_msg_mobilenumber));
               // requestFocus(mobilenumber);
                return false;
            } else {
                input_layout_mobilenumber.setError(null);
                input_layout_mobilenumber.setErrorEnabled(false);
                mobilenumber.setBackground(mobilenumber.getBackground().getConstantState().newDrawable());
            }

How to create a custom scrollbar on a div (Facebook style)

This link should get you started. Long story short, a div that has been styled to look like a scrollbar is used to catch click-and-drag events. Wired up to these events are methods that scroll the contents of another div which is set to an arbitrary height and typically has a css rule of overflow:scroll (there are variants on the css rules but you get the idea).

I'm all about the learning experience -- but after you've learned how it works, I recommend using a library (of which there are many) to do it. It's one of those "don't reinvent" things...

Difference between Pragma and Cache-Control headers?

There is no difference, except that Pragma is only defined as applicable to the requests by the client, whereas Cache-Control may be used by both the requests of the clients and the replies of the servers.

So, as far as standards go, they can only be compared from the perspective of the client making a requests and the server receiving a request from the client. The http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.32 defines the scenario as follows:

HTTP/1.1 caches SHOULD treat "Pragma: no-cache" as if the client had sent "Cache-Control: no-cache". No new Pragma directives will be defined in HTTP.

  Note: because the meaning of "Pragma: no-cache as a response
  header field is not actually specified, it does not provide a
  reliable replacement for "Cache-Control: no-cache" in a response

The way I would read the above:

  • if you're writing a client and need no-cache:

    • just use Pragma: no-cache in your requests, since you may not know if Cache-Control is supported by the server;
    • but in replies, to decide on whether to cache, check for Cache-Control
  • if you're writing a server:

    • in parsing requests from the clients, check for Cache-Control; if not found, check for Pragma: no-cache, and execute the Cache-Control: no-cache logic;
    • in replies, provide Cache-Control.

Of course, reality might be different from what's written or implied in the RFC!

How to get build time stamp from Jenkins build variables?

NOTE: This changed in Jenkins 1.597, Please see here for more info regarding the migration

You should be able to view all the global environment variables that are available during the build by navigating to https://<your-jenkins>/env-vars.html.

Replace https://<your-jenkins>/ with the URL you use to get to Jenkins webpage (for example, it could be http://localhost:8080/env-vars.html).

One of the environment variables is :

BUILD_ID
    The current build id, such as "2005-08-22_23-59-59" (YYYY-MM-DD_hh-mm-ss)

If you use jenkins editable email notification, you should be able to use ${ENV, var="BUILD_ID"} in the subject line of your email.

Check if null Boolean is true results in exception

Use the Apache BooleanUtils.

(If peak performance is the most important priority in your project then look at one of the other answers for a native solution that doesn't require including an external library.)

Don't reinvent the wheel. Leverage what's already been built and use isTrue():

BooleanUtils.isTrue( bool );

Checks if a Boolean value is true, handling null by returning false.

If you're not limited to the libraries you're "allowed" to include, there are a bunch of great helper functions for all sorts of use-cases, including Booleans and Strings. I suggest you peruse the various Apache libraries and see what they already offer.

How can I install Visual Studio Code extensions offline?

Now you can download an extension directly in the "Resources" section, there's a "Download extension" link, I hope this information is still useful.

What's the Linq to SQL equivalent to TOP or LIMIT/OFFSET?

@Janei: my first comment here is about your sample ;)

I think if you do like this, you want to take 4, then applying the sort on these 4.

var dados =  from d in dc.tbl_News.Take(4) 
                orderby d.idNews descending
                select new 
                {
                    d.idNews,
                    d.titleNews,
                    d.textNews,
                    d.dateNews,
                    d.imgNewsThumb
                };

Different than sorting whole tbl_News by idNews descending and then taking 4

var dados =  (from d in dc.tbl_News
                orderby d.idNews descending
                select new 
                {
                    d.idNews,
                    d.titleNews,
                    d.textNews,
                    d.dateNews,
                    d.imgNewsThumb
                }).Take(4);

no ? results may be different.

What do Clustered and Non clustered index actually mean?

A very simple, non-technical rule-of-thumb would be that clustered indexes are usually used for your primary key (or, at least, a unique column) and that non-clustered are used for other situations (maybe a foreign key). Indeed, SQL Server will by default create a clustered index on your primary key column(s). As you will have learnt, the clustered index relates to the way data is physically sorted on disk, which means it's a good all-round choice for most situations.

How to extract this specific substring in SQL Server?

An alternative to the answer provided by @Marc

SELECT SUBSTRING(LEFT(YOUR_FIELD, CHARINDEX('[', YOUR_FIELD) - 1), CHARINDEX(';', YOUR_FIELD) + 1, 100)
FROM YOUR_TABLE
WHERE CHARINDEX('[', YOUR_FIELD) > 0 AND
    CHARINDEX(';', YOUR_FIELD) > 0;

This makes sure the delimiters exist, and solves an issue with the currently accepted answer where doing the LEFT last is working with the position of the last delimiter in the original string, rather than the revised substring.

How to print a certain line of a file with PowerShell?

To reduce memory consumption and to speed up the search you may use -ReadCount option of Get-Content cmdlet (https://technet.microsoft.com/ru-ru/library/hh849787.aspx).

This may save hours when you working with large files.

Here is an example:

$n = 60699010
$src = 'hugefile.csv'
$batch = 100
$timer = [Diagnostics.Stopwatch]::StartNew()

$count = 0
Get-Content $src -ReadCount $batch -TotalCount $n | %  { 
    $count += $_.Length
    if ($count -ge $n ) {
        $_[($n - $count + $_.Length - 1)]
    }
}

$timer.Stop()
$timer.Elapsed

This prints $n'th line and elapsed time.

Underline text in UIlabel

NSMutableAttributedString *text = [self.myUILabel.attributedText mutableCopy];
[text addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:NSMakeRange(0, text.length)];
self.myUILabel.attributedText = text;

Convert INT to FLOAT in SQL

In oracle db there is a trick for casting int to float (I suppose, it should also work in mysql):

select myintfield + 0.0 as myfloatfield from mytable

While @Heximal's answer works, I don't personally recommend it.

This is because it uses implicit casting. Although you didn't type CAST, either the SUM() or the 0.0 need to be cast to be the same data-types, before the + can happen. In this case the order of precedence is in your favour, and you get a float on both sides, and a float as a result of the +. But SUM(aFloatField) + 0 does not yield an INT, because the 0 is being implicitly cast to a FLOAT.

I find that in most programming cases, it is much preferable to be explicit. Don't leave things to chance, confusion, or interpretation.

If you want to be explicit, I would use the following.

CAST(SUM(sl.parts) AS FLOAT) * cp.price
-- using MySQL CAST FLOAT  requires 8.0

I won't discuss whether NUMERIC or FLOAT *(fixed point, instead of floating point)* is more appropriate, when it comes to rounding errors, etc. I'll just let you google that if you need to, but FLOAT is so massively misused that there is a lot to read about the subject already out there.

You can try the following to see what happens...

CAST(SUM(sl.parts) AS NUMERIC(10,4)) * CAST(cp.price AS NUMERIC(10,4))

What are some examples of commonly used practices for naming git branches?

Why does it take three branches/merges for every task? Can you explain more about that?

If you use a bug tracking system you can use the bug number as part of the branch name. This will keep the branch names unique, and you can prefix them with a short and descriptive word or two to keep them human readable, like "ResizeWindow-43523". It also helps make things easier when you go to clean up branches, since you can look up the associated bug. This is how I usually name my branches.

Since these branches are eventually getting merged back into master, you should be safe deleting them after you merge. Unless you're merging with --squash, the entire history of the branch will still exist should you ever need it.

What's the u prefix in a Python string?

All strings meant for humans should use u"".

I found that the following mindset helps a lot when dealing with Python strings: All Python manifest strings should use the u"" syntax. The "" syntax is for byte arrays, only.

Before the bashing begins, let me explain. Most Python programs start out with using "" for strings. But then they need to support documentation off the Internet, so they start using "".decode and all of a sudden they are getting exceptions everywhere about decoding this and that - all because of the use of "" for strings. In this case, Unicode does act like a virus and will wreak havoc.

But, if you follow my rule, you won't have this infection (because you will already be infected).

How to redirect a page using onclick event in php?

Why do people keep confusing php and javascript?

PHP is SERVER SIDE
JAVASCRIPT (like onclick) is CLIENT SIDE

You will have to use just javascript to redirect. Otherwise if you want PHP involved you can use an AJAX call to log a hit or whatever you like to send back a URL or additional detail.

'list' object has no attribute 'shape'

firstly u have to import numpy library (refer code for making a numpy array) shape only gives the output only if the variable is attribute of numpy library .in other words it must be a np.array or any other data structure of numpy. Eg.

`>>> import numpy
>>> a=numpy.array([[1,1],[1,1]])
>>> a.shape
(2, 2)`

Why is Dictionary preferred over Hashtable in C#?

The Extensive Examination of Data Structures Using C# article on MSDN states that there is also a difference in the collision resolution strategy:

The Hashtable class uses a technique referred to as rehashing.

Rehashing works as follows: there is a set of hash different functions, H1 ... Hn, and when inserting or retrieving an item from the hash table, initially the H1 hash function is used. If this leads to a collision, H2 is tried instead, and onwards up to Hn if needed.

The Dictionary uses a technique referred to as chaining.

With rehashing, in the event of a collision the hash is recomputed, and the new slot corresponding to a hash is tried. With chaining, however, a secondary data structure is utilized to hold any collisions. Specifically, each slot in the Dictionary has an array of elements that map to that bucket. In the event of a collision, the colliding element is prepended to the bucket's list.

How to secure phpMyAdmin

The biggest threat is that an attacker could leverage a vulnerability such as; directory traversal, or using SQL Injection to call load_file() to read the plain text username/password in the configuration file and then Login using phpmyadmin or over tcp port 3306. As a pentester I have used this attack pattern to compromise a system.

Here is a great way to lock down phpmyadmin:

  • DO NOT ALLOW REMOTE ROOT LOGINS! Instead phpmyadmin can be configured to use "Cookie Auth" to limit what user can access the system. If you need some root privileges, create a custom account that can add/drop/create but doesn't have grant or file_priv.
  • Remove file_priv permissions from every account. file_priv is one of the most dangerous privileges in MySQL because it allows an attacker to read files or upload a backdoor.
  • Whitelist IP address who have access to the phpmyadmin interface. Here is an example .htaccess reulset:
Order deny,allow
Deny from all
allow from 199.166.210.1
  • Do not have a predictable file location like: http://127.0.0.1/phpmyadmin. Vulnerability scanners like Nessus/Nikto/Acunetix/w3af will scan for this.

  • Firewall off tcp port 3306 so that it cannot be accessed by an attacker.

  • Use HTTPS, otherwise data and passwords can be leaked to an attacker. If you don't want to fork out the $30 for a cert, then use a self-signed. You'll accept it once, and even if it was changed due to a MITM you'll be notified.

Detecting scroll direction

I personally use this code to detect scroll direction in javascript... Just you have to define a variable to store lastscrollvalue and then use this if&else

let lastscrollvalue;

function headeronscroll() {

    // document on which scroll event will occur
    var a = document.querySelector('.refcontainer'); 

    if (lastscrollvalue == undefined) {

        lastscrollvalue = a.scrollTop;

        // sets lastscrollvalue
    } else if (a.scrollTop > lastscrollvalue) {

        // downscroll rules will be here
        lastscrollvalue = a.scrollTop;

    } else if (a.scrollTop < lastscrollvalue) {

        // upscroll rules will be here
        lastscrollvalue = a.scrollTop;

    }
}

SQL Server AS statement aliased column within WHERE statement

I am not sure why you cannot use "lat" but, if you must you can rename the columns in a derived table.

select latitude from (SELECT lat AS latitude FROM poi_table) p where latitude < 500

Can I set variables to undefined or pass undefined as an argument?

The for if (something) and if (!something) is commonly used to check if something is defined or not defined. For example:

if (document.getElementById)

The identifier is converted to a boolean value, so undefined is interpreted as false. There are of course other values (like 0 and '') that also are interpreted as false, but either the identifier should not reasonably have such a value or you are happy with treating such a value the same as undefined.

Javascript has a delete operator that can be used to delete a member of an object. Depending on the scope of a variable (i.e. if it's global or not) you can delete it to make it undefined.

There is no undefined keyword that you can use as an undefined literal. You can omit parameters in a function call to make them undefined, but that can only be used by sending less paramters to the function, you can't omit a parameter in the middle.

I am getting an "Invalid Host header" message when connecting to webpack-dev-server remotely

I just experienced this issue while using the Windows Subsystem for Linux (WSL2), so I will also share this solution.

My objective was to render the output from webpack both at wsl:3000 and localhost:3000, thereby creating an alternate local endpoint.

As you might expect, this initially caused the "Invalid Host header" error to arise. Nothing seemed to help until I added the devServer config option shown below.


module.exports = {
  //...
  devServer: {
    proxy: [
      {
        context: ['http://wsl:3000'],
        target: 'http://localhost:3000',
      },
    ],
  },
}

This fixed the "bug" without introducing any security risks.

Reference: webpack DevServer docs

Highlight text similar to grep, but don't filter out text

You can use my highlight script from https://github.com/kepkin/dev-shell-essentials

It's better than grep cause you can highlight each match with it's own color.

$ command_here | highlight green "input" | highlight red "output"

enter image description here

how to change color of TextinputLayout's label and edittext underline android

Add this attribute in Edittext tag and enjoy:

 android:backgroundTint="@color/colorWhite"

How to git-svn clone the last n revisions from a Subversion repository?

... 7 years later, in the desert, a tumbleweed blows by ...

I wasn't satisfied with the accepted answer so I created some scripts to do this for you available on Github. These should help anyone who wants to use git svn clone but doesn't want to clone the entire repository and doesn't want to hunt for a specific revision to clone from in the middle of the history (maybe you're cloning a bunch of repos). Here we can just clone the last N revisions:

Use git svn clone to clone the last 50 revisions

# -u    The SVN URL to clone
# -l    The limit of revisions
# -o    The output directory

./git-svn-cloneback.sh -u https://server/project/trunk -l 50 -o myproj --authors-file=svn-authors.txt

Find the previous N revision from an SVN repo

# -u    The SVN URL to clone
# -l    The limit of revisions

./svn-lookback.sh -u https://server/project/trunk -l 5     

What is the ellipsis (...) for in this method signature?

The way to use the ellipsis or varargs inside the method is as if it were an array:

public void PrintWithEllipsis(String...setOfStrings) {
    for (String s : setOfStrings)
        System.out.println(s);
}

This method can be called as following:

obj.PrintWithEllipsis(); // prints nothing
obj.PrintWithEllipsis("first"); // prints "first"
obj.PrintWithEllipsis("first", "second"); // prints "first\nsecond"

Inside PrintWithEllipsis, the type of setOfStrings is an array of String. So you could save the compiler some work and pass an array:

String[] argsVar = {"first", "second"};
obj.PrintWithEllipsis(argsVar);

For varargs methods, a sequence parameter is treated as being an array of the same type. So if two signatures differ only in that one declares a sequence and the other an array, as in this example:

void process(String[] s){}
void process(String...s){}

then a compile-time error occurs.

Source: The Java Programming Language specification, where the technical term is variable arity parameter rather than the common term varargs.

Difference between const reference and normal parameter

There are three methods you can pass values in the function

  1. Pass by value

    void f(int n){
        n = n + 10;
    }
    
    int main(){
        int x = 3;
        f(x);
        cout << x << endl;
    }
    

    Output: 3. Disadvantage: When parameter x pass through f function then compiler creates a copy in memory in of x. So wastage of memory.

  2. Pass by reference

    void f(int& n){
        n = n + 10;
    }
    
    int main(){
        int x = 3;
        f(x);
        cout << x << endl;
    }
    

    Output: 13. It eliminate pass by value disadvantage, but if programmer do not want to change the value then use constant reference

  3. Constant reference

    void f(const int& n){
        n = n + 10; // Error: assignment of read-only reference  ‘n’
    }
    
    int main(){
        int x = 3;
        f(x);
        cout << x << endl;
    }
    

    Output: Throw error at n = n + 10 because when we pass const reference parameter argument then it is read-only parameter, you cannot change value of n.

Equivalent function for DATEADD() in Oracle

Equivalent will be

ADD_MONTHS( SYSDATE, -6 )

How do I compile a .cpp file on Linux?

The compiler is telling you that there are problems starting at line 122 in the middle of that strange FBI-CIA warning message. That message is not valid C++ code and is NOT commented out so of course it will cause compiler errors. Try removing that entire message.

Also, I agree with In silico: you should always tell us what you tried and exactly what error messages you got.

Convert char* to string C++

char *charPtr = "test string";
cout << charPtr << endl;

string str = charPtr;
cout << str << endl;

Returning the product of a list

reduce(lambda x, y: x * y, list, 1)

Split string on the first white space occurrence

I'm not sure why all other answers are so complicated, when you can do it all in one line, handling the lack of space as well.

As an example, let's get the first and "rest" components of a name:

_x000D_
_x000D_
const [first, rest] = 'John Von Doe'.split(/\s+(.*)/);
console.log({ first, rest });

// As array
const components = 'Surma'.split(/\s+(.*)/);
console.log(components);
_x000D_
_x000D_
_x000D_

Equal height rows in CSS Grid Layout

The short answer is that setting grid-auto-rows: 1fr; on the grid container solves what was asked.

https://codepen.io/Hlsg/pen/EXKJba

Simple DatePicker-like Calendar

No need to include JQuery or any other third party library.

Specify your input date format in title tag.

HTML:

<script type="text/javascript" src="http://services.iperfect.net/js/IP_generalLib.js">

Body

<input type="text" name="date1" id="date1" alt="date" class="IP_calendar" title="d/m/Y">

How to use KeyListener

In addition to using KeyListener (as shown by others' answers), sometimes you have to ensure that the JComponent you are using is Focusable. This can be set by adding this to your component(if you are subclassing):

@Override
public void setFocusable(boolean b) {
    super.setFocusable(b);
}

And by adding this to your constructor:

setFocusable(true);

Or, if you are calling the function from a parent class/container:

JComponent childComponent = new JComponent();
childComponent.setFocusable(true);

And then doing all the KeyListener stuff mentioned by others.

npm command to uninstall or prune unused packages in Node.js

Note: Recent npm versions do this automatically when package-locks are enabled, so this is not necessary except for removing development packages with the --production flag.


Run npm prune to remove modules not listed in package.json.

From npm help prune:

This command removes "extraneous" packages. If a package name is provided, then only packages matching one of the supplied names are removed.

Extraneous packages are packages that are not listed on the parent package's dependencies list.

If the --production flag is specified, this command will remove the packages specified in your devDependencies.

C# try catch continue execution

Leaving the catch block empty should do the trick. This is almost always a bad idea, though. On one hand, there's a performance penalty, and on the other (and this is more important), you always want to know when there's an error.

I would guess that the "callee" function failing, in your case, is actually not necessarily an "error," so to speak. That is, it is expected for it to fail sometimes. If this is the case, there is almost always a better way to handle it than using exceptions.

There are, if you'll pardon the pun, exceptions to the "rule", though. For example, if function2 were to call a web service whose results aren't really necessary for your page, this kind of pattern might be ok. Although, in almost 100% of cases, you should at least be logging it somewhere. In this scenario I'd log it in a finally block and report whether or not the service returned. Remember that data like that which may not be valuable to you now can become valuable later!

Last edit (probably):

In a comment I suggested you put the try/catch inside function2. Just thought I would elaborate. Function2 would look like this:

public Something? function2()
{
    try
    {
        //all of your function goes here
        return anActualObjectOfTypeSomething;
    }
    catch(Exception ex)
    {
        //logging goes here
        return null;
    }
}

That way, since you use a nullable return type, returning null doesn't hurt you.

Javascript Array of Functions

Ah man there are so many weird answers...

const execute = (fn) => fn()
const arrayOfFunctions = [fn1, fn2, fn3]

const results = arrayOfFunctions.map(execute)

or if you want to sequentially feed each functions result to the next:
compose(fn3, fn2, fn1)

compose is not supported by default, but there are libraries like ramda, lodash, or even redux which provide this tool

How to connect android emulator to the internet

it appears there might be a few reasons why there might be no internet connection for an emulator, in my case i was working from home where i have a wireless connection then came into the office and plugged in direct, however although my wireless connection was disconnected it was not disabled resulting in no emulator connection. my understanding is that when it starts up it looks for a network adapter and if there is any conflict here it might result in no internet connection. to resolve go to Start > Settings > Network Connections right click on Wireless Network Connection (if you are not using wireless) and select disable

Recover SVN password from local cache

Your SVN passwords in Ubuntu (12.04) are in:

~/.subversion/auth/svn.simple/

However in newer versions they are encrypted, as earlier someone mentioned. To find gnome-keyring passwords, I suggest You to use 'gkeyring' program.

To install it on Ubuntu – add repository :

sudo add-apt-repository ppa:kampka/ppa
sudo apt-get update

Install it:

sudo apt-get install gkeyring

And run as following:

gkeyring --id 15 --output=name,secret

Try different key ids to find pair matching what you are looking for. Thanks to kampka for the soft.

How to use Global Variables in C#?

There's no such thing as a global variable in C#. Period.

You can have static members if you want:

public static class MyStaticValues
{
   public static bool MyStaticBool {get;set;}
}

Validate date in dd/mm/yyyy format using JQuery Validate

If you use the moment js library it can easily be done like this -

jQuery.validator.addMethod("validDate", function(value, element) {
        return this.optional(element) || moment(value,"DD/MM/YYYY").isValid();
    }, "Please enter a valid date in the format DD/MM/YYYY");

python JSON only get keys in first level

for key in data.keys():
    print key