Programs & Examples On #Serverxmlhttp

How can I send an HTTP POST request to a server from Excel using VBA?

If you need it to work on both Mac and Windows, you can use QueryTables:

With ActiveSheet.QueryTables.Add(Connection:="URL;http://carbon.brighterplanet.com/flights.txt", Destination:=Range("A2"))
    .PostText = "origin_airport=MSN&destination_airport=ORD"
    .RefreshStyle = xlOverwriteCells
    .SaveData = True
    .Refresh
End With

Notes:

  • Regarding output... I don't know if it's possible to return the results to the same cell that called the VBA function. In the example above, the result is written into A2.
  • Regarding input... If you want the results to refresh when you change certain cells, make sure those cells are the argument to your VBA function.
  • This won't work on Excel for Mac 2008, which doesn't have VBA. Excel for Mac 2011 got VBA back.

For more details, you can see my full summary about "using web services from Excel."

Environment variables in Jenkins

The quick and dirty way, you can view the available environment variables from the below link.

http://localhost:8080/env-vars.html/

Just replace localhost with your Jenkins hostname, if its different

Android Lint contentDescription warning

Since it is only a warning you can suppress it. Go to your XML's Graphical Layout and do this:

  1. Click on the right top corner red button

    enter image description here

  2. Select "Disable Issue Type" (for example)

    enter image description here

Formatting code snippets for blogging on Blogger

Here's one site that will format your code and spit out html, and it even includes inline styles for syntax coloring. Might not work for all of your needs, but is a good start. I believe he has made the source available if you want to extend it:

How to access local files of the filesystem in the Android emulator?

In addition to the accepted answer, if you are using Android Studio you can

  1. invoke Android Device Monitor,
  2. select the device in the Devices tab on the left,
  3. select File Explorer tab on the right,
  4. navigate to the file you want, and
  5. click the Pull a file from the device button to save it to your local file system

Taken from Working with an emulator or device's file system

How to iterate (keys, values) in JavaScript?

I think the fast and easy way is

Object.entries(event).forEach(k => {
    console.log("properties ... ", k[0], k[1]); });

just check the documentation https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

Exact difference between CharSequence and String in java

Consider UTF-8. In UTF-8 Unicode code points are built from one or more bytes. A class encapsulating a UTF-8 byte array can implement the CharSequence interface but is most decidedly not a String. Certainly you can't pass a UTF-8 byte array where a String is expected but you certainly can pass a UTF-8 wrapper class that implements CharSequence when the contract is relaxed to allow a CharSequence. On my project, I am developing a class called CBTF8Field (Compressed Binary Transfer Format - Eight Bit) to provide data compression for xml and am looking to use the CharSequence interface to implement conversions from CBTF8 byte arrays to/from character arrays (UTF-16) and byte arrays (UTF-8).

The reason I came here was to get a complete understanding of the subsequence contract.

How to SELECT WHERE NOT EXIST using LINQ?

from s in context.shift
where !context.employeeshift.Any(es=>(es.shiftid==s.shiftid)&&(es.empid==57))
select s;

Hope this helps

Sending JSON object to Web API

Change:

 data: JSON.stringify({ model: source })

To:

 data: {model: JSON.stringify(source)}

And in your controller you do this:

public void PartSourceAPI(string model)
{
       System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();

   var result = js.Deserialize<PartSourceModel>(model);
}

If the url you use in jquery is /api/PartSourceAPI then the controller name must be api and the action(method) should be PartSourceAPI

How do I reference to another (open or closed) workbook, and pull values back, in VBA? - Excel 2007

You will have to open the file in one way or another if you want to access the data within it. Obviously, one way is to open it in your Excel application instance, e.g.:-

(untested code)

Dim wbk As Workbook
Set wbk = Workbooks.Open("C:\myworkbook.xls")

' now you can manipulate the data in the workbook anyway you want, e.g. '

Dim x As Variant
x = wbk.Worksheets("Sheet1").Range("A6").Value

Call wbk.Worksheets("Sheet2").Range("A1:G100").Copy
Call ThisWorbook.Worksheets("Target").Range("A1").PasteSpecial(xlPasteValues)
Application.CutCopyMode = False

' etc '

Call wbk.Close(False)

Another way to do it would be to use the Excel ADODB provider to open a connection to the file and then use SQL to select data from the sheet you want, but since you are anyway working from within Excel I don't believe there is any reason to do this rather than just open the workbook. Note that there are optional parameters for the Workbooks.Open() method to open the workbook as read-only, etc.

How to check if an object is defined?

You check if it's null in C# like this:

if(MyObject != null) {
  //do something
}

If you want to check against default (tough to understand the question on the info given) check:

if(MyObject != default(MyObject)) {
 //do something
}

How to default to other directory instead of home directory

For windows: Follow these steps-

  1. Go to windows home> Right click on "Git Bash" application.
  2. Properties> Shortcut
  3. Change these two settings: (a) Delete --cd-to-home from target (b) Type folder path you want to start with git in "Start in".

This worked for me:)

How to set dropdown arrow in spinner?

Set the Dropdown arrow image to spinner like this :

<Spinner
    android:id="@+id/Exam_Course"
    android:layout_width="320dp"
    android:background="@drawable/spinner_bg"
    android:layout_height="wrap_content"/>

Here android:background="@drawable/spinner_bg" the spinner_bg is the Dropdown arrow image.

SQL Server function to return minimum date (January 1, 1753)

You could write a User Defined Function that returns the min date value like this:

select cast(-53690 as datetime)

Then use that function in your scripts, and if you ever need to change it, there is only one place to do that.

Alternately, you could use this query if you prefer it for better readability:

select cast('1753-1-1' as datetime)

Example Function

create function dbo.DateTimeMinValue()
returns datetime as
begin
    return (select cast(-53690 as datetime))
end

Usage

select dbo.DateTimeMinValue() as DateTimeMinValue

DateTimeMinValue
-----------------------
1753-01-01 00:00:00.000

How to use LogonUser properly to impersonate domain user from workgroup client

Invalid login/password could be also related to issues in your DNS server - that's what happened to me and cost me good 5 hours of my life. See if you can specify ip address instead on domain name.

json.dumps vs flask.jsonify

This is flask.jsonify()

def jsonify(*args, **kwargs):
    if __debug__:
        _assert_have_json()
    return current_app.response_class(json.dumps(dict(*args, **kwargs),
        indent=None if request.is_xhr else 2), mimetype='application/json')

The json module used is either simplejson or json in that order. current_app is a reference to the Flask() object i.e. your application. response_class() is a reference to the Response() class.

UICollectionView Set number of columns

the perfect solution is to Using UICollectionViewDelegateFlowLayout but you can easily so calculate the cell width and divided on the wanted number of columns you want

the tricky is to make the width with no fraction

(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath

{
 CGFloat screenWidth = self.view.frame.size.width;
   CGFloat marginWidth = (screenWidth - collectionView.frame.size.width);


   CGFloat cellWith = (collectionView.frame.size.width - marginWidth )/3;
   cellWith= floorf(cellWith);




  CGSize retval = CGSizeMake(cellWith,cellWith);


  return retval;}

How to check if a string contains text from an array of substrings in JavaScript?

convert_to_array = function (sentence) {
     return sentence.trim().split(" ");
};

let ages = convert_to_array ("I'm a programmer in javascript writing script");

function confirmEnding(string) {
let target = "ipt";
    return  (string.substr(-target.length) === target) ? true : false;
}

function mySearchResult() {
return ages.filter(confirmEnding);
}

mySearchResult();

you could check like this and return an array of the matched words using filter

How do I wait until Task is finished in C#?

Your Print method likely needs to wait for the continuation to finish (ContinueWith returns a task which you can wait on). Otherwise the second ReadAsStringAsync finishes, the method returns (before result is assigned in the continuation). Same problem exists in your send method. Both need to wait on the continuation to consistently get the results you want. Similar to below

private static string Send(int id)
{
    Task<HttpResponseMessage> responseTask = client.GetAsync("aaaaa");
    string result = string.Empty;
    Task continuation = responseTask.ContinueWith(x => result = Print(x));
    continuation.Wait();
    return result;
}

private static string Print(Task<HttpResponseMessage> httpTask)
{
    Task<string> task = httpTask.Result.Content.ReadAsStringAsync();
    string result = string.Empty;
    Task continuation = task.ContinueWith(t =>
    {
        Console.WriteLine("Result: " + t.Result);
        result = t.Result;
    });
    continuation.Wait();  
    return result;
}

How to get a value inside an ArrayList java

import java.util.*;
import java.lang.*;
import java.io.*;

class hari
{
public static void main (String[] args) throws Exception
{  Scanner s=new Scanner(System.in);
    int i=0;
    int b=0;
    HashSet<Integer> h=new HashSet<Integer>();
    try{
        for(i=0;i<1000;i++)
    {   b=s.nextInt();
        h.add(b);
    }
    }
    catch(Exception e){
        System.out.println(h+","+h.size());
    }
}}

Error 1046 No database Selected, how to resolve?

first select database : USE db_name

then creat table:CREATE TABLE tb_name ( id int, name varchar(255), salary int, city varchar(255) );

this for mysql 5.5 version syntax

Unloading classes in java?

I wrote a custom classloader, from which it is possible to unload individual classes without GCing the classloader. Jar Class Loader

Loop through all the files with a specific extension

Recursively add subfolders,

for i in `find . -name "*.java" -type f`; do
    echo "$i"
done

How to unnest a nested list

Use reduce function

reduce(lambda x, y: x + y, A, [])

Or sum

sum(A, [])

Generator expressions vs. list comprehensions

When creating a generator from a mutable object (like a list) be aware that the generator will get evaluated on the state of the list at time of using the generator, not at time of the creation of the generator:

>>> mylist = ["a", "b", "c"]
>>> gen = (elem + "1" for elem in mylist)
>>> mylist.clear()
>>> for x in gen: print (x)
# nothing

If there is any chance of your list getting modified (or a mutable object inside that list) but you need the state at creation of the generator you need to use a list comprehension instead.

How can I set the value of a DropDownList using jQuery?

If you just need to set the value of a dropdown then the best way is

$("#ID").val("2");

If You have to trigger any script after updating the dropdown value like If you set any onChange event on the dropdown and you want to run this after update the dropdown than You need to use like this

$("#ID").val("2").change();

Python MYSQL update statement

Neither of them worked for me for some reason.

I figured it out that for some reason python doesn't read %s. So use (?) instead of %S in you SQL Code.

And finally this worked for me.

   cursor.execute ("update tablename set columnName = (?) where ID = (?) ",("test4","4"))
   connect.commit()

UICollectionView cell selection and cell reuse

Your observation is correct. This behavior is happening due to the reuse of cells. But you dont have to do any thing with the prepareForReuse. Instead do your check in cellForItem and set the properties accordingly. Some thing like..

 - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cvCell" forIndexPath:indexPath];


if (cell.selected) {
     cell.backgroundColor = [UIColor blueColor]; // highlight selection 
}
else
{
     cell.backgroundColor = [UIColor redColor]; // Default color
}
return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath  {

    UICollectionViewCell *datasetCell =[collectionView cellForItemAtIndexPath:indexPath];
    datasetCell.backgroundColor = [UIColor blueColor]; // highlight selection
 }  

 -(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {

UICollectionViewCell *datasetCell =[collectionView cellForItemAtIndexPath:indexPath]; 
datasetCell.backgroundColor = [UIColor redColor]; // Default color
}

Plot size and resolution with R markdown, knitr, pandoc, beamer

Figure sizes are specified in inches and can be included as a global option of the document output format. For example:

---
title: "My Document"
output:
  html_document:
    fig_width: 6
    fig_height: 4
---

And the plot's size in the graphic device can be increased at the chunk level:

```{r, fig.width=14, fig.height=12}          #Expand the plot width to 14 inches

ggplot(aes(x=mycolumn1, y=mycolumn2)) +     #specify the x and y aesthetic
geom_line(size=2) +                         #makes the line thicker
theme_grey(base_size = 25)                  #increases the size of the font
```

You can also use the out.width and out.height arguments to directly define the size of the plot in the output file:

```{r, out.width="200px", out.height="200px"} #Expand the plot width to 200 pixels

ggplot(aes(x=mycolumn1, y=mycolumn2)) +     #specify the x and y aesthetic
geom_line(size=2) +                         #makes the line thicker
theme_grey(base_size = 25)                  #increases the size of the font
```

Convert ArrayList to String array in Android

You could make an array the same size as the ArrayList and then make an iterated for loop to index the items and insert them into the array.

SQLite: How do I save the result of a query as a CSV file?

To include column names to your csv file you can do the following:

sqlite> .headers on
sqlite> .mode csv
sqlite> .output test.csv
sqlite> select * from tbl1;
sqlite> .output stdout

To verify the changes that you have made you can run this command:

sqlite> .show

Output:

echo: off   
explain: off   
headers: on   
mode: csv   
nullvalue: ""  
output: stdout  
separator: "|"   
stats: off   
width: 22 18 

Command to find information about CPUs on a UNIX machine

Try psrinfo to find the processor type and the number of physical processors installed on the system.

SQL Server AS statement aliased column within WHERE statement

Logical Processing Order of the SELECT statement

The following steps show the logical processing order, or binding order, for a SELECT statement. This order determines when the objects defined in one step are made available to the clauses in subsequent steps. For example, if the query processor can bind to (access) the tables or views defined in the FROM clause, these objects and their columns are made available to all subsequent steps. Conversely, because the SELECT clause is step 8, any column aliases or derived columns defined in that clause cannot be referenced by preceding clauses. However, they can be referenced by subsequent clauses such as the ORDER BY clause. Note that the actual physical execution of the statement is determined by the query processor and the order may vary from this list.

  1. FROM
  2. ON
  3. JOIN
  4. WHERE
  5. GROUP BY
  6. WITH CUBE or WITH ROLLUP
  7. HAVING
  8. SELECT
  9. DISTINCT
  10. ORDER BY
  11. TOP

Source: http://msdn.microsoft.com/en-us/library/ms189499%28v=sql.110%29.aspx

Inverse dictionary lookup in Python

Your list comprehension goes through all the dict's items finding all the matches, then just returns the first key. This generator expression will only iterate as far as necessary to return the first value:

key = next(key for key, value in dd.items() if value == 'value')

where dd is the dict. Will raise StopIteration if no match is found, so you might want to catch that and return a more appropriate exception like ValueError or KeyError.

How to manually trigger click event in ReactJS?

Try this and let me know if it does not work on your end:

<input type="checkbox" name='agree' ref={input => this.inputElement = input}/>
<div onClick={() => this.inputElement.click()}>Click</div>

Clicking on the div should simulate a click on the input element

How can I iterate over an enum?

For MS compilers:

#define inc_enum(i) ((decltype(i)) ((int)i + 1))

enum enumtype { one, two, three, count};
for(enumtype i = one; i < count; i = inc_enum(i))
{ 
    dostuff(i); 
}

Note: this is a lot less code than the simple templatized custom iterator answer.

You can get this to work with GCC by using typeof instead of decltype, but I don't have that compiler handy at the moment to make sure it compiles.

Convert Uri to String and String to Uri

I need to know way for converting uri to string and string to uri.

Use toString() to convert a Uri to a String. Use Uri.parse() to convert a String to a Uri.

this code doesn't work

That is not a valid string representation of a Uri. A Uri has a scheme, and "/external/images/media/470939" does not have a scheme.

Redirecting to a relative URL in JavaScript

https://developer.mozilla.org/en-US/docs/Web/API/Location/assign

  • window.location.assign("../"); // one level up
  • window.location.assign("/path"); // relative to domain

Python: How to use RegEx in an if statement?

if re.search(r'pattern', string):

Simple if-test:

if re.search(r'ing\b', "seeking a great perhaps"):     # any words end with ing?
    print("yes")

Pattern check, extract a substring, case insensitive:

match_object = re.search(r'^OUGHT (.*) BE$', "ought to be", flags=re.IGNORECASE)
if match_object:
    assert "to" == match_object.group(1)     # what's between ought and be?

Notes:

  • Use re.search() not re.match. Match restricts to the start of strings, a confusing convention if you ask me. If you do want a string-starting match, use caret or \A instead, re.search(r'^...', ...)

  • Use raw string syntax r'pattern' for the first parameter. Otherwise you would need to double up backslashes, as in re.search('ing\\b', ...)

  • In this example, \b is a special sequence meaning word-boundary in regex. Not to be confused with backspace.

  • re.search() returns None if it doesn't find anything, which is always falsy.

  • re.search() returns a Match object if it finds anything, which is always truthy.

  • a group is what matched inside parentheses

  • group numbering starts at 1

  • Specs

  • Tutorial

MySQL skip first 10 results

LIMIT allow you to skip any number of rows. It has two parameters, and first of them - how many rows to skip

Activate a virtualenv with a Python script

If you want to run a Python subprocess under the virtualenv, you can do that by running the script using the Python interpreter that lives inside virtualenv's /bin/ directory:

import subprocess

# Path to a Python interpreter that runs any Python script
# under the virtualenv /path/to/virtualenv/
python_bin = "/path/to/virtualenv/bin/python"

# Path to the script that must run under the virtualenv
script_file = "must/run/under/virtualenv/script.py"

subprocess.Popen([python_bin, script_file])

However, if you want to activate the virtualenv under the current Python interpreter instead of a subprocess, you can use the activate_this.py script:

# Doing execfile() on this file will alter the current interpreter's
# environment so you can import libraries in the virtualenv
activate_this_file = "/path/to/virtualenv/bin/activate_this.py"

execfile(activate_this_file, dict(__file__=activate_this_file))

Fatal error: Maximum execution time of 30 seconds exceeded

Maybe check for any thing that you have changed under the php.ini file. For example I changed the ";intl.default_locale =" to ";intl.default_locale = en_utf8" in order to enable the "Internationalization extension (Intl)" without adding the "extension=php_intl.dll" then this same error occurred. So I suggest to check for similar mistakes.

Does Spring Data JPA have any way to count entites using method name resolving?

Thanks you all! Now it's work. DATAJPA-231

It will be nice if was possible to create count…By… methods just like find…By ones. Example:

public interface UserRepository extends JpaRepository<User, Long> {

   public Long /*or BigInteger */ countByActiveTrue();
}

Hide Spinner in Input Number - Firefox 29

/* for chrome */
    input[type=number]::-webkit-inner-spin-button,
    input[type=number]::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;}             


/* for mozilla */  
   input[type=number] {-moz-appearance: textfield;}

How can I select an element in a component template?

import the ViewChild decorator from @angular/core, like so:

HTML Code:

<form #f="ngForm"> 
  ... 
  ... 
</form>

TS Code:

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

class TemplateFormComponent {

  @ViewChild('f') myForm: any;
    .
    .
    .
}

now you can use 'myForm' object to access any element within it in the class.

Source

GCC fatal error: stdio.h: No such file or directory

Mac OS X

I had this problem too (encountered through Macports compilers). Previous versions of Xcode would let you install command line tools through xcode/Preferences, but xcode5 doesn't give a command line tools option in the GUI, that so I assumed it was automatically included now. Try running this command:

xcode-select --install

Ubuntu

(as per this answer)

sudo apt-get install libc6-dev

Alpine Linux

(as per this comment)

apk add libc-dev

Pandas - 'Series' object has no attribute 'colNames' when using apply()

When you use df.apply(), each row of your DataFrame will be passed to your lambda function as a pandas Series. The frame's columns will then be the index of the series and you can access values using series[label].

So this should work:

df['D'] = (df.apply(lambda x: myfunc(x[colNames[0]], x[colNames[1]]), axis=1)) 

SQL where datetime column equals today's date?

Easy way out is to use a condition like this ( use desired date > GETDATE()-1)

your sql statement "date specific" > GETDATE()-1

How to solve a timeout error in Laravel 5

Execution is not related to laravel go to the php.ini file In php.ini file set max_execution_time=360 (time may be variable depends on need) if you want to increase execution of a specific page then write ini_set('max_execution_time',360) at top of page

otherwise in htaccess php_value max_execution_time 360

unable to remove file that really exists - fatal: pathspec ... did not match any files

Your file .idea/workspace.xml is not under git version control. You have either not added it yet (check git status/Untracked files) or ignored it (using .gitignore or .git/info/exclude files)

You can verify it using following git command, that lists all ignored files:

git ls-files --others -i --exclude-standard

TSQL - Cast string to integer or return default value

Regards.

I wrote a useful scalar function to simulate the TRY_CAST function of SQL SERVER 2012 in SQL Server 2008.

You can see it in the next link below and we help each other to improve it. TRY_CAST Function for SQL Server 2008 https://gist.github.com/jotapardo/800881eba8c5072eb8d99ce6eb74c8bb

The two main differences are that you must pass 3 parameters and you must additionally perform an explicit CONVERT or CAST to the field. However, it is still very useful because it allows you to return a default value if CAST is not performed correctly.

dbo.TRY_CAST(Expression, Data_Type, ReturnValueIfErrorCast)

Example:

SELECT   CASE WHEN dbo.TRY_CAST('6666666166666212', 'INT', DEFAULT) IS NULL   
                        THEN 'Cast failed'  
                        ELSE 'Cast succeeded'  
                    END AS Result; 

For now only supports the data types INT, DATE, NUMERIC, BIT and FLOAT

I hope you find it useful.

CODE:

DECLARE @strSQL NVARCHAR(1000)
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[TRY_CAST]'))
    BEGIN
        SET @strSQL = 'CREATE FUNCTION [dbo].[TRY_CAST] () RETURNS INT AS BEGIN RETURN 0 END'
        EXEC sys.sp_executesql @strSQL
    END

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
------------------------------------------------------------------------------------------------------------------------
    Description:    
                    Syntax 
                    ---------------
                    dbo.TRY_CAST(Expression, Data_Type, ReturnValueIfErrorCast)

                    +---------------------------+-----------------------+
                    |   Expression              |   VARCHAR(8000)       |
                    +---------------------------+-----------------------+
                    |   Data_Type               |   VARCHAR(8000)       |
                    +---------------------------+-----------------------+
                    |   ReturnValueIfErrorCast  |   SQL_VARIANT = NULL  |
                    +---------------------------+-----------------------+


                    Arguments
                    ---------------
                    expression
                    The value to be cast. Any valid expression.

                    Data_Type
                    The data type into which to cast expression.

                    ReturnValueIfErrorCast
                    Value returned if cast fails or is not supported. Required. Set the DEFAULT value by default.


                    Return Type
                    ----------------
                    Returns value cast to SQL_VARIANT type if the cast succeeds; otherwise, returns null if the parameter @pReturnValueIfErrorCast is set to DEFAULT, 
                    or that the user indicates.


                    Remarks
                    ----------------
                    dbo.TRY_CAST function simulates the TRY_CAST function reserved of SQL SERVER 2012 for using in SQL SERVER 2008. 
                    dbo.TRY_CAST function takes the value passed to it and tries to convert it to the specified Data_Type. 
                    If the cast succeeds, dbo.TRY_CAST returns the value as SQL_VARIANT type; if the cast doesn´t succees, null is returned if the parameter @pReturnValueIfErrorCast is set to DEFAULT. 
                    If the Data_Type is unsupported will return @pReturnValueIfErrorCast.
                    dbo.TRY_CAST function requires user make an explicit CAST or CONVERT in ANY statements.
                    This version of dbo.TRY_CAST only supports CAST for INT, DATE, NUMERIC and BIT types.


                    Examples
                    ====================================================================================================

                    --A. Test TRY_CAST function returns null

                        SELECT   
                            CASE WHEN dbo.TRY_CAST('6666666166666212', 'INT', DEFAULT) IS NULL   
                            THEN 'Cast failed'  
                            ELSE 'Cast succeeded'  
                        END AS Result; 

                    GO

                    --B. Error Cast With User Value

                        SELECT   
                            dbo.TRY_CAST('2147483648', 'INT', DEFAULT) AS [Error Cast With DEFAULT],
                            dbo.TRY_CAST('2147483648', 'INT', -1) AS [Error Cast With User Value],
                            dbo.TRY_CAST('2147483648', 'INT', NULL) AS [Error Cast With User NULL Value]; 

                        GO 

                    --C. Additional CAST or CONVERT required in any assignment statement

                        DECLARE @IntegerVariable AS INT

                        SET @IntegerVariable = CAST(dbo.TRY_CAST(123, 'INT', DEFAULT) AS INT)

                        SELECT @IntegerVariable

                        GO 

                        IF OBJECT_ID('tempdb..#temp') IS NOT NULL
                            DROP TABLE #temp

                        CREATE TABLE #temp (
                            Id INT IDENTITY
                            , FieldNumeric NUMERIC(3, 1)
                            )

                        INSERT INTO dbo.#temp (FieldNumeric)
                        SELECT CAST(dbo.TRY_CAST(12.3, 'NUMERIC(3,1)', 0) AS NUMERIC(3, 1));--Need explicit CAST on INSERT statements

                        SELECT *
                        FROM #temp

                        DROP TABLE #temp

                        GO 

                    --D. Supports CAST for INT, DATE, NUMERIC and BIT types.

                        SELECT dbo.TRY_CAST(2147483648, 'INT', 0) AS [Cast failed]
                            , dbo.TRY_CAST(2147483647, 'INT', 0) AS [Cast succeeded]
                            , SQL_VARIANT_PROPERTY(dbo.TRY_CAST(212, 'INT', 0), 'BaseType') AS [BaseType];

                        SELECT dbo.TRY_CAST('AAAA0101', 'DATE', DEFAULT) AS [Cast failed]
                            , dbo.TRY_CAST('20160101', 'DATE', DEFAULT) AS [Cast succeeded]
                            , SQL_VARIANT_PROPERTY(dbo.TRY_CAST('2016-01-01', 'DATE', DEFAULT), 'BaseType') AS [BaseType];

                        SELECT dbo.TRY_CAST(1.23, 'NUMERIC(3,1)', DEFAULT) AS [Cast failed]
                            , dbo.TRY_CAST(12.3, 'NUMERIC(3,1)', DEFAULT) AS [Cast succeeded]
                            , SQL_VARIANT_PROPERTY(dbo.TRY_CAST(12.3, 'NUMERIC(3,1)', DEFAULT), 'BaseType') AS [BaseType];

                        SELECT dbo.TRY_CAST('A', 'BIT', DEFAULT) AS [Cast failed]
                            , dbo.TRY_CAST(1, 'BIT', DEFAULT) AS [Cast succeeded]
                            , SQL_VARIANT_PROPERTY(dbo.TRY_CAST('123', 'BIT', DEFAULT), 'BaseType') AS [BaseType];

                        GO 

                    --E. B. TRY_CAST return NULL on unsupported data_types

                        SELECT dbo.TRY_CAST(4, 'xml', DEFAULT) AS [unsupported];  

                        GO  

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

------------------------------------------------------------------------------------------------------------------------
    Responsible:    Javier Pardo 
    Date:           diciembre 29/2016
    WB tests:       Javier Pardo 
------------------------------------------------------------------------------------------------------------------------
    Update by:      Javier Eduardo Pardo Moreno 
    Date:           febrero 16/2017
    Id update:      JEPM20170216
    Description:    Fix  ISNUMERIC function makes it unreliable. SELECT dbo.TRY_CAST('+', 'INT', 0) will yield Msg 8114, 
                    Level 16, State 5, Line 16 Error converting data type varchar to float.
                    ISNUMERIC() function treats few more characters as numeric, like: – (minus), + (plus), $ (dollar), \ (back slash), (.)dot and (,)comma
                    Collaborator aperiooculus (http://stackoverflow.com/users/3083382/aperiooculus )

                    Fix dbo.TRY_CAST('2013/09/20', 'datetime', DEFAULT) for supporting DATETIME format

    WB tests:       Javier Pardo 

------------------------------------------------------------------------------------------------------------------------
*/

ALTER FUNCTION dbo.TRY_CAST
(
    @pExpression AS VARCHAR(8000),
    @pData_Type AS VARCHAR(8000),
    @pReturnValueIfErrorCast AS SQL_VARIANT = NULL
)
RETURNS SQL_VARIANT
AS
BEGIN
    --------------------------------------------------------------------------------
    --  INT 
    --------------------------------------------------------------------------------

    IF @pData_Type = 'INT'
    BEGIN
        IF ISNUMERIC(@pExpression) = 1 AND @pExpression NOT IN ('-','+','$','.',',','\')    --JEPM20170216
        BEGIN
            DECLARE @pExpressionINT AS FLOAT = CAST(@pExpression AS FLOAT)

            IF @pExpressionINT BETWEEN - 2147483648.0 AND 2147483647.0
            BEGIN
                RETURN CAST(@pExpressionINT as INT)
            END
            ELSE
            BEGIN
                RETURN @pReturnValueIfErrorCast
            END --FIN IF @pExpressionINT BETWEEN - 2147483648.0 AND 2147483647.0
        END
        ELSE
        BEGIN
            RETURN @pReturnValueIfErrorCast
        END -- FIN IF ISNUMERIC(@pExpression) = 1
    END -- FIN IF @pData_Type = 'INT'

    --------------------------------------------------------------------------------
    --  DATE    
    --------------------------------------------------------------------------------

    IF @pData_Type IN ('DATE','DATETIME')
    BEGIN
        IF ISDATE(@pExpression) = 1
        BEGIN

            DECLARE @pExpressionDATE AS DATETIME = cast(@pExpression AS DATETIME)

            IF @pData_Type = 'DATE'
            BEGIN
                RETURN cast(@pExpressionDATE as DATE)
            END

            IF @pData_Type = 'DATETIME'
            BEGIN
                RETURN cast(@pExpressionDATE as DATETIME)
            END

        END
        ELSE 
        BEGIN

            DECLARE @pExpressionDATEReplaced AS VARCHAR(50) = REPLACE(REPLACE(REPLACE(@pExpression,'\',''),'/',''),'-','')

            IF ISDATE(@pExpressionDATEReplaced) = 1
            BEGIN
                IF @pData_Type = 'DATE'
                BEGIN
                    RETURN cast(@pExpressionDATEReplaced as DATE)
                END

                IF @pData_Type = 'DATETIME'
                BEGIN
                    RETURN cast(@pExpressionDATEReplaced as DATETIME)
                END

            END
            ELSE
            BEGIN
                RETURN @pReturnValueIfErrorCast
            END
        END --FIN IF ISDATE(@pExpression) = 1
    END --FIN IF @pData_Type = 'DATE'

    --------------------------------------------------------------------------------
    --  NUMERIC 
    --------------------------------------------------------------------------------

    IF @pData_Type LIKE 'NUMERIC%'
    BEGIN

        IF ISNUMERIC(@pExpression) = 1
        BEGIN

            DECLARE @TotalDigitsOfType AS INT = SUBSTRING(@pData_Type,CHARINDEX('(',@pData_Type)+1,  CHARINDEX(',',@pData_Type) - CHARINDEX('(',@pData_Type) - 1)
                , @TotalDecimalsOfType AS INT = SUBSTRING(@pData_Type,CHARINDEX(',',@pData_Type)+1,  CHARINDEX(')',@pData_Type) - CHARINDEX(',',@pData_Type) - 1)
                , @TotalDigitsOfValue AS INT 
                , @TotalDecimalsOfValue AS INT 
                , @TotalWholeDigitsOfType AS INT 
                , @TotalWholeDigitsOfValue AS INT 

            SET @pExpression = REPLACE(@pExpression, ',','.')

            SET @TotalDigitsOfValue = LEN(REPLACE(@pExpression, '.',''))
            SET @TotalDecimalsOfValue = CASE Charindex('.', @pExpression)
                                        WHEN 0
                                            THEN 0
                                        ELSE Len(Cast(Cast(Reverse(CONVERT(VARCHAR(50), @pExpression, 128)) AS FLOAT) AS BIGINT))
                                        END 
            SET @TotalWholeDigitsOfType = @TotalDigitsOfType - @TotalDecimalsOfType
            SET @TotalWholeDigitsOfValue = @TotalDigitsOfValue - @TotalDecimalsOfValue

            -- The total digits can not be greater than the p part of NUMERIC (p, s)
            -- The total of decimals can not be greater than the part s of NUMERIC (p, s)
            -- The total digits of the whole part can not be greater than the subtraction between p and s
            IF (@TotalDigitsOfValue <= @TotalDigitsOfType) AND (@TotalDecimalsOfValue <= @TotalDecimalsOfType) AND (@TotalWholeDigitsOfValue <= @TotalWholeDigitsOfType)
            BEGIN
                DECLARE @pExpressionNUMERIC AS FLOAT
                SET @pExpressionNUMERIC = CAST (ROUND(@pExpression, @TotalDecimalsOfValue) AS FLOAT) 

                RETURN @pExpressionNUMERIC --Returns type FLOAT
            END 
            else
            BEGIN
                RETURN @pReturnValueIfErrorCast
            END-- FIN IF (@TotalDigitisOfValue <= @TotalDigits) AND (@TotalDecimalsOfValue <= @TotalDecimals) 

        END
        ELSE 
        BEGIN
            RETURN @pReturnValueIfErrorCast
        END --FIN IF ISNUMERIC(@pExpression) = 1
    END --IF @pData_Type LIKE 'NUMERIC%'

    --------------------------------------------------------------------------------
    --  BIT 
    --------------------------------------------------------------------------------

    IF @pData_Type LIKE 'BIT'
    BEGIN
        IF ISNUMERIC(@pExpression) = 1
        BEGIN
            RETURN CAST(@pExpression AS BIT) 
        END
        ELSE 
        BEGIN
            RETURN @pReturnValueIfErrorCast
        END --FIN IF ISNUMERIC(@pExpression) = 1
    END --IF @pData_Type LIKE 'BIT'


    --------------------------------------------------------------------------------
    --  FLOAT   
    --------------------------------------------------------------------------------

    IF @pData_Type LIKE 'FLOAT'
    BEGIN
        IF ISNUMERIC(REPLACE(REPLACE(@pExpression, CHAR(13), ''), CHAR(10), '')) = 1
        BEGIN

            RETURN CAST(@pExpression AS FLOAT) 
        END
        ELSE 
        BEGIN

            IF REPLACE(@pExpression, CHAR(13), '') = '' --Only white spaces are replaced, not new lines
            BEGIN
                RETURN 0
            END
            ELSE 
            BEGIN
                RETURN @pReturnValueIfErrorCast
            END --IF REPLACE(@pExpression, CHAR(13), '') = '' 

        END --FIN IF ISNUMERIC(@pExpression) = 1
    END --IF @pData_Type LIKE 'FLOAT'

    --------------------------------------------------------------------------------
    --  Any other unsupported data type will return NULL or the value assigned by the user to @pReturnValueIfErrorCast  
    --------------------------------------------------------------------------------

    RETURN @pReturnValueIfErrorCast



END

Matplotlib discrete colorbar

This topic is well covered already but I wanted to add something more specific : I wanted to be sure that a certain value would be mapped to that color (not to any color).

It is not complicated but as it took me some time, it might help others not lossing as much time as I did :)

import matplotlib
from matplotlib.colors import ListedColormap

# Let's design a dummy land use field
A = np.reshape([7,2,13,7,2,2], (2,3))
vals = np.unique(A)

# Let's also design our color mapping: 1s should be plotted in blue, 2s in red, etc...
col_dict={1:"blue",
          2:"red",
          13:"orange",
          7:"green"}

# We create a colormar from our list of colors
cm = ListedColormap([col_dict[x] for x in col_dict.keys()])

# Let's also define the description of each category : 1 (blue) is Sea; 2 (red) is burnt, etc... Order should be respected here ! Or using another dict maybe could help.
labels = np.array(["Sea","City","Sand","Forest"])
len_lab = len(labels)

# prepare normalizer
## Prepare bins for the normalizer
norm_bins = np.sort([*col_dict.keys()]) + 0.5
norm_bins = np.insert(norm_bins, 0, np.min(norm_bins) - 1.0)
print(norm_bins)
## Make normalizer and formatter
norm = matplotlib.colors.BoundaryNorm(norm_bins, len_lab, clip=True)
fmt = matplotlib.ticker.FuncFormatter(lambda x, pos: labels[norm(x)])

# Plot our figure
fig,ax = plt.subplots()
im = ax.imshow(A, cmap=cm, norm=norm)

diff = norm_bins[1:] - norm_bins[:-1]
tickz = norm_bins[:-1] + diff / 2
cb = fig.colorbar(im, format=fmt, ticks=tickz)
fig.savefig("example_landuse.png")
plt.show()

enter image description here

How to unzip a file in Powershell?

In PowerShell v5+, there is an Expand-Archive command (as well as Compress-Archive) built in:

Expand-Archive c:\a.zip -DestinationPath c:\a

How to pass data from child component to its parent in ReactJS?

The idea is to send a callback to the child which will be called to give the data back

A complete and minimal example using functions:

App will create a Child which will compute a random number and send it back directly to the parent, which will console.log the result

const Child = ({ handleRandom }) => {
  handleRandom(Math.random())

  return <span>child</span>
}
const App = () => <Child handleRandom={(num) => console.log(num)}/>

Maven home (M2_HOME) not being picked up by IntelliJ IDEA

If you are having this problem with a homebrew installation of maven 3 on the OSX 10.9.4 then check out this blog post.

opening a window form from another form programmatically

This is an old question, but answering for gathering knowledge. We have an original form with a button to show the new form.

enter image description here

The code for the button click is below

private void button1_Click(object sender, EventArgs e)
{
    New_Form new_Form = new New_Form();
    new_Form.Show();
}

Now when click is made, New Form is shown. Since, you want to hide after 2 seconds we are adding a onload event to the new form designer

this.Load += new System.EventHandler(this.OnPageLoad);

This OnPageLoad function runs when that form is loaded

In NewForm.cs ,

public partial class New_Form : Form
{
    private Timer formClosingTimer;

    private void OnPageLoad(object sender, EventArgs e)
    {
        formClosingTimer = new Timer();  // Creating a new timer 
        formClosingTimer.Tick += new EventHandler(CloseForm); // Defining tick event to invoke after a time period
        formClosingTimer.Interval = 2000; // Time Interval in miliseconds
        formClosingTimer.Start(); // Starting a timer
    }
    private void CloseForm(object sender, EventArgs e)
    {
        formClosingTimer.Stop(); // Stoping timer. If we dont stop, function will be triggered in regular intervals
        this.Close(); // Closing the current form
    }
}

In this new form , a timer is used to invoke a method which closes that form.

Here is the new form which automatically closes after 2 seconds, we will be able operate on both the forms where no interference between those two forms.

enter image description here

For your knowledge,

form.close() will free the memory and we can never interact with that form again form.hide() will just hide the form, where the code part can still run

For more details about timer refer this link, https://docs.microsoft.com/en-us/dotnet/api/system.timers.timer?view=netframework-4.7.2

How to use ArrayList's get() method

ArrayList get(int index) method is used for fetching an element from the list. We need to specify the index while calling get method and it returns the value present at the specified index.

public Element get(int index)

Example : In below example we are getting few elements of an arraylist by using get method.

package beginnersbook.com;
import java.util.ArrayList;
public class GetMethodExample {
   public static void main(String[] args) {
       ArrayList<String> al = new ArrayList<String>();
       al.add("pen");
       al.add("pencil");
       al.add("ink");
       al.add("notebook");
       al.add("book");
       al.add("books");
       al.add("paper");
       al.add("white board");

       System.out.println("First element of the ArrayList: "+al.get(0));
       System.out.println("Third element of the ArrayList: "+al.get(2));
       System.out.println("Sixth element of the ArrayList: "+al.get(5));
       System.out.println("Fourth element of the ArrayList: "+al.get(3));
   }
}

Output:

First element of the ArrayList: pen
Third element of the ArrayList: ink
Sixth element of the ArrayList: books
Fourth element of the ArrayList: notebook

How to get current relative directory of your Makefile?

If you are using GNU make, $(CURDIR) is actually a built-in variable. It is the location where the Makefile resides the current working directory, which is probably where the Makefile is, but not always.

OUTPUT_PATH = /project1/bin/$(notdir $(CURDIR))

See Appendix A Quick Reference in http://www.gnu.org/software/make/manual/make.html

Simulate limited bandwidth from within Chrome?

As of today you can throttle your connection natively in Google Chrome Canary 46.0.2489.0. Simply open up Dev Tools and head over to the Network tab:

enter image description here

Docker: unable to prepare context: unable to evaluate symlinks in Dockerfile path: GetFileAttributesEx

In windows 10, period is first parameter

docker build . -t docker-whale

Firebase FCM notifications click_action payload

As far as I can tell, at this point it is not possible to set click_action in the console.

While not a strict answer to how to get the click_action set in the console, you can use curl as an alternative:

curl --header "Authorization: key=<YOUR_KEY_GOES_HERE>" --header Content-Type:"application/json" https://fcm.googleapis.com/fcm/send  -d "{\"to\":\"/topics/news\",\"notification\": {\"title\": \"Click Action Message\",\"text\": \"Sample message\",\"click_action\":\"OPEN_ACTIVITY_1\"}}"

This is an easy way to test click_action mapping. It requires an intent filter like the one specified in the FCM docs:

_x000D_
_x000D_
<intent-filter>_x000D_
  <action android:name="OPEN_ACTIVITY_1" />_x000D_
  <category android:name="android.intent.category.DEFAULT" />_x000D_
</intent-filter>
_x000D_
_x000D_
_x000D_

This also makes use of topics to set the audience. In order for this to work you will need to subscribe to a topic called "news".

FirebaseMessaging.getInstance().subscribeToTopic("news");

Even though it takes several hours to see a newly-created topic in the console, you may still send messages to it through the FCM apis.

Also, keep in mind, this will only work if the app is in the background. If it is in the foreground you will need to implement an extension of FirebaseMessagingService. In the onMessageReceived method, you will need to manually navigate to your click_action target:

    @Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    //This will give you the topic string from curl request (/topics/news)
    Log.d(TAG, "From: " + remoteMessage.getFrom());
    //This will give you the Text property in the curl request(Sample Message): 
    Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
    //This is where you get your click_action 
    Log.d(TAG, "Notification Click Action: " + remoteMessage.getNotification().getClickAction());
    //put code here to navigate based on click_action
}

As I said, at this time I cannot find a way to access notification payload properties through the console, but I thought this work around might be helpful.

How to refresh table contents in div using jquery/ajax

You can load HTML page partial, in your case is everything inside div#mytable.

setTimeout(function(){
   $( "#mytable" ).load( "your-current-page.html #mytable" );
}, 2000); //refresh every 2 seconds

more information read this http://api.jquery.com/load/

Update Code (if you don't want it auto-refresh)

<button id="refresh-btn">Refresh Table</button>

<script>
$(document).ready(function() {

   function RefreshTable() {
       $( "#mytable" ).load( "your-current-page.html #mytable" );
   }

   $("#refresh-btn").on("click", RefreshTable);

   // OR CAN THIS WAY
   //
   // $("#refresh-btn").on("click", function() {
   //    $( "#mytable" ).load( "your-current-page.html #mytable" );
   // });


});
</script>

Cast object to interface in TypeScript

If it helps anyone, I was having an issue where I wanted to treat an object as another type with a similar interface. I attempted the following:

Didn't pass linting

const x = new Obj(a as b);

The linter was complaining that a was missing properties that existed on b. In other words, a had some properties and methods of b, but not all. To work around this, I followed VS Code's suggestion:

Passed linting and testing

const x = new Obj(a as unknown as b);

Note that if your code attempts to call one of the properties that exists on type b that is not implemented on type a, you should realize a runtime fault.

boolean in an if statement

Since the checked value is Boolean it's preferred to use it directly for less coding and at all it did same ==true

Error: "The sandbox is not in sync with the Podfile.lock..." after installing RestKit with cocoapods

After many attemps I managed to fix this problem. Variable ${PODS_ROOT} was not set and I do below trick. Go to Build Phases -> Check Pods Manifest.lock and replace

diff "${PODS_ROOT}/../Podfile.lock" "${PODS_ROOT}/Manifest.lock" > /dev/null

to

diff "${SRCROOT}/Podfile.lock" "${SRCROOT}/Pods/Manifest.lock" > /dev/null

It helps me.

What is a regex to match ONLY an empty string?

I would use a negative lookahead for any character:

^(?![\s\S])

This can only match if the input is totally empty, because the character class will match any character, including any of the various newline characters.

Bootstrap 3.0 - Fluid Grid that includes Fixed Column Sizes

There's really no easy way to mix fluid and fixed widths with Bootstrap 3. It's meant to be like this, as the grid system is designed to be a fluid, responsive thing. You could try hacking something up, but it would go against what the Responsive Grid system is trying to do, the intent of which is to make that layout flow across different device types.

If you need to stick with this layout, I'd consider laying out your page with custom CSS and not using the grid.

Android Studio Error: Error:CreateProcess error=216, This version of %1 is not compatible with the version of Windows you're running

I had the same issue, but I have resolved it the next:

1) Install jdk1.8...

2) In AndroidStudio File->Project Structure->SDK Location, select your directory where the JDK is located, by default Studio uses embedded JDK but for some reason it produces error=216.

3) Click Ok.

Compile a DLL in C/C++, then call it from another program

For VB6:

You need to declare your C functions as __stdcall, otherwise you get "invalid calling convention" type errors. About other your questions:

can I take arguments by pointer/reference from the VB front-end?

Yes, use ByRef/ByVal modifiers.

Can the DLL call a theoretical function in the front-end?

Yes, use AddressOf statement. You need to pass function pointer to dll before.

Or have a function take a "function pointer" (I don't even know if that's possible) from VB and call it?)

Yes, use AddressOf statement.

update (more questions appeared :)):

to load it into VB, do I just do the usual method (what I would do to load winsock.ocx or some other runtime, but find my DLL instead) or do I put an API call into a module?

You need to decaler API function in VB6 code, like next:

Private Declare Function SHGetSpecialFolderLocation Lib "shell32" _
   (ByVal hwndOwner As Long, _
    ByVal nFolder As Long, _
    ByRef pidl As Long) As Long

How to get file size in Java

Try this:

long length = f.length();

rbind error: "names do not match previous names"

The names of the first dataframe do not match the names of the second one. Just as the error message says.

> identical(names(xd.small[[1]]), names(xd.small[[2]]) )
[1] FALSE

If you do not care about the names of the 3rd or 4th columns of the second df, you can coerce them to be the same:

> names(xd.small[[1]]) <- names(xd.small[[2]]) 
> identical(names(xd.small[[1]]), names(xd.small[[2]]) )
[1] TRUE

Then things should proceed happily.

What is the difference between IQueryable<T> and IEnumerable<T>?

In simple words other major difference is that IEnumerable execute select query on server side, load data in-memory on client side and then filter data while IQueryable execute select query on server side with all filters.

HttpContext.Current.Request.Url.Host what it returns?

Try this:

string callbackurl = Request.Url.Host != "localhost" 
    ? Request.Url.Host : Request.Url.Authority;

This will work for local as well as production environment. Because the local uses url with port no that is possible using Url.Host.

How to draw lines in Java

In your class you should have:

public void paint(Graphics g){
   g.drawLine(x1, y1, x2, y2);
}

Then in code if there is needed you will change x1, y1, x2, y2 and call repaint();.

How to stop process from .BAT file?

As TASKKILL might be unavailable on some Home/basic editions of windows here some alternatives:

TSKILL processName

or

TSKILL PID

Have on mind that processName should not have the .exe suffix and is limited to 18 characters.

Another option is WMIC :

wmic Path win32_process Where "Caption Like 'MyProcess.exe'" Call Terminate

wmic offer even more flexibility than taskkill .With wmic Path win32_process get you can see the available fileds you can filter.

How to create a JavaScript callback for knowing when an image is loaded?

If you are using React.js, you could do this:

render() {

// ...

<img 
onLoad={() => this.onImgLoad({ item })}
onError={() => this.onImgLoad({ item })}

src={item.src} key={item.key}
ref={item.key} />

// ... }

Where:

  • - onLoad (...) now will called with something like this: { src: "https://......png", key:"1" } you can use this as "key" to know which images is loaded correctly and which not.
  • - onError(...) it is the same but for errors.
  • - the object "item" is something like this { key:"..", src:".."} you can use to store the images' URL and key in order to use in a list of images.

  • How to escape double quotes in JSON

    When and where to use \\\" instead. OK if you are like me you will feel just as silly as I did when I realized what I was doing after I found this thread.

    If you're making a .json text file/stream and importing the data from there then the main stream answer of just one backslash before the double quotes:\" is the one you're looking for.

    However if you're like me and you're trying to get the w3schools.com "Tryit Editor" to have a double quotes in the output of the JSON.parse(text), then the one you're looking for is the triple backslash double quotes \\\". This is because you're building your text string within an HTML <script> block, and the first double backslash inserts a single backslash into the string variable then the following backslash double quote inserts the double quote into the string so that the resulting script string contains the \" from the standard answer and the JSON parser will parse this as just the double quotes.

    <script>
      var text="{";
      text += '"quip":"\\\"If nobody is listening, then you\'re likely talking to the wrong audience.\\\""';
      text += "}";
      var obj=JSON.parse(text);
    </script>
    

    +1: since it's a JavaScript text string, a double backslash double quote \\" would work too; because the double quote does not need escaped within a single quoted string eg '\"' and '"' result in the same JS string.

    Store an array in HashMap

    HashMap<String, List<Integer>> map = new HashMap<String, List<Integer>>();
    HashMap<String, int[]> map = new HashMap<String, int[]>();
    

    pick one, for example

    HashMap<String, List<Integer>> map = new HashMap<String, List<Integer>>();
    map.put("Something", new ArrayList<Integer>());
    for (int i=0;i<numarulDeCopii; i++) {
        map.get("Something").add(coeficientUzura[i]); 
    }
    

    or just

    HashMap<String, int[]> map = new HashMap<String, int[]>();
    map.put("Something", coeficientUzura);
    

    Return JSON with error status code MVC

    The thing that worked for me (and that I took from another stackoverflow response), is to set the flag:

    Response.TrySkipIisCustomErrors = true;
    

    open failed: EACCES (Permission denied)

    I ran into a similar issue a while back.

    Your problem could be in two different areas. It's either how you're creating the file to write to, or your method of writing could be flawed in that it is phone dependent.

    If you're writing the file to a specific location on the SD card, try using Environment variables. They should always point to a valid location. Here's an example to write to the downloads folder:

    java.io.File xmlFile = new java.io.File(Environment
        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
         + "/Filename.xml");
    

    If you're writing the file to the application's internal storage. Try this example:

    java.io.File xmlFile = new java.io.File((getActivity()
       .getApplicationContext().getFileStreamPath("FileName.xml")
       .getPath()));
    

    Personally I rely on external libraries to handle the streaming to file. This one hasn't failed me yet.

    org.apache.commons.io.FileUtils.copyInputStreamToFile(is, file);
    

    I've lost data one too many times on a failed write command, so I rely on well-known and tested libraries for my IO heavy lifting.

    If the files are large, you may also want to look into running the IO in the background, or use callbacks.

    If you're already using environment variables, it could be a permissions issue. Check out Justin Fiedler's answer below.

    Inserting values into a SQL Server database using ado.net via C#

    you should remove last comma and as nrodic said your command is not correct.

    you should change it like this :

    SqlCommand cmd = new SqlCommand("INSERT INTO dbo.regist (" + " FirstName, Lastname, Username, Password, Age, Gender,Contact " + ") VALUES (" + " textBox1.Text, textBox2.Text, textBox3.Text, textBox4.Text, comboBox1.Text,comboBox2.Text,textBox7.Text" + ")", cn);
    

    How do I make an input field accept only letters in javaScript?

    If you want only letters - so from a to z, lower case or upper case, excluding everything else (numbers, blank spaces, symbols), you can modify your function like this:

    function validate() {
        if (document.myForm.name.value == "") {
            alert("Enter a name");
            document.myForm.name.focus();
            return false;
        }
        if (!/^[a-zA-Z]*$/g.test(document.myForm.name.value)) {
            alert("Invalid characters");
            document.myForm.name.focus();
            return false;
        }
    }
    

    Getting Current time to display in Label. VB.net

    Try This.....

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load    
        Timer1.Start()
    End Sub
    
    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        Label12.Text = TimeOfDay.ToString("h:mm:ss tt")
    End Sub
    

    How to tell if UIViewController's view is visible

    XCode 6.4, for iOS 8.4, ARC enabled

    Obviously lots of ways of doing it. The one that has worked for me is the following...

    @property(nonatomic, readonly, getter=isKeyWindow) BOOL keyWindow
    

    This can be used in any view controller in the following way,

    [self.view.window isKeyWindow]
    

    If you call this property in -(void)viewDidLoad you get 0, then if you call this after -(void)viewDidAppear:(BOOL)animated you get 1.

    Hope this helps someone. Thanks! Cheers.

    How do I get logs from all pods of a Kubernetes replication controller?

    I use this simple script to get a log from the pods of a deployment:

    #!/usr/bin/env bash
    
    DEPLOYMENT=$1
    
    for p in $(kubectl get pods | grep ^${DEPLOYMENT}- | cut -f 1 -d ' '); do 
        echo --------------------------- 
        echo $p 
        echo --------------------------- 
        kubectl logs $p
    done
    

    Gist of the script

    Usage: log_deployment.sh "deployment-name".

    Script will then show log of all pods that start with that "deployment-name".

    How do I determine the current operating system with Node.js

    when you are using 32bits node on 64bits windows(like node-webkit or atom-shell developers), process.platform will echo win32

    use

        function isOSWin64() {
          return process.arch === 'x64' || process.env.hasOwnProperty('PROCESSOR_ARCHITEW6432');
        }
    

    (check here for details)

    How to enable copy paste from between host machine and virtual machine in vmware, virtual machine is ubuntu

    If your VM already came with VMware Tools pre-installed, but this still isn't working for you--or if you install and still no luck--make sure you run Workstation or Player as Administrator. That fixed the issue for me.

    selenium get current url after loading a page

    It's been a little while since I coded with selenium, but your code looks ok to me. One thing to note is that if the element is not found, but the timeout is passed, I think the code will continue to execute. So you can do something like this:

    boolean exists = driver.findElements(By.xpath("//*[@id='someID']")).size() != 0
    

    What does the above boolean return? And are you sure selenium actually navigates to the expected page? (That may sound like a silly question but are you actually watching the pages change... selenium can be run remotely you know...)

    How to remove duplicate values from an array in PHP

    function arrayUnique($myArray)
    {
        $newArray = Array();
        if (is_array($myArray))
        {
            foreach($myArray as $key=>$val)
            {
                if (is_array($val))
                {
                    $val2 = arrayUnique($val);
                }
                else
                {
                    $val2 = $val;
                    $newArray=array_unique($myArray);
                    $newArray=deleteEmpty($newArray);
                    break;
                }
                if (!empty($val2))
                {
                    $newArray[$key] = $val2;
                }
            }
        }
        return ($newArray);
    }
    
    function deleteEmpty($myArray)
    {
        $retArray= Array();
        foreach($myArray as $key=>$val)
        {
            if (($key<>"") && ($val<>""))
            {
                $retArray[$key] = $val;
            }
        }
        return $retArray;
    }
    

    How do I get the current GPS location programmatically in Android?

    Simple Find Write Code in On Location Method

    public void onLocationChanged(Location location) {
        if (mCurrLocationMarker != null) {
            mCurrLocationMarker.remove();
        }
    
    
        //Place current location marker
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.title("Current Position");
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
        mCurrLocationMarker = mMap.addMarker(markerOptions);
    
        //move map camera
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(18));
    
        PolylineOptions pOptions = new PolylineOptions()
                .width(5)
                .color(Color.GREEN)
                .geodesic(true);
        for (int z = 0; z < routePoints.size(); z++) {
            LatLng point = routePoints.get(z);
            pOptions.add(point);
        }
        line = mMap.addPolyline(pOptions);
        routePoints.add(latLng);
    }
    

    Java: method to get position of a match in a String?

        String match = "hello";
        String text = "0123456789hello0123456789hello";
    
        int j = 0;
        String indxOfmatch = "";
    
        for (int i = -1; i < text.length()+1; i++) {
            j =  text.indexOf("hello", i);
            if (i>=j && j > -1) {
                indxOfmatch += text.indexOf("hello", i)+" ";
            }
        }
        System.out.println(indxOfmatch);
    

    How do I format date and time on ssrs report?

    The following is how I do it using Visual Studio 2017 for an RDL targetted for SSRS 2017:

    Right-click on the field in the textbox on the design surface and choose Placeholder Properties. Choose the Number panel and click on Date in the Category listbox, then select the formatting you are looking for in the Type listbox.

    .jar error - could not find or load main class

    Had this problem couldn't find the answer so i went looking on other threads, I found that i was making my app with 1.8 but for some reason my jre was out dated even though i remember updating it. I downloaded the lastes jre 8 and the jar file runs perfectly. Hope this helps.

    How to uninstall / completely remove Oracle 11g (client)?

    Do everything suggested by ziesemer.

    You may also want to remove from the registry:

    HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\<any Ora* drivers> keys     
    
    HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\ODBC Drivers<any Ora* driver> values
    

    So they no longer appear in the "ODBC Drivers that are installed on your system" in ODBC Data Source Administrator

    Simulate CREATE DATABASE IF NOT EXISTS for PostgreSQL?

    PostgreSQL does not support IF NOT EXISTS for CREATE DATABASE statement. It is supported only in CREATE SCHEMA. Moreover CREATE DATABASE cannot be issued in transaction therefore it cannot be in DO block with exception catching.

    When CREATE SCHEMA IF NOT EXISTS is issued and schema already exists then notice (not error) with duplicate object information is raised.

    To solve these problems you need to use dblink extension which opens a new connection to database server and execute query without entering into transaction. You can reuse connection parameters with supplying empty string.

    Below is PL/pgSQL code which fully simulates CREATE DATABASE IF NOT EXISTS with same behavior like in CREATE SCHEMA IF NOT EXISTS. It calls CREATE DATABASE via dblink, catch duplicate_database exception (which is issued when database already exists) and converts it into notice with propagating errcode. String message has appended , skipping in the same way how it does CREATE SCHEMA IF NOT EXISTS.

    CREATE EXTENSION IF NOT EXISTS dblink;
    
    DO $$
    BEGIN
    PERFORM dblink_exec('', 'CREATE DATABASE testdb');
    EXCEPTION WHEN duplicate_database THEN RAISE NOTICE '%, skipping', SQLERRM USING ERRCODE = SQLSTATE;
    END
    $$;
    

    This solution is without any race condition like in other answers, where database can be created by external process (or other instance of same script) between checking if database exists and its own creation.

    Moreover when CREATE DATABASE fails with other error than database already exists then this error is propagated as error and not silently discarded. There is only catch for duplicate_database error. So it really behaves as IF NOT EXISTS should.

    You can put this code into own function, call it directly or from transaction. Just rollback (restore dropped database) would not work.

    Testing output (called two times via DO and then directly):

    $ sudo -u postgres psql
    psql (9.6.12)
    Type "help" for help.
    
    postgres=# \set ON_ERROR_STOP on
    postgres=# \set VERBOSITY verbose
    postgres=# 
    postgres=# CREATE EXTENSION IF NOT EXISTS dblink;
    CREATE EXTENSION
    postgres=# DO $$
    postgres$# BEGIN
    postgres$# PERFORM dblink_exec('', 'CREATE DATABASE testdb');
    postgres$# EXCEPTION WHEN duplicate_database THEN RAISE NOTICE '%, skipping', SQLERRM USING ERRCODE = SQLSTATE;
    postgres$# END
    postgres$# $$;
    DO
    postgres=# 
    postgres=# CREATE EXTENSION IF NOT EXISTS dblink;
    NOTICE:  42710: extension "dblink" already exists, skipping
    LOCATION:  CreateExtension, extension.c:1539
    CREATE EXTENSION
    postgres=# DO $$
    postgres$# BEGIN
    postgres$# PERFORM dblink_exec('', 'CREATE DATABASE testdb');
    postgres$# EXCEPTION WHEN duplicate_database THEN RAISE NOTICE '%, skipping', SQLERRM USING ERRCODE = SQLSTATE;
    postgres$# END
    postgres$# $$;
    NOTICE:  42P04: database "testdb" already exists, skipping
    LOCATION:  exec_stmt_raise, pl_exec.c:3165
    DO
    postgres=# 
    postgres=# CREATE DATABASE testdb;
    ERROR:  42P04: database "testdb" already exists
    LOCATION:  createdb, dbcommands.c:467
    

    Storing data into list with class

    And if you want to create the list with some elements to start with:

    var emailList = new List<EmailData>
    {
       new EmailData { FirstName = "John", LastName = "Doe", Location = "Moscow" },
       new EmailData {.......}
    };
    

    "Auth Failed" error with EGit and GitHub

    For *nix users who are using SSH:

    Make sure the username for your account on your local machine does not differ from the username for the account on the server. Apparently, eGit does not seem to be able to handle this. For example, if your username on your local machine is 'john', and the account you are using on the server is named 'git', egit simply fails to connect (for me anyways). The only work around I have found is to make sure you have identical usernames in both the local machine and the server.

    TortoiseSVN icons overlay not showing after updating to Windows 10

    Tortoise Settings > Icon Overlays -> Overlay Handlers -> Start registry editor

    1. Rename icon name :By adding a space(s) at the beginning of the file's name and then press F5 until it goes to top . example: " Tortoise1Normal" (in default 2 spaces included)? " Tortoise1Normal" (3 spaces)

    2. Restart explorer in Task manager

    Registry

    How to set the java.library.path from Eclipse

    Here is another fix:

    My build system (Gradle) added a required native library (dll) to the Eclipse build path (Right Click on Project -> Properties -> Java Build Path -> Libraries). Telling the build system not to add the native dll library to the Eclipse classpath solved the problem.

    How to check if a std::string is set or not?

    You can't; at least not the same way you can test whether a pointer is NULL.

    A std::string object is always initialized and always contains a string; its contents by default are an empty string ("").

    You can test for emptiness (using s.size() == 0 or s.empty()).

    How to view the contents of an Android APK file?

    There is also zzos. (Full disclosure: I wrote it). It only decompiles the actual resources, not the dex part (baksmali, which I did not write, does an excellent job of handling that part).

    Zzos is much less known than apktool, but there are some APKs that are better handled by it (and vice versa - more on that later). Mostly, APKs containing custom resource types (not modifiers) were not handled by apktool the last time I checked, and are handled by zzos. There are also some cases with escaping that zzos handles better.

    On the negative side of things, zzos (current version) requires a few support tools to install. It is written in perl (as opposed to APKTool, which is written in Java), and uses aapt for the actual decompilation. It also does not decompile attrib resources yet (which APKTool does).

    The meaning of the name is "aapt", Android's resource compiler, shifted down one letter.

    Eclipse reported "Failed to load JNI shared library"

    First, ensure that your version of Eclipse and JDK match, either both 64-bit or both 32-bit (you can't mix-and-match 32-bit with 64-bit).

    Second, the -vm argument in eclipse.ini should point to the java executable. See http://wiki.eclipse.org/Eclipse.ini for examples.

    If you're unsure of what version (64-bit or 32-bit) of Eclipse you have installed, you can determine that a few different ways. See How to find out if an installed Eclipse is 32 or 64 bit version?

    Convert Mongoose docs to json

    Try this options:

      UserModel.find({}, function (err, users) {
        //i got into errors using so i changed to res.send()
        return res.send( JSON.parse(JSON.stringify(users)) );
        //Or
        //return JSON.parse(JSON.stringify(users));
      }
    

    How can I display a JavaScript object?

    A little helper function I always use in my projects for simple, speedy debugging via the console. Inspiration taken from Laravel.

    /**
     * @param variable mixed  The var to log to the console
     * @param varName string  Optional, will appear as a label before the var
     */
    function dd(variable, varName) {
        var varNameOutput;
    
        varName = varName || '';
        varNameOutput = varName ? varName + ':' : '';
    
        console.warn(varNameOutput, variable, ' (' + (typeof variable) + ')');
    }
    

    Usage

    dd(123.55); outputs:
    enter image description here

    var obj = {field1: 'xyz', field2: 2016};
    dd(obj, 'My Cool Obj'); 
    

    enter image description here

    Required attribute HTML5

    A small note on custom attributes: HTML5 allows all kind of custom attributes, as long as they are prefixed with the particle data-, i.e. data-my-attribute="true".

    How can I reconcile detached HEAD with master/origin?

    Just do this:

    git checkout master
    

    Or, if you have changes that you want to keep, do this:

    git checkout -b temp
    git checkout -B master temp
    

    Change marker size in Google maps V3

    This answer expounds on John Black's helpful answer, so I will repeat some of his answer content in my answer.

    The easiest way to resize a marker seems to be leaving argument 2, 3, and 4 null and scaling the size in argument 5.

    var pinIcon = new google.maps.MarkerImage(
        "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|FFFF00",
        null, /* size is determined at runtime */
        null, /* origin is 0,0 */
        null, /* anchor is bottom center of the scaled image */
        new google.maps.Size(42, 68)
    );  
    

    As an aside, this answer to a similar question asserts that defining marker size in the 2nd argument is better than scaling in the 5th argument. I don't know if this is true.

    Leaving arguments 2-4 null works great for the default google pin image, but you must set an anchor explicitly for the default google pin shadow image, or it will look like this:

    what happens when you leave anchor null on an enlarged shadow

    The bottom center of the pin image happens to be collocated with the tip of the pin when you view the graphic on the map. This is important, because the marker's position property (marker's LatLng position on the map) will automatically be collocated with the visual tip of the pin when you leave the anchor (4th argument) null. In other words, leaving the anchor null ensures the tip points where it is supposed to point.

    However, the tip of the shadow is not located at the bottom center. So you need to set the 4th argument explicitly to offset the tip of the pin shadow so the shadow's tip will be colocated with the pin image's tip.

    By experimenting I found the tip of the shadow should be set like this: x is 1/3 of size and y is 100% of size.

    var pinShadow = new google.maps.MarkerImage(
        "http://chart.apis.google.com/chart?chst=d_map_pin_shadow",
        null,
        null,
        /* Offset x axis 33% of overall size, Offset y axis 100% of overall size */
        new google.maps.Point(40, 110), 
        new google.maps.Size(120, 110)); 
    

    to give this:

    offset the enlarged shadow anchor explicitly

    How to call function on child component on parent events

    You can use $emit and $on. Using @RoyJ code:

    html:

    <div id="app">
      <my-component></my-component>
      <button @click="click">Click</button>  
    </div>
    

    javascript:

    var Child = {
      template: '<div>{{value}}</div>',
      data: function () {
        return {
          value: 0
        };
      },
      methods: {
        setValue: function(value) {
            this.value = value;
        }
      },
      created: function() {
        this.$parent.$on('update', this.setValue);
      }
    }
    
    new Vue({
      el: '#app',
      components: {
        'my-component': Child
      },
      methods: {
        click: function() {
            this.$emit('update', 7);
        }
      }
    })
    

    Running example: https://jsfiddle.net/rjurado/m2spy60r/1/

    Get the first element of an array

    Nice one with a combination of array_slice and implode:

    $arr = array(1, 2, 3);
    echo implode(array_slice($arr, 0, 1));
    // Outputs 1
    
    /*---------------------------------*/
    
    $arr = array(
        'key_1' => 'One',
        'key_2' => 'Two',
        'key_3' => 'Three',
    );
    echo implode(array_slice($arr, 0, 1));
    // Outputs One
    

    How to use doxygen to create UML class diagrams from C++ source

    Quote from this post (it's written by the author of doxygen himself) :

    run doxygen -g and change the following options of the generated Doxyfile:
    
        EXTRACT_ALL            = YES
        HAVE_DOT               = YES
        UML_LOOK               = YES
    
    run doxygen again
    

    Download file from an ASP.NET Web API method using AngularJS

    For me the Web API was Rails and client side Angular used with Restangular and FileSaver.js

    Web API

    module Api
      module V1
        class DownloadsController < BaseController
    
          def show
            @download = Download.find(params[:id])
            send_data @download.blob_data
          end
        end
      end
    end
    

    HTML

     <a ng-click="download('foo')">download presentation</a>
    

    Angular controller

     $scope.download = function(type) {
        return Download.get(type);
      };
    

    Angular Service

    'use strict';
    
    app.service('Download', function Download(Restangular) {
    
      this.get = function(id) {
        return Restangular.one('api/v1/downloads', id).withHttpConfig({responseType: 'arraybuffer'}).get().then(function(data){
          console.log(data)
          var blob = new Blob([data], {
            type: "application/pdf"
          });
          //saveAs provided by FileSaver.js
          saveAs(blob, id + '.pdf');
        })
      }
    });
    

    How to customize the back button on ActionBar

    tray this:

    getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_close);
    

    inside onCreate();

    SQlite - Android - Foreign key syntax

    Since I cannot comment, adding this note in addition to @jethro answer.

    I found out that you also need to do the FOREIGN KEY line as the last part of create the table statement, otherwise you will get a syntax error when installing your app. What I mean is, you cannot do something like this:

    private static final String TASK_TABLE_CREATE = "create table "
        + TASK_TABLE + " (" + TASK_ID
        + " integer primary key autoincrement, " + TASK_TITLE
        + " text not null, " + TASK_NOTES + " text not null, "
    + TASK_CAT + " integer,"
    + " FOREIGN KEY ("+TASK_CAT+") REFERENCES "+CAT_TABLE+" ("+CAT_ID+"), "
    + TASK_DATE_TIME + " text not null);";
    

    Where I put the TASK_DATE_TIME after the foreign key line.

    How to modify a global variable within a function in bash?

    When you use a command substitution (i.e., the $(...) construct), you are creating a subshell. Subshells inherit variables from their parent shells, but this only works one way: A subshell cannot modify the environment of its parent shell.

    Your variable e is set within a subshell, but not the parent shell. There are two ways to pass values from a subshell to its parent. First, you can output something to stdout, then capture it with a command substitution:

    myfunc() {
        echo "Hello"
    }
    
    var="$(myfunc)"
    
    echo "$var"
    

    The above outputs:

    Hello
    

    For a numerical value in the range of 0 through 255, you can use return to pass the number as the exit status:

    mysecondfunc() {
        echo "Hello"
        return 4
    }
    
    var="$(mysecondfunc)"
    num_var=$?
    
    echo "$var - num is $num_var"
    

    This outputs:

    Hello - num is 4
    

    How to get height of entire document with JavaScript?

    The "jQuery method" of determining the document size - query everything, take the highest value, and hope for the best - works in most cases, but not in all of them .

    If you really need bullet-proof results for the document size, I'd suggest you use my jQuery.documentSize plugin. Unlike the other methods, it actually tests and evaluates browser behaviour when it is loaded and, based on the result, queries the right property from there on out.

    The impact of this one-time test on performance is minimal, and the plugin returns the right results in even the weirdest scenarios - not because I say so, but because a massive, auto-generated test suite actually verifies that it does.

    Because the plugin is written in vanilla Javascript, you can use it without jQuery, too.

    How to determine whether a substring is in a different string

    def find_substring():
        s = 'bobobnnnnbobmmmbosssbob'
        cnt = 0
        for i in range(len(s)):
            if s[i:i+3] == 'bob':
                cnt += 1
        print 'bob found: ' + str(cnt)
        return cnt
    
    def main():
        print(find_substring())
    
    main()
    

    How do I get the total number of unique pairs of a set in the database?

    What you're looking for is n choose k. Basically:

    enter image description here

    For every pair of 100 items, you'd have 4,950 combinations - provided order doesn't matter (AB and BA are considered a single combination) and you don't want to repeat (AA is not a valid pair).

    pandas three-way joining multiple dataframes on columns

    In python 3.6.3 with pandas 0.22.0 you can also use concat as long as you set as index the columns you want to use for the joining

    pd.concat(
        (iDF.set_index('name') for iDF in [df1, df2, df3]),
        axis=1, join='inner'
    ).reset_index()
    

    where df1, df2, and df3 are defined as in John Galt's answer

    import pandas as pd
    df1 = pd.DataFrame(np.array([
        ['a', 5, 9],
        ['b', 4, 61],
        ['c', 24, 9]]),
        columns=['name', 'attr11', 'attr12']
    )
    df2 = pd.DataFrame(np.array([
        ['a', 5, 19],
        ['b', 14, 16],
        ['c', 4, 9]]),
        columns=['name', 'attr21', 'attr22']
    )
    df3 = pd.DataFrame(np.array([
        ['a', 15, 49],
        ['b', 4, 36],
        ['c', 14, 9]]),
        columns=['name', 'attr31', 'attr32']
    )
    

    How to create empty constructor for data class in Kotlin Android

    the modern answer for this should be using Kotlin's no-arg compiler plugin which creates a non argument construct code for classic apies more about here

    simply you have to add the plugin class path in build.gradle project level

        dependencies {
        ....
    
        classpath "org.jetbrains.kotlin:kotlin-noarg:1.4.10"
    
        ....
        }
    

    then configure your annotation to generate the no-arg constructor

    apply plugin: "kotlin-noarg"
    
    noArg {
          annotation("your.path.to.annotaion.NoArg")
          invokeInitializers = true
    }
    

    then define your annotation file NoArg.kt

     @Target(AnnotationTarget.CLASS)
     @Retention(AnnotationRetention.SOURCE)
     annotation class NoArg
    

    finally in any data class you can simply use your own annotation

    @NoArg
    data class SomeClass( val datafield:Type , ...   )
    

    I used to create my own no-arg constructor as the accepted answer , which i got by search but then this plugin released or something and I found it way cleaner .

    What is the difference between HTTP status code 200 (cache) vs status code 304?

    200 (cache) means Firefox is simply using the locally cached version. This is the fastest because no request to the Web server is made.

    304 means Firefox is sending a "If-Modified-Since" conditional request to the Web server. If the file has not been updated since the date sent by the browser, the Web server returns a 304 response which essentially tells Firefox to use its cached version. It is not as fast as 200 (cache) because the request is still sent to the Web server, but the server doesn't have to send the contents of the file.

    To your last question, I don't know why the two JavaScript files in the same directory are returning different results.

    Cannot redeclare function php

    Remove the function and check the output of:

    var_dump(function_exists('parseDate'));
    

    In which case, change the name of the function.

    If you get false, you're including the file with that function twice, replace :

    include
    

    by

    include_once
    

    And replace :

    require
    

    by

    require_once
    

    EDIT : I'm just a little too late, post before beat me to it !

    Ionic android build Error - Failed to find 'ANDROID_HOME' environment variable

    To add ANDROID_HOME value permanently,

    gedit ~/.bashrc
    

    and add the following lines

    export ANDROID_HOME=/root/Android/Sdk
    PATH=$PATH:$ANDROID_HOME/tools
    

    Save the file and you need not update ANDROID_HOME value everytime.

    Array versus linked-list

    Linked List are more of an overhead to maintain than array, it also requires additional memory storage all these points are agreed. But there are a few things which array cant do. In many cases suppose you want an array of length 10^9 you can't get it because getting one continous memory location has to be there. Linked list could be a saviour here.

    Suppose you want to store multiple things with data then they can be easily extended in the linked list.

    STL containers usually have linked list implementation behind the scene.

    Making view resize to its parent when added with addSubview

    Tested in Xcode 9.4, Swift 4 Another way to solve this issue is , You can add

    override func layoutSubviews() {
            self.frame = (self.superview?.bounds)!
        }
    

    in subview class.

    Error in Chrome only: XMLHttpRequest cannot load file URL No 'Access-Control-Allow-Origin' header is present on the requested resource

    add this at the top of file,

    header('content-type: application/json; charset=utf-8');
    header("access-control-allow-origin: *");
    

    Displaying a Table in Django from Database

    The easiest way is to use a for loop template tag.

    Given the view:

    def MyView(request):
        ...
        query_results = YourModel.objects.all()
        ...
        #return a response to your template and add query_results to the context
    

    You can add a snippet like this your template...

    <table>
        <tr>
            <th>Field 1</th>
            ...
            <th>Field N</th>
        </tr>
        {% for item in query_results %}
        <tr> 
            <td>{{ item.field1 }}</td>
            ...
            <td>{{ item.fieldN }}</td>
        </tr>
        {% endfor %}
    </table>
    

    This is all covered in Part 3 of the Django tutorial. And here's Part 1 if you need to start there.

    Where to find "Microsoft.VisualStudio.TestTools.UnitTesting" missing dll?

    To resolve this issue, I had to do the following:

    1. Launch the Visual Studio Installer with administrative privileges
    2. If it prompts you to install updates to Visual Studio, do so before continuing
    3. When prompted, click the button to Modify the existing installation
    4. Click on the "Individual components" tab / header along the top
    5. Scroll down to the "Debugging and testing" section
    6. Check the box next to "Web performance and load testing tools"
    7. Click the Modify button on the bottom right corner of the dialog to install the missing DLLs

    Once the DLLs are installed, you can add references to them using the method that Agent007 indicated in his answer.

    how to insert a new line character in a string to PrintStream then use a scanner to re-read the file

    The linefeed character \n is not the line separator in certain operating systems (such as windows, where it's "\r\n") - my suggestion is that you use \r\n instead, then it'll both see the line-break with only \n and \r\n, I've never had any problems using it.

    Also, you should look into using a StringBuilder instead of concatenating the String in the while-loop at BookCatalog.toString(), it is a lot more effective. For instance:

    public String toString() {
            BookNode current = front;
            StringBuilder sb = new StringBuilder();
            while (current!=null){
                sb.append(current.getData().toString()+"\r\n ");
                current = current.getNext();
            }
            return sb.toString();
    }
    

    grid controls for ASP.NET MVC?

    I just discovered Telerik has some great components, including Grid, and they are open source too. http://demos.telerik.com/aspnet-mvc/

    Selenium using Java - The path to the driver executable must be set by the webdriver.gecko.driver system property

    Every Driver service in selenium calls the similar code(following is the firefox specific code) while creating the driver object

     @Override
     protected File findDefaultExecutable() {
          return findExecutable(
            "geckodriver", GECKO_DRIVER_EXE_PROPERTY,
            "https://github.com/mozilla/geckodriver",
            "https://github.com/mozilla/geckodriver/releases");
        }
    

    now for the driver that you want to use, you have to set the system property with the value of path to the driver executable.

    for firefox GECKO_DRIVER_EXE_PROPERTY = "webdriver.gecko.driver" and this can be set before creating the driver object as below

    System.setProperty("webdriver.gecko.driver", "./libs/geckodriver.exe");
    WebDriver driver = new FirefoxDriver();
    

    Assigning variables with dynamic names in Java

    What you need is named array. I wanted to write the following code:

    int[] n = new int[4];
    
    for(int i=1;i<4;i++)
    {
        n[i] = 5;
    }
    

    Dilemma: when to use Fragments vs Activities:

    My philosophy is this:

    Create an activity only if it's absolutely absolutely required. With the back stack made available for committing bunch of fragment transactions, I try to create as few activities in my app as possible. Also, communicating between various fragments is much easier than sending data back and forth between activities.

    Activity transitions are expensive, right? At least I believe so - since the old activity has to be destroyed/paused/stopped, pushed onto the stack, and then the new activity has to be created/started/resumed.

    It's just my philosophy since fragments were introduced.

    PostgreSQL "DESCRIBE TABLE"

    /dt is the commad which lists you all the tables present in a database. using
    /d command and /d+ we can get the details of a table. The sysntax will be like
    * /d table_name (or) \d+ table_name

    What version of Java is running in Eclipse?

    The one the eclipse run in is the default java installed in the system (unless set specifically in the eclipse.ini file, use the -vm option). You can of course add more Java runtimes and use them for your projects

    The string you've written is the right one, but it is specific to your environment. If you want to know the exact update then run the following code:

    public class JavaVersion {
      public static void main(String[] args) {
        System.out.println(System.getProperty("java.runtime.version"));
      }
    }
    

    Joining 2 SQL SELECT result sets into one

    Use a FULL OUTER JOIN:

    select 
       a.col_a,
       a.col_b,
       b.col_c
    from
       (select col_a,col_bfrom tab1) a
    join 
       (select col_a,col_cfrom tab2) b 
    on a.col_a= b.col_a
    

    No @XmlRootElement generated by JAXB

    The topic is quite old but still relevant in enterprise business contexts. I tried to avoid to touch the xsds in order to easily update them in the future. Here are my solutions..

    1. Mostly xjc:simple is sufficient

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <jxb:bindings version="2.0" xmlns:jxb="http://java.sun.com/xml/ns/jaxb"
        xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
        jxb:extensionBindingPrefixes="xjc">
    
        <jxb:globalBindings>
            <xjc:simple/> <!-- adds @XmlRootElement annotations -->
        </jxb:globalBindings>
    
    </jxb:bindings>
    

    It will mostly create XmlRootElements for importing xsd definitions.

    2. Divide your jaxb2-maven-plugin executions

    I have encountered that it makes a huge difference if you try to generate classes from multiple xsd definitions instead of a execution definition per xsd.

    So if you have a definition with multiple <source>'s, than just try to split them:

              <execution>
                <id>xjc-schema-1</id>
                <goals>
                  <goal>xjc</goal>
                </goals>
                <configuration>
                  <xjbSources>
                    <xjbSource>src/main/resources/xsd/binding.xjb</xjbSource>
                  </xjbSources>
                  <sources>
                    <source>src/main/resources/xsd/definition1/</source>
                  </sources>
                  <clearOutputDir>false</clearOutputDir>
                </configuration>
              </execution>
    
              <execution>
                <id>xjc-schema-2</id>
                <goals>
                  <goal>xjc</goal>
                </goals>
                <configuration>
                  <xjbSources>
                    <xjbSource>src/main/resources/xsd/binding.xjb</xjbSource>
                  </xjbSources>
                  <sources>
                    <source>src/main/resources/xsd/definition2/</source>
                  </sources>
                  <clearOutputDir>false</clearOutputDir>
                </configuration>
              </execution>
    

    The generator will not catch the fact that one class might be sufficient and therefore create custom classes per execution. And thats exactly what I need ;).

    Xcode "Build and Archive" from command line

    The xcodebuild tool can build and export archive products with the -exportArchive flag (as of Xcode 5). The export step was previously only possible via the Xcode Organizer UI.

    First archive your app:

    xcodebuild -scheme <scheme name> archive
    

    Given $ARCHIVE_PATH (the path to the .xcarchive file), export the app from the archive with one of the following:

    iOS .ipa file:

    xcodebuild -exportArchive -exportFormat ipa -archivePath "$ARCHIVE_PATH" -exportPath "myApp.ipa" -exportProvisioningProfile "My App Provisioning profile"
    

    Mac .app file:

    xcodebuild -exportArchive -exportFormat app -archivePath "$ARCHIVE_PATH" -exportPath "myApp.app" -exportSigningIdentity "Developer ID Application: My Software Company"
    

    In both commands the -exportProvisioningProfile and -exportSigningIdentity arguments are optional. man xcodebuild for details on the semantics. In these examples, the provisioning profile for the iOS build specified an AdHoc distribution provisioning profile, and the signing identity for the Mac app specified a Developer ID for export as a 3rd party application (i.e. not distributed via the Mac App Store).

    Custom alert and confirm box in jquery

    jQuery UI has it's own elements, but jQuery alone hasn't.

    http://jqueryui.com/dialog/

    Working example:

    <!doctype html>
    
    <html lang="en">
    <head>
      <meta charset="utf-8" />
      <title>jQuery UI Dialog - Default functionality</title>
      <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
      <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
      <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
      <link rel="stylesheet" href="/resources/demos/style.css" />
      <script>
      $(function() {
        $( "#dialog" ).dialog();
      });
      </script>
    </head>
    <body>
    
    <div id="dialog" title="Basic dialog">
      <p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
    </div>
    
    
    </body>
    </html>
    

    How to use PrintWriter and File classes in Java?

    Java doesn't normally accept "/" to use in defining a file directory, so try this:

     File file = new File ("C:\\Users\\user\\workspace\\FileTester\\myFile.txt");
    

    If the file doesn't exist do:

     try {
          file.createNewFile();
     }
     catch (IOException e) {
     e.printStackTrace();
     }
    

    Determine which MySQL configuration file is being used

    If you are on Linux, then start the 'mysqld' with strace, for eg strace ./mysqld.

    Among all the other system calls, you will find something like:

    stat64("/etc/my.cnf", 0xbfa3d7fc)       = -1 ENOENT (No such file or directory)
    stat64("/etc/mysql/my.cnf", {st_mode=S_IFREG|0644, st_size=4227, ...}) = 0
    open("/etc/mysql/my.cnf", O_RDONLY|O_LARGEFILE) = 3
    

    So, as you can see..it lists the .cnf files, that it attempts to use and finally uses.

    Calling Javascript from a html form

    Everything seems to be perfect in your code except the fact that handleClick() isn't working because this function lacks a parameter in its function call invocation(but the function definition within has an argument which makes a function mismatch to occur).

    The following is a sample working code for calculating all semester's total marks and corresponding grade. It demonstrates the use of a JavaScript function(call) within a html file and also solves the problem you are facing.

    <!DOCTYPE html>
    <html>
    <head>
        <title> Semester Results </title>
    </head>
    <body>
        <h1> Semester Marks </h1> <br> 
        <script type = "text/javascript">
            function checkMarks(total)
            {
                document.write("<h1> Final Result !!! </h1><br>");
                document.write("Total Marks = " + total + "<br><br>");
                var avg = total / 6.0;
                document.write("CGPA = " + (avg / 10.0).toFixed(2) + "<br><br>");
                if(avg >= 90)
                    document.write("Grade = A");
                else if(avg >= 80)
                    document.write("Grade = B");
                else if(avg >= 70)
                    document.write("Grade = C");
                else if(avg >= 60)
                    document.write("Grade = D");
                else if(avg >= 50)
                    document.write("Grade = Pass");
                else
                    document.write("Grade = Fail");
           }
        </script>
        <form name = "myform" action = "javascript:checkMarks(Number(s1.value) + Number(s2.value) + Number(s3.value) + Number(s4.value) + Number(s5.value) + Number(s6.value))"/>
            Semester 1:  <input type = "text" id = "s1"/> <br><br>
            Semester 2:  <input type = "text" id = "s2"/> <br><br>
            Semester 3:  <input type = "text" id = "s3"/> <br><br>
            Semester 4:  <input type = "text" id = "s4"/> <br><br>
            Semester 5:  <input type = "text" id = "s5"/> <br><br>
            Semester 6:  <input type = "text" id = "s6"/> <br><br><br>
            <input type = "submit" value = "Submit"/>
        </form>
    </body>
    </html>
    

    How to configure slf4j-simple

    You can programatically change it by setting the system property:

    public class App {
    
        public static void main(String[] args) {
    
            System.setProperty(org.slf4j.impl.SimpleLogger.DEFAULT_LOG_LEVEL_KEY, "TRACE");
    
            final org.slf4j.Logger log = LoggerFactory.getLogger(App.class);
    
            log.trace("trace");
            log.debug("debug");
            log.info("info");
            log.warn("warning");
            log.error("error");
    
        }
    }
    

    The log levels are ERROR > WARN > INFO > DEBUG > TRACE.

    Please note that once the logger is created the log level can't be changed. If you need to dynamically change the logging level you might want to use log4j with SLF4J.

    How to search text using php if ($text contains "World")

    In your case you can just use strpos(), or stripos() for case insensitive search:

    if (stripos($text, "world") !== false) {
        echo "True";
    }
    

    Creating a new empty branch for a new project

    If your git version does not have the --orphan option, this method should be used:

    git symbolic-ref HEAD refs/heads/<newbranch> 
    rm .git/index 
    git clean -fdx 
    

    After doing some work:

    git add -A
    git commit -m <message>
    git push origin <newbranch>
    

    Printing one character at a time from a string, using the while loop

    Try this instead ...

    Printing each character using while loop

    i=0
    x="abc"
    while i<len(x) :
        print(x[i],end=" ")
        print(i)
        i+=1
    

    jQuery callback for multiple ajax calls

    Looks like you've got some answers to this, however I think there is something worth mentioning here that will greatly simplify your code. jQuery introduced the $.when in v1.5. It looks like:

    $.when($.ajax(...), $.ajax(...)).then(function (resp1, resp2) {
        //this callback will be fired once all ajax calls have finished.
    });
    

    Didn't see it mentioned here, hope it helps.

    How can I use the apply() function for a single column?

    Let me try a complex computation using datetime and considering nulls or empty spaces. I am reducing 30 years on a datetime column and using apply method as well as lambda and converting datetime format. Line if x != '' else x will take care of all empty spaces or nulls accordingly.

    df['Date'] = df['Date'].fillna('')
    df['Date'] = df['Date'].apply(lambda x : ((datetime.datetime.strptime(str(x), '%m/%d/%Y') - datetime.timedelta(days=30*365)).strftime('%Y%m%d')) if x != '' else x)
    

    JavaScript sleep/wait before continuing

    JS does not have a sleep function, it has setTimeout() or setInterval() functions.

    If you can move the code that you need to run after the pause into the setTimeout() callback, you can do something like this:

    //code before the pause
    setTimeout(function(){
        //do what you need here
    }, 2000);
    

    see example here : http://jsfiddle.net/9LZQp/

    This won't halt the execution of your script, but due to the fact that setTimeout() is an asynchronous function, this code

    console.log("HELLO");
    setTimeout(function(){
        console.log("THIS IS");
    }, 2000);
    console.log("DOG");
    

    will print this in the console:

    HELLO
    DOG
    THIS IS
    

    (note that DOG is printed before THIS IS)


    You can use the following code to simulate a sleep for short periods of time:

    function sleep(milliseconds) {
      var start = new Date().getTime();
      for (var i = 0; i < 1e7; i++) {
        if ((new Date().getTime() - start) > milliseconds){
          break;
        }
      }
    }
    

    now, if you want to sleep for 1 second, just use:

    sleep(1000);
    

    example: http://jsfiddle.net/HrJku/1/

    please note that this code will keep your script busy for n milliseconds. This will not only stop execution of Javascript on your page, but depending on the browser implementation, may possibly make the page completely unresponsive, and possibly make the entire browser unresponsive. In other words this is almost always the wrong thing to do.

    Getting java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory exception

    Adding commons-logging.jar or commons-logging-1.1.jar will solve this...

    Inverse of a matrix using numpy

    Another way to do this is to use the numpy matrix class (rather than a numpy array) and the I attribute. For example:

    >>> m = np.matrix([[2,3],[4,5]])
    >>> m.I
    matrix([[-2.5,  1.5],
           [ 2. , -1. ]])
    

    "Too many characters in character literal error"

    I believe you can do this using a Unicode encoding, but I doubt this is what you really want.

    The == is the unicode value 2A76 so I belive you can do this:

    char c = '\u2A76';
    

    I can't test this at the moment but I'd be interested to know if that works for you.

    You will need to dig around for the others. Here is a unicode table if you want to look:

    http://www.tamasoft.co.jp/en/general-info/unicode.html

    Access parent URL from iframe

    If your iframe is from another domain, (cross domain), you will simply need to use this:

    var currentUrl = document.referrer;
    

    and - here you've got the main url!

    How do I restart nginx only after the configuration test was successful on Ubuntu?

    I use the following command to reload Nginx (version 1.5.9) only if a configuration test was successful:

    /etc/init.d/nginx configtest && sudo /etc/init.d/nginx reload
    

    If you need to do this often, you may want to use an alias. I use the following:

    alias n='/etc/init.d/nginx configtest && sudo /etc/init.d/nginx reload'
    

    The trick here is done by the "&&" which only executes the second command if the first was successful. You can see here a more detailed explanation of the use of the "&&" operator.

    You can use "restart" instead of "reload" if you really want to restart the server.

    Remote branch is not showing up in "git branch -r"

    I had the same issue. It seems the easiest solution is to just remove the remote, readd it, and fetch.

    How do you create optional arguments in php?

    The date function would be defined something like this:

    function date($format, $timestamp = null)
    {
        if ($timestamp === null) {
            $timestamp = time();
        }
    
        // Format the timestamp according to $format
    }
    

    Usually, you would put the default value like this:

    function foo($required, $optional = 42)
    {
        // This function can be passed one or more arguments
    }
    

    However, only literals are valid default arguments, which is why I used null as default argument in the first example, not $timestamp = time(), and combined it with a null check. Literals include arrays (array() or []), booleans, numbers, strings, and null.

    If "0" then leave the cell blank

    You can change the number format of the column to this custom format:

    0;-0;;@
    

    which will hide all 0 values.

    To do this, select the column, right-click > Format Cells > Custom.

    load external css file in body tag

    No, it is not okay to put a link element in the body tag. See the specification (links to the HTML4.01 specs, but I believe it is true for all versions of HTML):

    “This element defines a link. Unlike A, it may only appear in the HEAD section of a document, although it may appear any number of times.”

    Use of 'prototype' vs. 'this' in JavaScript?

    What's the difference? => A lot.

    I think, the this version is used to enable encapsulation, i.e. data hiding. It helps to manipulate private variables.

    Let us look at the following example:

    var AdultPerson = function() {
    
      var age;
    
      this.setAge = function(val) {
        // some housekeeping
        age = val >= 18 && val;
      };
    
      this.getAge = function() {
        return age;
      };
    
      this.isValid = function() {
        return !!age;
      };
    };
    

    Now, the prototype structure can be applied as following:

    Different adults have different ages, but all of the adults get the same rights.
    So, we add it using prototype, rather than this.

    AdultPerson.prototype.getRights = function() {
      // Should be valid
      return this.isValid() && ['Booze', 'Drive'];
    };
    

    Lets look at the implementation now.

    var p1 = new AdultPerson;
    p1.setAge(12); // ( age = false )
    console.log(p1.getRights()); // false ( Kid alert! )
    p1.setAge(19); // ( age = 19 )
    console.log(p1.getRights()); // ['Booze', 'Drive'] ( Welcome AdultPerson )
    
    var p2 = new AdultPerson;
    p2.setAge(45);    
    console.log(p2.getRights()); // The same getRights() method, *** not a new copy of it ***
    

    Hope this helps.

    Installing PG gem on OS X - failure to build native extension

    I am using OS X Mavericks (version 10.9)

    and when I run the above I got the following message: If builds of PostgreSQL 9 are failing and you have version 8.x installed.

    So I run the following command:

    ARCHFLAGS="-arch x86_64" gem install pg
    

    and this worked for me, I hope this helps someone :)

    What is the difference between C and embedded C?

    1: C is a type of computer programming language. While embedded C is a set of language extensions for the C Programming language.

    2: C has a free-format program source code, in a desktop computer. while embedded C has different format based on embedded processor (micro- controllers/microprocessors).

    3: C have normal optimization, in programming. while embedded C high level optimization in programming.

    4: C programming must have required operating system. while embedded C may or may not be required operating system.

    5: C can use resources from OS, memory, etc, i.e all resources from desktop computer can be used by C. while embedded C can use limited resources, like RAM, ROM, and I/Os on an embedded processor.

    Apache Cordova - uninstall globally

    Try sudo npm uninstall cordova -g to uninstall it globally and then just npm install cordova without the -g flag after cding to the local app directory

    Tomcat: How to find out running tomcat version

    Windows task manager > Processes > find tomcat > right click > open file location > if you run Tomcat7w.exe it is visible at description.

    Tomcat should running to be visible at Processes if not at Windows Vista/7 go to task manager > tab (services) find tomcat start it and then processes.

    Div Background Image Z-Index Issue

    Set your header and footer position to "absolute" and that should do the trick. Hope it helps and good luck with your project!

    Finding out current index in EACH loop (Ruby)

    X.each_with_index do |item, index|
      puts "current_index: #{index}"
    end
    

    AngularJS - Binding radio buttons to models with boolean values

    The correct approach in Angularjs is to use ng-value for non-string values of models.

    Modify your code like this:

    <label data-ng-repeat="choice in question.choices">
      <input type="radio" name="response" data-ng-model="choice.isUserAnswer" data-ng-value="true" />
      {{choice.text}}
    </label>
    

    Ref: Straight from the horse's mouth

    How to delete all files and folders in a directory?

    The simplest way:

    Directory.Delete(path,true);  
    Directory.CreateDirectory(path);
    

    Be aware that this may wipe out some permissions on the folder.

    Get name of current class?

    EDIT: Yes, you can; but you have to cheat: The currently running class name is present on the call stack, and the traceback module allows you to access the stack.

    >>> import traceback
    >>> def get_input(class_name):
    ...     return class_name.encode('rot13')
    ... 
    >>> class foo(object):
    ...      _name = traceback.extract_stack()[-1][2]
    ...     input = get_input(_name)
    ... 
    >>> 
    >>> foo.input
    'sbb'
    

    However, I wouldn't do this; My original answer is still my own preference as a solution. Original answer:

    probably the very simplest solution is to use a decorator, which is similar to Ned's answer involving metaclasses, but less powerful (decorators are capable of black magic, but metaclasses are capable of ancient, occult black magic)

    >>> def get_input(class_name):
    ...     return class_name.encode('rot13')
    ... 
    >>> def inputize(cls):
    ...     cls.input = get_input(cls.__name__)
    ...     return cls
    ... 
    >>> @inputize
    ... class foo(object):
    ...     pass
    ... 
    >>> foo.input
    'sbb'
    >>> 
    

    Synchronously waiting for an async operation, and why does Wait() freeze the program here

    With small custom synchronization context, sync function can wait for completion of async function, without creating deadlock. Here is small example for WinForms app.

    Imports System.Threading
    Imports System.Runtime.CompilerServices
    
    Public Class Form1
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            SyncMethod()
        End Sub
    
        ' waiting inside Sync method for finishing async method
        Public Sub SyncMethod()
            Dim sc As New SC
            sc.WaitForTask(AsyncMethod())
            sc.Release()
        End Sub
    
        Public Async Function AsyncMethod() As Task(Of Boolean)
            Await Task.Delay(1000)
            Return True
        End Function
    
    End Class
    
    Public Class SC
        Inherits SynchronizationContext
    
        Dim OldContext As SynchronizationContext
        Dim ContextThread As Thread
    
        Sub New()
            OldContext = SynchronizationContext.Current
            ContextThread = Thread.CurrentThread
            SynchronizationContext.SetSynchronizationContext(Me)
        End Sub
    
        Dim DataAcquired As New Object
        Dim WorkWaitingCount As Long = 0
        Dim ExtProc As SendOrPostCallback
        Dim ExtProcArg As Object
    
        <MethodImpl(MethodImplOptions.Synchronized)>
        Public Overrides Sub Post(d As SendOrPostCallback, state As Object)
            Interlocked.Increment(WorkWaitingCount)
            Monitor.Enter(DataAcquired)
            ExtProc = d
            ExtProcArg = state
            AwakeThread()
            Monitor.Wait(DataAcquired)
            Monitor.Exit(DataAcquired)
        End Sub
    
        Dim ThreadSleep As Long = 0
    
        Private Sub AwakeThread()
            If Interlocked.Read(ThreadSleep) > 0 Then ContextThread.Resume()
        End Sub
    
        Public Sub WaitForTask(Tsk As Task)
            Dim aw = Tsk.GetAwaiter
    
            If aw.IsCompleted Then Exit Sub
    
            While Interlocked.Read(WorkWaitingCount) > 0 Or aw.IsCompleted = False
                If Interlocked.Read(WorkWaitingCount) = 0 Then
                    Interlocked.Increment(ThreadSleep)
                    ContextThread.Suspend()
                    Interlocked.Decrement(ThreadSleep)
                Else
                    Interlocked.Decrement(WorkWaitingCount)
                    Monitor.Enter(DataAcquired)
                    Dim Proc = ExtProc
                    Dim ProcArg = ExtProcArg
                    Monitor.Pulse(DataAcquired)
                    Monitor.Exit(DataAcquired)
                    Proc(ProcArg)
                End If
            End While
    
        End Sub
    
         Public Sub Release()
             SynchronizationContext.SetSynchronizationContext(OldContext)
         End Sub
    
    End Class
    

    What are some reasons for jquery .focus() not working?

    You need to either put the code below the HTML or load if using the document load event:

    <input type="text" id="goal-input" name="goal" />
    <script type="text/javascript">
    $(function(){
        $("#goal-input").focus();
    });
    </script>
    

    Update:

    Switching divs doesn't trigger the document load event since everything already have been loaded. You need to focus it when you switch div:

    if (goal) {
          step1.fadeOut('fast', function() {
              step1.hide();
              step2.fadeIn('fast', function() {  
                  $("#name").focus();
              });
          });
    }
    

    c++ custom compare function for std::sort()

    std::pair already has the required comparison operators, which perform lexicographical comparisons using both elements of each pair. To use this, you just have to provide the comparison operators for types for types K and V.

    Also bear in mind that std::sort requires a strict weak ordeing comparison, and <= does not satisfy that. You would need, for example, a less-than comparison < for K and V. With that in place, all you need is

    std::vector<pair<K,V>> items; 
    std::sort(items.begin(), items.end()); 
    

    If you really need to provide your own comparison function, then you need something along the lines of

    template <typename K, typename V>
    bool comparePairs(const std::pair<K,V>& lhs, const std::pair<K,V>& rhs)
    {
      return lhs.first < rhs.first;
    }
    

    Showing data values on stacked bar chart in ggplot2

    From ggplot 2.2.0 labels can easily be stacked by using position = position_stack(vjust = 0.5) in geom_text.

    ggplot(Data, aes(x = Year, y = Frequency, fill = Category, label = Frequency)) +
      geom_bar(stat = "identity") +
      geom_text(size = 3, position = position_stack(vjust = 0.5))
    

    enter image description here

    Also note that "position_stack() and position_fill() now stack values in the reverse order of the grouping, which makes the default stack order match the legend."


    Answer valid for older versions of ggplot:

    Here is one approach, which calculates the midpoints of the bars.

    library(ggplot2)
    library(plyr)
    
    # calculate midpoints of bars (simplified using comment by @DWin)
    Data <- ddply(Data, .(Year), 
       transform, pos = cumsum(Frequency) - (0.5 * Frequency)
    )
    
    # library(dplyr) ## If using dplyr... 
    # Data <- group_by(Data,Year) %>%
    #    mutate(pos = cumsum(Frequency) - (0.5 * Frequency))
    
    # plot bars and add text
    p <- ggplot(Data, aes(x = Year, y = Frequency)) +
         geom_bar(aes(fill = Category), stat="identity") +
         geom_text(aes(label = Frequency, y = pos), size = 3)
    

    Resultant chart

    Apache gives me 403 Access Forbidden when DocumentRoot points to two different drives

    You did not need

    Options Indexes FollowSymLinks MultiViews Includes ExecCGI
    AllowOverride All
    Order Allow,Deny
    Allow from all
    Require all granted
    

    the only thing what you need is...

    Require all granted
    

    ...inside the directory section.

    See Apache 2.4 upgrading side:

    http://httpd.apache.org/docs/2.4/upgrading.html

    How to replace negative numbers in Pandas Data Frame by zero

    If you are dealing with a large df (40m x 700 in my case) it works much faster and memory savvy through iteration on columns with something like.

    for col in df.columns:
        df[col][df[col] < 0] = 0
    

    MySQL - UPDATE query based on SELECT Query

    I had an issue with duplicate entries in one table itself. Below is the approaches were working for me. It has also been advocated by @sibaz.

    Finally I solved it using the below queries:

    1. The select query is saved in a temp table

      IF OBJECT_ID(N'tempdb..#New_format_donor_temp', N'U') IS NOT NULL
          DROP TABLE #New_format_donor_temp;
      
      select *
      into #New_format_donor_temp
      from DONOR_EMPLOYMENTS
      where DONOR_ID IN (
        1, 2
      )
      
      -- Test New_format_donor_temp
      -- SELECT *
      -- FROM #New_format_donor_temp;
      
    2. The temp table is joined in the update query.

      UPDATE de
      SET STATUS_CD=de_new.STATUS_CD, STATUS_REASON_CD=de_new.STATUS_REASON_CD, TYPE_CD=de_new.TYPE_CD
      FROM DONOR_EMPLOYMENTS AS de
        INNER JOIN #New_format_donor_temp AS de_new ON de_new.EMP_NO = de.EMP_NO
      WHERE
        de.DONOR_ID IN (
          3, 4
      )
      

    I not very experienced with SQL please advise any better approach you know.

    Above queries are for MySql server.

    PostgreSQL DISTINCT ON with different ORDER BY

    You can order by address_id in an subquery, then order by what you want in an outer query.

    SELECT * FROM 
        (SELECT DISTINCT ON (address_id) purchases.address_id, purchases.* 
        FROM "purchases" 
        WHERE "purchases"."product_id" = 1 ORDER BY address_id DESC ) 
    ORDER BY purchased_at DESC
    

    Random alpha-numeric string in JavaScript?

    Another variation of answer suggested by JAR.JAR.beans

    (Math.random()*1e32).toString(36)
    

    By changing multiplicator 1e32 you can change length of random string.

    Turn off display errors using file "php.ini"

    Open your php.ini file (If you are using Linux - sudo vim /etc/php5/apache2/php.ini)

    Add this lines into that file

       error_reporting = E_ALL & ~E_WARNING 
    

    (If you need to disabled any other errors -> error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE & ~E_WARNING)

        display_errors = On
    

    And finally you need to restart your APACHE server.

    Is it wrong to place the <script> tag after the </body> tag?

    Yes. Only comments and the end tag for the html element are allowed after the end tag for the body.

    Browsers may perform error recovery, but you should never depend on that.

    ES6 export default with multiple functions referring to each other

    tl;dr: baz() { this.foo(); this.bar() }

    In ES2015 this construct:

    var obj = {
        foo() { console.log('foo') }
    }
    

    is equal to this ES5 code:

    var obj = {
        foo : function foo() { console.log('foo') }
    }
    

    exports.default = {} is like creating an object, your default export translates to ES5 code like this:

    exports['default'] = {
        foo: function foo() {
            console.log('foo');
        },
        bar: function bar() {
            console.log('bar');
        },
        baz: function baz() {
            foo();bar();
        }
    };
    

    now it's kind of obvious (I hope) that baz tries to call foo and bar defined somewhere in the outer scope, which are undefined. But this.foo and this.bar will resolve to the keys defined in exports['default'] object. So the default export referencing its own methods shold look like this:

    export default {
        foo() { console.log('foo') }, 
        bar() { console.log('bar') },
        baz() { this.foo(); this.bar() }
    }
    

    See babel repl transpiled code.

    CSS selector for disabled input type="submit"

    Does that work in IE6?

    No, IE6 does not support attribute selectors at all, cf. CSS Compatibility and Internet Explorer.

    You might find How to workaround: IE6 does not support CSS “attribute” selectors worth the read.


    EDIT
    If you are to ignore IE6, you could do (CSS2.1):

    input[type=submit][disabled=disabled],
    button[disabled=disabled] {
        ...
    }
    

    CSS3 (IE9+):

    input[type=submit]:disabled,
    button:disabled {
        ...
    }
    

    You can substitute [disabled=disabled] (attribute value) with [disabled] (attribute presence).

    How to set the title of UIButton as left alignment?

    Swift 4+

    button.contentHorizontalAlignment = .left
    button.contentVerticalAlignment = .top
    button.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    

    Jquery check if element is visible in viewport

    You can write a jQuery function like this to determine if an element is in the viewport.

    Include this somewhere after jQuery is included:

    $.fn.isInViewport = function() {
        var elementTop = $(this).offset().top;
        var elementBottom = elementTop + $(this).outerHeight();
    
        var viewportTop = $(window).scrollTop();
        var viewportBottom = viewportTop + $(window).height();
    
        return elementBottom > viewportTop && elementTop < viewportBottom;
    };
    

    Sample usage:

    $(window).on('resize scroll', function() {
        if ($('#Something').isInViewport()) {
            // do something
        } else {
            // do something else
        }
    });
    

    Note that this only checks the top and bottom positions of elements, it doesn't check if an element is outside of the viewport horizontally.

    Creating a Jenkins environment variable using Groovy

    For me, the following also worked in Jenkins 2 (2.73.3)

    Replace

    def pa = new ParametersAction([new StringParameterValue("FOO", foo)])
    build.addAction(pa)
    

    with

    def pa = new ParametersAction([new StringParameterValue("FOO", foo)], ["FOO"])
    build.addAction(pa)
    

    ParametersAction seems to have a second constructor which allows to pass in "additionalSafeParameters" https://github.com/jenkinsci/jenkins/blob/master/core/src/main/java/hudson/model/ParametersAction.java

    Angular - Use pipes in services and components

    If you want to use your custom pipe in your components, you can add

    @Injectable({
      providedIn: 'root'
    })
    

    annotation to your custom pipe. Then, you can use it as a service

    How ViewBag in ASP.NET MVC works

    The ViewBag is an System.Dynamic.ExpandoObject as suggested. The properties in the ViewBag are essentially KeyValue pairs, where you access the value by the key. In this sense these are equivalent:

    ViewBag.Foo = "Bar";
    ViewBag["Foo"] = "Bar";
    

    Where to change the value of lower_case_table_names=2 on windows xampp

    ADD following -

    • look up for: # The MySQL server [mysqld]
    • add this right below it: lower_case_table_names = 1 In file - /etc/mysql/mysql.conf.d/mysqld.cnf

    It's works for me.

    How do I make a comment in a Dockerfile?

    Dockerfile comments start with '#', just like Python. Here is a good example (kstaken/dockerfile-examples):

    # Install a more-up-to date version of MongoDB than what is included in the default Ubuntu repositories.
    
    FROM ubuntu
    MAINTAINER Kimbro Staken
    
    RUN apt-key adv --keyserver keyserver.ubuntu.com --recv 7F0CEB10
    RUN echo "deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen" | tee -a /etc/apt/sources.list.d/10gen.list
    RUN apt-get update
    RUN apt-get -y install apt-utils
    RUN apt-get -y install mongodb-10gen
    
    #RUN echo "" >> /etc/mongodb.conf
    
    CMD ["/usr/bin/mongod", "--config", "/etc/mongodb.conf"] 
    

    setImmediate vs. nextTick

    I recommend you to check docs section dedicated for Loop to get better understanding. Some snippet taken from there:

    We have two calls that are similar as far as users are concerned, but their names are confusing.

    • process.nextTick() fires immediately on the same phase

    • setImmediate() fires on the following iteration or 'tick' of the
      event loop

    In essence, the names should be swapped. process.nextTick() fires more immediately than setImmediate(), but this is an artifact of the past which is unlikely to change.

    JavaScript editor within Eclipse

    Oracle Workshop for WebLogic (formally BEA Workshop) has excellent support for JavaScript and for visually editing HTMLs. It support many servers, not only WebLogic, including Tomcat, JBoss, Resin, Jetty, and WebSphere.

    It recently became free, check out my post about it. Given that it was an expensive product not long ago, I guess it's worth checking out.

    Push method in React Hooks (useState)?

    // Save search term state to React Hooks with spread operator and wrapper function
    
    // Using .concat(), no wrapper function (not recommended)
    setSearches(searches.concat(query))
    
    // Using .concat(), wrapper function (recommended)
    setSearches(searches => searches.concat(query))
    
    // Spread operator, no wrapper function (not recommended)
    setSearches([...searches, query])
    
    // Spread operator, wrapper function (recommended)
    setSearches(searches => [...searches, query])
    

    https://medium.com/javascript-in-plain-english/how-to-add-to-an-array-in-react-state-3d08ddb2e1dc

    How to take MySQL database backup using MySQL Workbench?

    In workbench 6.0 Connect to any of the database. You will see two tabs.

    1.Management 2. Schemas

    By default Schemas tab is selected. Select Management tab then select Data Export . You will get list of all databases. select the desired database and and the file name and ther options you wish and start export. You are done with backup.

    Javascript array value is undefined ... how do I test for that

    try: typeof(predQuery[preId])=='undefined'
    or more generally: typeof(yourArray[yourIndex])=='undefined'
    You're comparing "undefined" to undefined, which returns false =)

    Thymeleaf using path variables to th:href

    Your code looks syntactically correct, but I think your property doesn't exist to create the URL.

    I just tested it, and it works fine for me.

    Try using category.idCategory instead of category.id, for example…

      <tr th:each="category : ${categories}">
        <td th:text="${category.idCategory}"></td>
        <td th:text="${category.name}"></td>
        <td>
          <a th:href="@{'/category/edit/' + ${category.idCategory}}">view</a>
        </td>
      </tr>
    

    Deserialize JSON string to c# object

    I think the JavaScriptSerializer does not create a dynamic object.

    So you should define the class first:

    class MyObj {
        public int arg1 {get;set;}
        public int arg2 {get;set;}
    }
    

    And deserialize that instead of object:

    serializer.Deserialize<MyObj>(str);
    

    Not testet, please try.

    Printing Python version in output

    Try

    import sys
    print(sys.version)
    

    This prints the full version information string. If you only want the python version number, then Bastien Léonard's solution is the best. You might want to examine the full string and see if you need it or portions of it.

    ORA-12516, TNS:listener could not find available handler

    You opened a lot of connections and that's the issue. I think in your code, you did not close the opened connection.

    A database bounce could temporarily solve, but will re-appear when you do consecutive execution. Also, it should be verified the number of concurrent connections to the database. If maximum DB processes parameter has been reached this is a common symptom.

    Courtesy of this thread: https://community.oracle.com/thread/362226?tstart=-1

    Why do we need C Unions?

    Here's an example of a union from my own codebase (from memory and paraphrased so it may not be exact). It was used to store language elements in an interpreter I built. For example, the following code:

    set a to b times 7.
    

    consists of the following language elements:

    • symbol[set]
    • variable[a]
    • symbol[to]
    • variable[b]
    • symbol[times]
    • constant[7]
    • symbol[.]

    Language elements were defines as '#define' values thus:

    #define ELEM_SYM_SET        0
    #define ELEM_SYM_TO         1
    #define ELEM_SYM_TIMES      2
    #define ELEM_SYM_FULLSTOP   3
    #define ELEM_VARIABLE     100
    #define ELEM_CONSTANT     101
    

    and the following structure was used to store each element:

    typedef struct {
        int typ;
        union {
            char *str;
            int   val;
        }
    } tElem;
    

    then the size of each element was the size of the maximum union (4 bytes for the typ and 4 bytes for the union, though those are typical values, the actual sizes depend on the implementation).

    In order to create a "set" element, you would use:

    tElem e;
    e.typ = ELEM_SYM_SET;
    

    In order to create a "variable[b]" element, you would use:

    tElem e;
    e.typ = ELEM_VARIABLE;
    e.str = strdup ("b");   // make sure you free this later
    

    In order to create a "constant[7]" element, you would use:

    tElem e;
    e.typ = ELEM_CONSTANT;
    e.val = 7;
    

    and you could easily expand it to include floats (float flt) or rationals (struct ratnl {int num; int denom;}) and other types.

    The basic premise is that the str and val are not contiguous in memory, they actually overlap, so it's a way of getting a different view on the same block of memory, illustrated here, where the structure is based at memory location 0x1010 and integers and pointers are both 4 bytes:

           +-----------+
    0x1010 |           |
    0x1011 |    typ    |
    0x1012 |           |
    0x1013 |           |
           +-----+-----+
    0x1014 |     |     |
    0x1015 | str | val |
    0x1016 |     |     |
    0x1017 |     |     |
           +-----+-----+
    

    If it were just in a structure, it would look like this:

           +-------+
    0x1010 |       |
    0x1011 |  typ  |
    0x1012 |       |
    0x1013 |       |
           +-------+
    0x1014 |       |
    0x1015 |  str  |
    0x1016 |       |
    0x1017 |       |
           +-------+
    0x1018 |       |
    0x1019 |  val  |
    0x101A |       |
    0x101B |       |
           +-------+