Programs & Examples On #Docblocks

AngularJs $http.post() does not send data

Angular

  var payload = $.param({ jobId: 2 });

                this.$http({
                    method: 'POST',
                    url: 'web/api/ResourceAction/processfile',
                    data: payload,
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
                });

WebAPI 2

public class AcceptJobParams
        {
            public int jobId { get; set; }
        }

        public IHttpActionResult ProcessFile([FromBody]AcceptJobParams thing)
        {
            // do something with fileName parameter

            return Ok();
        }

Append values to query string

I like Bjorn's answer, however the solution he's provided is misleading, as the method updates an existing parameter, rather than adding it if it doesn't exist.. To make it a bit safer, I've adapted it below.

public static class UriExtensions
{
    /// <summary>
    /// Adds or Updates the specified parameter to the Query String.
    /// </summary>
    /// <param name="url"></param>
    /// <param name="paramName">Name of the parameter to add.</param>
    /// <param name="paramValue">Value for the parameter to add.</param>
    /// <returns>Url with added parameter.</returns>
    public static Uri AddOrUpdateParameter(this Uri url, string paramName, string paramValue)
    {
        var uriBuilder = new UriBuilder(url);
        var query = HttpUtility.ParseQueryString(uriBuilder.Query);

        if (query.AllKeys.Contains(paramName))
        {
            query[paramName] = paramValue;
        }
        else
        {
            query.Add(paramName, paramValue);
        }
        uriBuilder.Query = query.ToString();

        return uriBuilder.Uri;
    }
}

JavaScript: clone a function

Here is an updated answer

var newFunc = oldFunc.bind({}); //clones the function with '{}' acting as it's new 'this' parameter

However .bind is a modern ( >=iE9 ) feature of JavaScript (with a compatibility workaround from MDN)

Notes

  1. It does not clone the function object additional attached properties, including the prototype property. Credit to @jchook

  2. The new function this variable is stuck with the argument given on bind(), even on new function apply() calls. Credit to @Kevin

function oldFunc() {
  console.log(this.msg);
}
var newFunc = oldFunc.bind({ msg: "You shall not pass!" }); // this object is binded
newFunc.apply({ msg: "hello world" }); //logs "You shall not pass!" instead
  1. Bound function object, instanceof treats newFunc/oldFunc as the same. Credit to @Christopher
(new newFunc()) instanceof oldFunc; //gives true
(new oldFunc()) instanceof newFunc; //gives true as well
newFunc == oldFunc; //gives false however

Laravel Eloquent compare date from datetime field

If you're still wondering how to solve it.

I use

$protected $dates = ['created_at','updated_at','aired'];

In my model and in my where i do

where('aired','>=',time())

So just use the unix to compaire in where.

In views on the otherhand you have to use the date object.

Hope it helps someone!

How to lowercase a pandas dataframe string column if it has missing values?

Apply lambda function

df['original_category'] = df['original_category'].apply(lambda x:x.lower())

Google Map API v3 — set bounds and center

Use below one,

map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));

How do I open a new fragment from another fragment?

first of all, give set an ID for your Fragment layout e.g:

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
**android:id="@+id/cameraFragment"**
tools:context=".CameraFragment">

and use that ID to replace the view with another fragment.java file. e.g

 ivGallary.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
          UploadDoc uploadDoc= new UploadDoc();
          (getActivity()).getSupportFragmentManager().beginTransaction()
                  .replace(**R.id.cameraFragment**, uploadDoc, "findThisFragment")
                  .addToBackStack(null)
                  .commit();
      }
  });

Export data from R to Excel

I have been trying out the different packages including the function:

install.packages ("prettyR") 

library (prettyR)

delimit.table (Corrvar,"Name the csv.csv") ## Corrvar is a name of an object from an output I had on scaled variables to run a regression.

However I tried this same code for an output from another analysis (occupancy models model selection output) and it did not work. And after many attempts and exploration I:

  • copied the output from R (Ctrl+c)
  • in Excel sheet I pasted it (Ctrl+V)
  • Select the first column where the data is
  • In the "Data" vignette, click on "Text to column"

  • Select Delimited option, click next

  • Tick space box in "Separator", click next

  • Click Finalize (End)

Your output now should be in a form you can manipulate easy in excel. So perhaps not the fanciest option but it does the trick if you just want to explore your data in another way.

PS. If the labels in excel are not the exact one it is because Im translating the lables from my spanish excel.

C# - How to get Program Files (x86) on Windows 64 bit

Environment.GetEnvironmentVariable("PROGRAMFILES(X86)") ?? Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)

Prevent WebView from displaying "web page not available"

I've been working on this problem of ditching those irritable Google error pages today. It is possible with the Android example code seen above and in plenty of other forums (ask how I know):

wv.setWebViewClient(new WebViewClient() {
    public void onReceivedError(WebView view, int errorCode,
                            String description, String failingUrl) {
       if (view.canGoBack()) {
          view.goBack();
        }
       Toast.makeText(getBaseContext(), description, Toast.LENGTH_LONG).show();
       }
    }
});

IF you put it in shouldOverrideUrlLoading() as one more webclient. At least, this is working for me on my 2.3.6 device. We'll see where else it works later. That would only depress me now, I'm sure. The goBack bit is mine. You may not want it.

Angular2 router (@angular/router), how to set default route?

Only you need to add other parameter in your route, the parameter is useAsDefault:true. For example, if you want the DashboardComponent as default you need to do this:

@RouteConfig([
    { path: '/Dashboard', component: DashboardComponent , useAsDefault:true},
    .
    .
    .
    ])

I recomend you to add names to your routes.

{ path: '/Dashboard',name:'Dashboard', component: DashboardComponent , useAsDefault:true}

"The system cannot find the file specified" when running C++ program

I know this is an old thread, but for any future visitors, the cause of this error is most likely because you haven't built your project from Build > Build Solution. The reason you're getting this error when you try to run your project is because Visual Studio can't find the executable file that should be produced when you build your project.

Where is git.exe located?

If you are using Git For Windows then it is located at

C:\Program Files\Git\mingw64\libexec\git-core

It is nice to have in mind that Git For Windows offers Git CMD, a command prompt with the PATH already set. Git CMD is available as a shortcut in

Start Menu > Programs > Git

among other options.

Number of elements in a javascript object

The concept of number/length/dimensionality doesn't really make sense for an Object, and needing it suggests you really want an Array to me.

Edit: Pointed out to me that you want an O(1) for this. To the best of my knowledge no such way exists I'm afraid.

Is there a Max function in SQL Server that takes two values like Math.Max in .NET?

If you're using SQL Server 2008 (or above), then this is the better solution:

SELECT o.OrderId,
       (SELECT MAX(Price)
        FROM (VALUES (o.NegotiatedPrice),(o.SuggestedPrice)) AS AllPrices(Price))
FROM Order o

All credit and votes should go to Sven's answer to a related question, "SQL MAX of multiple columns?"
I say it's the "best answer" because:

  1. It doesn't require complicating your code with UNION's, PIVOT's, UNPIVOT's, UDF's, and crazy-long CASE statments.
  2. It isn't plagued with the problem of handling nulls, it handles them just fine.
  3. It's easy to swap out the "MAX" with "MIN", "AVG", or "SUM". You can use any aggregate function to find the aggregate over many different columns.
  4. You're not limited to the names I used (i.e. "AllPrices" and "Price"). You can pick your own names to make it easier to read and understand for the next guy.
  5. You can find multiple aggregates using SQL Server 2008's derived_tables like so:
    SELECT MAX(a), MAX(b) FROM (VALUES (1, 2), (3, 4), (5, 6), (7, 8), (9, 10) ) AS MyTable(a, b)

CRC32 C or C++ implementation

The SNIPPETS C Source Code Archive has a CRC32 implementation that is freely usable:

/* Copyright (C) 1986 Gary S. Brown.  You may use this program, or
   code or tables extracted from it, as desired without restriction.*/

(Unfortunately, c.snippets.org seems to have died. Fortunately, the Wayback Machine has it archived.)

In order to be able to compile the code, you'll need to add typedefs for BYTE as an unsigned 8-bit integer and DWORD as an unsigned 32-bit integer, along with the header files crc.h & sniptype.h.

The only critical item in the header is this macro (which could just as easily go in CRC_32.c itself:

#define UPDC32(octet, crc) (crc_32_tab[((crc) ^ (octet)) & 0xff] ^ ((crc) >> 8))

What is SYSNAME data type in SQL Server?

Another use case is when using the SQL Server 2016+ functionality of AT TIME ZONE

The below statement will return a date converted to GMT

SELECT 
CONVERT(DATETIME, SWITCHOFFSET([ColumnA], DATEPART(TZOFFSET, [ColumnA] AT TIME ZONE 'GMT Standard Time')))

If you want to pass the time zone as a variable, say:

SELECT 
CONVERT(DATETIME, SWITCHOFFSET([ColumnA], DATEPART(TZOFFSET, [ColumnA] AT TIME ZONE @TimeZone)))

then that variable needs to be of the type sysname (declaring it as varchar will cause an error).

Regular expression for a hexadecimal number?

It's worth mentioning that detecting an MD5 (which is one of the examples) can be done with:

[0-9a-fA-F]{32}

Select an Option from the Right-Click Menu in Selenium Webdriver - Java

Better and easy way.

Actions action = new Actions(driver);
action.moveToElement(driver.findElement(By.cssSelector("a[href^='https://www.amazon.in/ap/signin']"))).contextClick().build().perform();

You can use any selector at the place of cssSelector.

MySQL SELECT last few days?

WHERE t.date >= DATE_ADD(CURDATE(), INTERVAL '-3' DAY);

use quotes on the -3 value

How to open a txt file and read numbers in Java

Read file, parse each line into an integer and store into a list:

List<Integer> list = new ArrayList<Integer>();
File file = new File("file.txt");
BufferedReader reader = null;

try {
    reader = new BufferedReader(new FileReader(file));
    String text = null;

    while ((text = reader.readLine()) != null) {
        list.add(Integer.parseInt(text));
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        if (reader != null) {
            reader.close();
        }
    } catch (IOException e) {
    }
}

//print out the list
System.out.println(list);

How to Set focus to first text input in a bootstrap modal after shown

According to Bootstrap 4 docs:

Due to how HTML5 defines its semantics, the autofocus HTML attribute has no effect in Bootstrap modals. To achieve the same effect, use some custom JavaScript.

E.g:

$('#idOfMyModal').on('shown.bs.modal', function () {
    $('input:first').trigger('focus')
});

Link.

How to view unallocated free space on a hard disk through terminal

This is an old question, but I wanted to give my answer as well.

Since we're talking about free available space, we should talk about sectors, since no partitioning or sizing of sectors is done.

For us human beings this doesn't make much sense. To have human-readable information we must translate this number into bytes. So, we have a disk already partitioned and we want to know how much space we may use. I personally don't like the parted solution because my brain-memory for commands is already taken. There is also cfdisk, which gives you free space. But I think fdisk is the quickest solution: it's plain and simple, with nothing to install: execute fdisk /dev/sdx and then enter v into the interactive shell. It will gives you the number of sectors still free.

2004-54-0 [17:03:33][root@minimac:~]$> fdisk /dev/sda
Welcome to fdisk (util-linux 2.23.2).
..
Command (m for help): v
Remaining 1713 unallocated 512-byte sectors

We still have 1713 sectors at 512 bytes each. So, because you love terminal (in 2012, who knows now?) we do echo $(((1713*512)/1024))k, which is 1713 sectors multiplied for 512 bytes (divided by 1024 to have KB), which gives 856k.. not even 900 KB.. and I need another disk..

How to import .py file from another directory?

Python3:

import importlib.machinery

loader = importlib.machinery.SourceFileLoader('report', '/full/path/report/other_py_file.py')
handle = loader.load_module('report')

handle.mainFunction(parameter)

This method can be used to import whichever way you want in a folder structure (backwards, forwards doesn't really matter, i use absolute paths just to be sure).

There's also the more normal way of importing a python module in Python3,

import importlib
module = importlib.load_module('folder.filename')
module.function()

Kudos to Sebastian for spplying a similar answer for Python2:

import imp

foo = imp.load_source('module.name', '/path/to/file.py')
foo.MyClass()

How to set the custom border color of UIView programmatically?

In Swift 4 you can set the border color and width to UIControls using below code.

let yourColor : UIColor = UIColor( red: 0.7, green: 0.3, blue:0.1, alpha: 1.0 )
yourControl.layer.masksToBounds = true
yourControl.layer.borderColor = yourColor.CGColor
yourControl.layer.borderWidth = 1.0

< Swift 4, You can set UIView's border width and border color using the below code.

yourView.layer.borderWidth = 1

yourView.layer.borderColor = UIColor.red.cgColor

Using the passwd command from within a shell script

Have you looked at the -p option of adduser (which AFAIK is just another name for useradd)? You may also want to look at the -P option of luseradd which takes a plaintext password, but I don't know if luseradd is a standard command (it may be part of SE Linux or perhaps just an oddity of Fedora).

.NET String.Format() to add commas in thousands place for a number

String.Format("0,###.###"); also works with decimal places

C# equivalent of C++ map<string,double>

Roughly:-

var accounts = new Dictionary<string, double>();

// Initialise to zero...

accounts["Fred"] = 0;
accounts["George"] = 0;
accounts["Fred"] = 0;

// Add cash.
accounts["Fred"] += 4.56;
accounts["George"] += 1.00;
accounts["Fred"] += 1.00;

Console.WriteLine("Fred owes me ${0}", accounts["Fred"]);

What are libtool's .la file for?

It is a textual file that includes a description of the library.

It allows libtool to create platform-independent names.

For example, libfoo goes to:

Under Linux:

/lib/libfoo.so       # Symlink to shared object
/lib/libfoo.so.1     # Symlink to shared object
/lib/libfoo.so.1.0.1 # Shared object
/lib/libfoo.a        # Static library
/lib/libfoo.la       # 'libtool' library

Under Cygwin:

/lib/libfoo.dll.a    # Import library
/lib/libfoo.a        # Static library
/lib/libfoo.la       # libtool library
/bin/cygfoo_1.dll    # DLL

Under Windows MinGW:

/lib/libfoo.dll.a    # Import library
/lib/libfoo.a        # Static library
/lib/libfoo.la       # 'libtool' library
/bin/foo_1.dll       # DLL

So libfoo.la is the only file that is preserved between platforms by libtool allowing to understand what happens with:

  • Library dependencies
  • Actual file names
  • Library version and revision

Without depending on a specific platform implementation of libraries.

Is there a way to check for both `null` and `undefined`?

The simplest way is to use:

import { isNullOrUndefined } from 'util';

and than:

if (!isNullOrUndefined(foo))

Center Triangle at Bottom of Div

Can't you just set left to 50% and then have margin-left set to -25px to account for it's width: http://jsfiddle.net/9AbYc/

.hero:after {
    content:'';
    position: absolute;
    top: 100%;
    left: 50%;
    margin-left: -50px;
    width: 0;
    height: 0;
    border-top: solid 50px #e15915;
    border-left: solid 50px transparent;
    border-right: solid 50px transparent;
}

or if you needed a variable width you could use: http://jsfiddle.net/9AbYc/1/

.hero:after {
    content:'';
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    margin: 0 auto;
    width: 0;
    height: 0;
    border-top: solid 50px #e15915;
    border-left: solid 50px transparent;
    border-right: solid 50px transparent;
}

Apache Spark: The number of cores vs. the number of executors

Spark Dynamic allocation gives flexibility and allocates resources dynamically. In this number of min and max executors can be given. Also the number of executors that has to be launched at the starting of the application can also be given.

Read below on the same:

http://spark.apache.org/docs/latest/configuration.html#dynamic-allocation

Google OAuth 2 authorization - Error: redirect_uri_mismatch

I have frontend app and backend api.

From my backend server I was testing by hitting google api and was facing this error. During my whole time I was wondering of why should I need to give redirect_uri as this is just the backend, for frontend it makes sense.

What I was doing was giving different redirect_uri (though valid) from server (assuming this is just placeholder, it just has only to be registered to google) but my frontend url that created token code was different. So when I was passing this code in my server side testing(for which redirect-uri was different), I was facing this error.

So don't do this mistake. Make sure your frontend redirect_uri is same as your server's as google use it to validate the authenticity.

How to get first N elements of a list in C#?

var firstFiveItems = myList.Take(5);

Or to slice:

var secondFiveItems = myList.Skip(5).Take(5);

And of course often it's convenient to get the first five items according to some kind of order:

var firstFiveArrivals = myList.OrderBy(i => i.ArrivalTime).Take(5);

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

Complementing (as an algebraic curiosity) the @deceze answer with the @ operator, and indicating cases where is "better" to use @ ... Not really better if you need (no log and) micro-performance optimization:

  • array_key_exists: is true if a key exists in an array;
  • isset: is true if the key/variable exists and is not null [faster than array_key_exists];
  • @$array['key']: is true if the key/variable exists and is not (null or '' or 0); [so much slower?]
$a = array('k1' => 'HELLO', 'k2' => null, 'k3' => '', 'k4' => 0);

print isset($a['k1'])? "OK $a[k1].": 'NO VALUE.';            // OK
print array_key_exists('k1', $a)? "OK $a[k1].": 'NO VALUE.'; // OK
print @$a['k1']? "OK $a[k1].": 'NO VALUE.';                  // OK
// outputs OK HELLO.  OK HELLO. OK HELLO.

print isset($a['k2'])? "OK $a[k2].": 'NO VALUE.';            // NO
print array_key_exists('k2', $a)? "OK $a[k2].": 'NO VALUE.'; // OK
print @$a['k2']? "OK $a[k2].": 'NO VALUE.';                  // NO
// outputs NO VALUE.  OK .  NO VALUE.

print isset($a['k3'])? "OK $a[k3].": 'NO VALUE.';            // OK
print array_key_exists('k3', $a)? "OK $a[k3].": 'NO VALUE.'; // OK
print @$a['k3']? "OK $a[k3].": 'NO VALUE.';                  // NO
// outputs OK . OK . NO VALUE.

print isset($a['k4'])? "OK $a[k4].": 'NO VALUE.';            // OK
print array_key_exists('k4', $a)? "OK $a[k4].": 'NO VALUE.'; // OK
print @$a['k4']? "OK $a[k4].": 'NO VALUE.';                  // NO
// outputs OK 0. OK 0. NO VALUE

PS: you can change/correct/complement this text, it is a Wiki.

Convert a String In C++ To Upper Case

If you are only concerned with 8 bit characters (which all other answers except Milan Babuškov assume as well) you can get the fastest speed by generating a look-up table at compile time using metaprogramming. On ideone.com this runs 7x faster than the library function and 3x faster than a hand written version (http://ideone.com/sb1Rup). It is also customizeable through traits with no slow down.

template<int ...Is>
struct IntVector{
using Type = IntVector<Is...>;
};

template<typename T_Vector, int I_New>
struct PushFront;
template<int ...Is, int I_New>
struct PushFront<IntVector<Is...>,I_New> : IntVector<I_New,Is...>{};

template<int I_Size, typename T_Vector = IntVector<>>
struct Iota : Iota< I_Size-1, typename PushFront<T_Vector,I_Size-1>::Type> {};
template<typename T_Vector>
struct Iota<0,T_Vector> : T_Vector{};

template<char C_In>
struct ToUpperTraits {
    enum { value = (C_In >= 'a' && C_In <='z') ? C_In - ('a'-'A'):C_In };
};

template<typename T>
struct TableToUpper;
template<int ...Is>
struct TableToUpper<IntVector<Is...>>{
    static char at(const char in){
        static const char table[] = {ToUpperTraits<Is>::value...};
        return table[in];
    }
};

int tableToUpper(const char c){
    using Table = TableToUpper<typename Iota<256>::Type>;
    return Table::at(c);
}

with use case:

std::transform(in.begin(),in.end(),out.begin(),tableToUpper);

For an in depth (many page) decription of how it works allow me to shamelessly plug my blog: http://metaporky.blogspot.de/2014/07/part-4-generating-look-up-tables-at.html

HTML 5 input type="number" element for floating point numbers on Chrome

Note: If you're using AngularJS, then in addition to changing the step value, you may have to set ng-model-options="{updateOn: 'blur change'}" on the html input.

The reason for this is in order to have the validators run less often, as they are preventing the user from entering a decimal point. This way, the user can type in a decimal point and the validators go into effect after the user blurs.

Choice between vector::resize() and vector::reserve()

reserve when you do not want the objects to be initialized when reserved. also, you may prefer to logically differentiate and track its count versus its use count when you resize. so there is a behavioral difference in the interface - the vector will represent the same number of elements when reserved, and will be 100 elements larger when resized in your scenario.

Is there any better choice in this kind of scenario?

it depends entirely on your aims when fighting the default behavior. some people will favor customized allocators -- but we really need a better idea of what it is you are attempting to solve in your program to advise you well.

fwiw, many vector implementations will simply double the allocated element count when they must grow - are you trying to minimize peak allocation sizes or are you trying to reserve enough space for some lock free program or something else?

SQL Server - Adding a string to a text column (concat equivalent)

The + (String Concatenation) does not work on SQL Server for the image, ntext, or text data types.

In fact, image, ntext, and text are all deprecated.

ntext, text, and image data types will be removed in a future version of MicrosoftSQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead.

That said if you are using an older version of SQL Server than you want to use UPDATETEXT to perform your concatenation. Which Colin Stasiuk gives a good example of in his blog post String Concatenation on a text column (SQL 2000 vs SQL 2005+).

Excel Validation Drop Down list using VBA

You are defining your array as xlValidateList(), so when you try to assign the type, it gets confused as to what you are trying to assign to the type.

Instead, try this:

Dim MyList(5) As String
MyList(0) = 1
MyList(1) = 2
MyList(2) = 3
MyList(3) = 4
MyList(4) = 5
MyList(5) = 6

With Range("A1").Validation
    .Delete
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
         Operator:=xlBetween, Formula1:=Join(MyList, ",")
End With

fatal: could not create work tree dir 'kivy'

You need to ensure you are in a directory in which you have write permission. This might not be the directory in which Git is in once you open the terminal. In my case (Widows 10) I had to use the cd command to change the directory to the root directory (C:) After that it worked just fine.

Display Parameter(Multi-value) in Report

=Join(Parameters!Product.Label, vbcrfl) for new line

List passed by ref - help me explain this behaviour

This link will help you in understanding pass by reference in C#. Basically,when an object of reference type is passed by value to an method, only methods which are available on that object can modify the contents of object.

For example List.sort() method changes List contents but if you assign some other object to same variable, that assignment is local to that method. That is why myList remains unchanged.

If we pass object of reference type by using ref keyword then we can assign some other object to same variable and that changes entire object itself.

(Edit: this is the updated version of the documentation linked above.)

How to send a correct authorization header for basic authentication

NodeJS answer:

In case you wanted to do it with NodeJS: make a GET to JSON endpoint with Authorization header and get a Promise back:

First

npm install --save request request-promise

(see on npm) and then in your .js file:

var requestPromise = require('request-promise');

var user = 'user';
var password = 'password';

var base64encodedData = Buffer.from(user + ':' + password).toString('base64');

requestPromise.get({
  uri: 'https://example.org/whatever',
  headers: {
    'Authorization': 'Basic ' + base64encodedData
  },
  json: true
})
.then(function ok(jsonData) {
  console.dir(jsonData);
})
.catch(function fail(error) {
  // handle error
});

java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.testing.models.Account

The way I could mitigate the JSON Array to collection of LinkedHashMap objects problem was by using CollectionType rather than a TypeReference . This is what I did and worked:

public <T> List<T> jsonArrayToObjectList(String json, Class<T> tClass) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    CollectionType listType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, tClass);
    List<T> ts = mapper.readValue(json, listType);
    LOGGER.debug("class name: {}", ts.get(0).getClass().getName());
    return ts;
}

Using the TypeReference, I was still getting an ArrayList of LinkedHashMaps, i.e. does not work:

public <T> List<T> jsonArrayToObjectList(String json, Class<T> tClass) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    List<T> ts = mapper.readValue(json, new TypeReference<List<T>>(){});
    LOGGER.debug("class name: {}", ts.get(0).getClass().getName());
    return ts;
}

Grouping functions (tapply, by, aggregate) and the *apply family

First start with Joran's excellent answer -- doubtful anything can better that.

Then the following mnemonics may help to remember the distinctions between each. Whilst some are obvious, others may be less so --- for these you'll find justification in Joran's discussions.

Mnemonics

  • lapply is a list apply which acts on a list or vector and returns a list.
  • sapply is a simple lapply (function defaults to returning a vector or matrix when possible)
  • vapply is a verified apply (allows the return object type to be prespecified)
  • rapply is a recursive apply for nested lists, i.e. lists within lists
  • tapply is a tagged apply where the tags identify the subsets
  • apply is generic: applies a function to a matrix's rows or columns (or, more generally, to dimensions of an array)

Building the Right Background

If using the apply family still feels a bit alien to you, then it might be that you're missing a key point of view.

These two articles can help. They provide the necessary background to motivate the functional programming techniques that are being provided by the apply family of functions.

Users of Lisp will recognise the paradigm immediately. If you're not familiar with Lisp, once you get your head around FP, you'll have gained a powerful point of view for use in R -- and apply will make a lot more sense.

What is the easiest way to ignore a JPA field during persistence?

To ignore a field, annotate it with @Transient so it will not be mapped by hibernate.

but then jackson will not serialize the field when converting to JSON.

If you need mix JPA with JSON(omit by JPA but still include in Jackson) use @JsonInclude :

@JsonInclude()
@Transient
private String token;

TIP:

You can also use JsonInclude.Include.NON_NULL and hide fields in JSON during deserialization when token == null:

@JsonInclude(JsonInclude.Include.NON_NULL)
@Transient
private String token;

How to sort a HashMap in Java

Do you have to use a HashMap? If you only need the Map Interface use a TreeMap


If you want to sort by comparing values in the HashMap. You have to write code to do this, if you want to do it once you can sort the values of your HashMap:

Map<String, Person> people = new HashMap<>();
Person jim = new Person("Jim", 25);
Person scott = new Person("Scott", 28);
Person anna = new Person("Anna", 23);

people.put(jim.getName(), jim);
people.put(scott.getName(), scott);
people.put(anna.getName(), anna);

// not yet sorted
List<Person> peopleByAge = new ArrayList<>(people.values());

Collections.sort(peopleByAge, Comparator.comparing(Person::getAge));

for (Person p : peopleByAge) {
    System.out.println(p.getName() + "\t" + p.getAge());
}

If you want to access this sorted list often, then you could insert your elements into a HashMap<TreeSet<Person>>, though the semantics of sets and lists are a bit different.

How to change Elasticsearch max memory size

In elasticsearch path home dir i.e. typically /usr/share/elasticsearch, There is a config file bin/elasticsearch.in.sh. Edit parameter ES_MIN_MEM, ES_MAX_MEM in this file to change -Xms2g, -Xmx4g respectively. And Please make sure you have restarted the node after this config change.

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

TRY THIS:

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

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

Git error when trying to push -- pre-receive hook declined

I got this when trying to push to a dokku instance. Turns out the disk was full on my server.

Ran: du -f

And result was:

Filesystem      Size  Used Avail Use% Mounted on
udev            476M     0  476M   0% /dev
tmpfs           100M  4.4M   95M   5% /run
/dev/xvda1      7.8G  7.4G  8.9M 100% /

react-router (v4) how to go back?

I think the issue is with binding:

constructor(props){
   super(props);
   this.goBack = this.goBack.bind(this); // i think you are missing this
}

goBack(){
    this.props.history.goBack();
}

.....

<button onClick={this.goBack}>Go Back</button>

As I have assumed before you posted the code:

constructor(props) {
    super(props);
    this.handleNext = this.handleNext.bind(this);
    this.handleBack = this.handleBack.bind(this); // you are missing this line
}

Returning pointer from a function

To my knowledge the use of the keyword new, does relatively the same thing as malloc(sizeof identifier). The code below demonstrates how to use the keyword new.

    void main(void){
        int* test;
        test = tester();
        printf("%d",*test);
        system("pause");
    return;
}
    int* tester(void){
        int *retMe;
        retMe = new int;//<----Here retMe is getting malloc for integer type
        *retMe = 12;<---- Initializes retMe... Note * dereferences retMe 
    return retMe;
}

PHP Composer update "cannot allocate memory" error (using Laravel 4)

As composer troubleshooting guide here This could be happening because the VPS runs out of memory and has no Swap space enabled.

free -m

To enable the swap you can use for example:

sudo /bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024
sudo /sbin/mkswap /var/swap.1
sudo /sbin/swapon /var/swap.1

Or if above not worked then you can try create a swap file

sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile

Can regular expressions be used to match nested patterns?

No, you are getting into the realm of Context Free Grammars at that point.

Installing packages in Sublime Text 2

Try using Sublime Package Control to install your packages.

Also take a look at these tips

Jquery Chosen plugin - dynamically populate list by Ajax

If you are generating select tag from ajax, add this inside success function:

$('.chosen').chosen();

Or, If you are generating select tag on clicking add more button then add:

$('.chosen').chosen();

inside the function.

How to parse JSON in Kotlin?

There is no question that the future of parsing in Kotlin will be with kotlinx.serialization. It is part of Kotlin libraries. Version kotlinx.serialization 1.0 is finally released

https://github.com/Kotlin/kotlinx.serialization

import kotlinx.serialization.*
import kotlinx.serialization.json.JSON

@Serializable
data class MyModel(val a: Int, @Optional val b: String = "42")

fun main(args: Array<String>) {

    // serializing objects
    val jsonData = JSON.stringify(MyModel.serializer(), MyModel(42))
    println(jsonData) // {"a": 42, "b": "42"}
    
    // serializing lists
    val jsonList = JSON.stringify(MyModel.serializer().list, listOf(MyModel(42)))
    println(jsonList) // [{"a": 42, "b": "42"}]

    // parsing data back
    val obj = JSON.parse(MyModel.serializer(), """{"a":42}""")
    println(obj) // MyModel(a=42, b="42")
}

How to return a file (FileContentResult) in ASP.NET WebAPI

This question helped me.

So, try this:

Controller code:

[HttpGet]
public HttpResponseMessage Test()
{
    var path = System.Web.HttpContext.Current.Server.MapPath("~/Content/test.docx");;
    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    var stream = new FileStream(path, FileMode.Open);
    result.Content = new StreamContent(stream);
    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
    result.Content.Headers.ContentDisposition.FileName = Path.GetFileName(path);
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
    result.Content.Headers.ContentLength = stream.Length;
    return result;          
}

View Html markup (with click event and simple url):

<script type="text/javascript">
    $(document).ready(function () {
        $("#btn").click(function () {
            // httproute = "" - using this to construct proper web api links.
            window.location.href = "@Url.Action("GetFile", "Data", new { httproute = "" })";
        });
    });
</script>


<button id="btn">
    Button text
</button>

<a href=" @Url.Action("GetFile", "Data", new { httproute = "" }) ">Data</a>

What's the purpose of git-mv?

From the official GitFaq:

Git has a rename command git mv, but that is just a convenience. The effect is indistinguishable from removing the file and adding another with different name and the same content

Database corruption with MariaDB : Table doesn't exist in engine

I've just had this problem with MariaDB/InnoDB and was able to fix it by

  • create the required table in the correct database in another MySQL/MariaDB instance
  • stop both servers
  • copy .ibd, .frm files to original server
  • start both servers
  • drop problem table on both servers

How to get all privileges back to the root user in MySQL?

If you facing grant permission access denied problem, you can try mysql to fix the problem:

grant all privileges on . to root@'localhost' identified by 'Your password';

grant all privileges on . to root@'IP ADDRESS' identified by 'Your password?';

your can try this on any mysql user, its working.

Use below command to login mysql with iP address.

mysql -h 10.0.0.23 -u root -p

How to open my files in data_folder with pandas using relative path?

Try

import pandas as pd
pd.read_csv("../data_folder/data.csv")

GC overhead limit exceeded

From Java SE 6 HotSpot[tm] Virtual Machine Garbage Collection Tuning

the following

Excessive GC Time and OutOfMemoryError

The concurrent collector will throw an OutOfMemoryError if too much time is being spent in garbage collection: if more than 98% of the total time is spent in garbage collection and less than 2% of the heap is recovered, an OutOfMemoryError will be thrown. This feature is designed to prevent applications from running for an extended period of time while making little or no progress because the heap is too small. If necessary, this feature can be disabled by adding the option -XX:-UseGCOverheadLimit to the command line.

The policy is the same as that in the parallel collector, except that time spent performing concurrent collections is not counted toward the 98% time limit. In other words, only collections performed while the application is stopped count toward excessive GC time. Such collections are typically due to a concurrent mode failure or an explicit collection request (e.g., a call to System.gc()).

in conjunction with a passage further down

One of the most commonly encountered uses of explicit garbage collection occurs with RMIs distributed garbage collection (DGC). Applications using RMI refer to objects in other virtual machines. Garbage cannot be collected in these distributed applications without occasionally collection the local heap, so RMI forces full collections periodically. The frequency of these collections can be controlled with properties. For example,

java -Dsun.rmi.dgc.client.gcInterval=3600000

-Dsun.rmi.dgc.server.gcInterval=3600000 specifies explicit collection once per hour instead of the default rate of once per minute. However, this may also cause some objects to take much longer to be reclaimed. These properties can be set as high as Long.MAX_VALUE to make the time between explicit collections effectively infinite, if there is no desire for an upper bound on the timeliness of DGC activity.

Seems to imply that the evaluation period for determining the 98% is one minute long, but it might be configurable on Sun's JVM with the correct define.

Of course, other interpretations are possible.

How to Set JPanel's Width and Height?

please, something went xxx*x, and that's not true at all, check that

JButton Size - java.awt.Dimension[width=400,height=40]
JPanel Size - java.awt.Dimension[width=640,height=480]
JFrame Size - java.awt.Dimension[width=646,height=505]

code (basic stuff from Trail: Creating a GUI With JFC/Swing , and yet I still satisfied that that would be outdated )

EDIT: forget setDefaultCloseOperation()

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class FrameSize {

    private JFrame frm = new JFrame();
    private JPanel pnl = new JPanel();
    private JButton btn = new JButton("Get ScreenSize for JComponents");

    public FrameSize() {
        btn.setPreferredSize(new Dimension(400, 40));
        btn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("JButton Size - " + btn.getSize());
                System.out.println("JPanel Size - " + pnl.getSize());
                System.out.println("JFrame Size - " + frm.getSize());
            }
        });
        pnl.setPreferredSize(new Dimension(640, 480));
        pnl.add(btn, BorderLayout.SOUTH);
        frm.add(pnl, BorderLayout.CENTER);
        frm.setLocation(150, 100);
        frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // EDIT
        frm.setResizable(false);
        frm.pack();
        frm.setVisible(true);
    }

    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                FrameSize fS = new FrameSize();
            }
        });
    }
}

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

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

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

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

How to get array keys in Javascript?

Seems to work.

var widthRange = new Array();
widthRange[46] = { sel:46, min:0,  max:52 };
widthRange[66] = { sel:66, min:52, max:70 };
widthRange[90] = { sel:90, min:70, max:94 };

for (var key in widthRange)
{
    document.write(widthRange[key].sel + "<br />");
    document.write(widthRange[key].min + "<br />");
    document.write(widthRange[key].max + "<br />");
}

ArrayAdapter in android to create simple listview

If you have more than one view in the layout file android.R.layout.simple_list_item_1 then you'll have to pass the third argument android.R.id.text1 to specify the view that should be filled with the array elements (values). But if you have just one view in your layout file, there is no need to specify the third argument.

When is it appropriate to use C# partial classes?

Aside from the other answers...

I've found them helpful as a stepping-stone in refactoring god-classes. If a class has multiple responsibilities (especially if it's a very large code-file) then I find it beneficial to add 1x partial class per-responsibility as a first-pass for organizing and then refactoring the code.

This helps greatly because it can help with making the code much more readable without actually effecting the executing behavior. It also can help identify when a responsibility is easy to refactor out or is tightly tangled with other aspects.

However--to be clear--this is still bad code, at the end of development you still want one responsibility per-class (NOT per partial class). It's just a stepping-stone :)

Volatile Vs Atomic

Volatile and Atomic are two different concepts. Volatile ensures, that a certain, expected (memory) state is true across different threads, while Atomics ensure that operation on variables are performed atomically.

Take the following example of two threads in Java:

Thread A:

value = 1;
done = true;

Thread B:

if (done)
  System.out.println(value);

Starting with value = 0 and done = false the rule of threading tells us, that it is undefined whether or not Thread B will print value. Furthermore value is undefined at that point as well! To explain this you need to know a bit about Java memory management (which can be complex), in short: Threads may create local copies of variables, and the JVM can reorder code to optimize it, therefore there is no guarantee that the above code is run in exactly that order. Setting done to true and then setting value to 1 could be a possible outcome of the JIT optimizations.

volatile only ensures, that at the moment of access of such a variable, the new value will be immediately visible to all other threads and the order of execution ensures, that the code is at the state you would expect it to be. So in case of the code above, defining done as volatile will ensure that whenever Thread B checks the variable, it is either false, or true, and if it is true, then value has been set to 1 as well.

As a side-effect of volatile, the value of such a variable is set thread-wide atomically (at a very minor cost of execution speed). This is however only important on 32-bit systems that i.E. use long (64-bit) variables (or similar), in most other cases setting/reading a variable is atomic anyways. But there is an important difference between an atomic access and an atomic operation. Volatile only ensures that the access is atomically, while Atomics ensure that the operation is atomically.

Take the following example:

i = i + 1;

No matter how you define i, a different Thread reading the value just when the above line is executed might get i, or i + 1, because the operation is not atomically. If the other thread sets i to a different value, in worst case i could be set back to whatever it was before by thread A, because it was just in the middle of calculating i + 1 based on the old value, and then set i again to that old value + 1. Explanation:

Assume i = 0
Thread A reads i, calculates i+1, which is 1
Thread B sets i to 1000 and returns
Thread A now sets i to the result of the operation, which is i = 1

Atomics like AtomicInteger ensure, that such operations happen atomically. So the above issue cannot happen, i would either be 1000 or 1001 once both threads are finished.

jQuery Find and List all LI elements within a UL within a specific DIV

var column1RelArray = [];
$('#column1 li').each(function(){
    column1RelArray.push($(this).attr('rel'));
});

or fp style

var column1RelArray = $('#column1 li').map(function(){ 
    return $(this).attr('rel'); 
});

How does HttpContext.Current.User.Identity.Name know which usernames exist?

How does [HttpContext.Current.User] know which usernames exist or do not exist?

Let's look at an example of one way this works. Suppose you are using Forms Authentication and the "OnAuthenticate" event fires. This event occurs "when the application authenticates the current request" (Reference Source).

Up until this point, the application has no idea who you are.

Since you are using Forms Authentication, it first checks by parsing the authentication cookie (usually .ASPAUTH) via a call to ExtractTicketFromCookie. This calls FormsAuthentication.Decrypt (This method is public; you can call this yourself!). Next, it calls Context.SetPrincipalNoDemand, turning the cookie into a user and stuffing it into Context.User (Reference Source).

How to get a dependency tree for an artifact?

1) Use maven dependency plugin

Create a simple project with pom.xml only. Add your dependency and run:

mvn dependency:tree

Unfortunately dependency mojo must use pom.xml or you get following error:

Cannot execute mojo: tree. It requires a project with an existing pom.xml, but the build is not using one.

2) Find pom.xml of your artifact in maven central repository

Dependencies are described In pom.xml of your artifact. Find it using maven infrastructure.

Go to https://search.maven.org/ and enter your groupId and artifactId.

Or you can go to https://repo1.maven.org/maven2/ and navigate first using plugins groupId, later using artifactId and finally using its version.

For example see org.springframework:spring-core

3) Use maven dependency plugin against your artifact

Part of dependency artifact is a pom.xml. That specifies it's dependency. And you can execute mvn dependency:tree on this pom.

How can I make visible an invisible control with jquery? (hide and show not work)

.show() and .hide() modify the css display rule. I think you want:

$(selector).css('visibility', 'hidden'); // Hide element
$(selector).css('visibility', 'visible'); // Show element

Configuration System Failed to Initialize

It is worth noting that if you add things like connection strings into the app.config, that if you add items outside of the defined config sections, that it will not immediately complain, but when you try and access it, that you may then get the above errors.

Collapse all major sections and make sure there are no items outside the defined ones. Obvious, when you have actually spotted it.

Could not create SSL/TLS secure channel, despite setting ServerCertificateValidationCallback

Just as a follow up for anyone still running into this – I had added the ServicePointManager.SecurityProfile options as noted in the solution:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

And yet I continued to get the same “The request was aborted: Could not create SSL/TLS secure channel” error. I was attempting to connect to some older voice servers with HTTPS SOAP API interfaces (i.e. voice mail, IP phone systems etc… installed years ago). These only support SSL3 connections as they were last updated years ago.

One would think including SSl3 in the list of SecurityProtocols would do the trick here, but it didn’t. The only way I could force the connection was to include ONLY the Ssl3 protocol and no others:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;

Then the connection goes through – seems like a bug to me but this didn’t start throwing errors until recently on tools I provide for these servers that have been out there for years – I believe Microsoft has started rolling out system changes that have updated this behavior to force TLS connections unless there is no other alternative.

Anyway – if you’re still running into this against some old sites/servers, it’s worth giving it a try.

Writing outputs to log file and console

I have found a way to get the desired output. Though it may be somewhat unorthodox way. Anyways here it goes. In the redir.env file I have following code:

#####redir.env#####    
export LOG_FILE=log.txt

      exec 2>>${LOG_FILE}

    function log {
     echo "$1">>${LOG_FILE}
    }

    function message {
     echo "$1"
     echo "$1">>${LOG_FILE}
    }

Then in the actual script I have the following codes:

#!/bin/sh 
. redir.env
echo "Echoed to console only"
log "Written to log file only"
message "To console and log"
echo "This is stderr. Written to log file only" 1>&2

Here echo outputs only to console, log outputs to only log file and message outputs to both the log file and console.

After executing the above script file I have following outputs:

In console

In console
Echoed to console only
To console and log

For the Log file

In Log File Written to log file only
This is stderr. Written to log file only
To console and log

Hope this help.

How do I retrieve the number of columns in a Pandas data frame?

Like so:

import pandas as pd
df = pd.DataFrame({"pear": [1,2,3], "apple": [2,3,4], "orange": [3,4,5]})

len(df.columns)
3

How can I get dictionary key as variable directly in Python (not by searching from value)?

easily change the position of your keys and values,then use values to get key, in dictionary keys can have same value but they(keys) should be different. for instance if you have a list and the first value of it is a key for your problem and other values are the specs of the first value:

list1=["Name",'ID=13736','Phone:1313','Dep:pyhton']

you can save and use the data easily in Dictionary by this loop:

data_dict={}
for i in range(1, len(list1)):
     data_dict[list1[i]]=list1[0]
print(data_dict)
{'ID=13736': 'Name', 'Phone:1313': 'Name', 'Dep:pyhton': 'Name'}

then you can find the key(name) base on any input value.

newline character in c# string

They might be just a \r or a \n. I just checked and the text visualizer in VS 2010 displays both as newlines as well as \r\n.

This string

string test = "blah\r\nblah\rblah\nblah";

Shows up as

blah
blah
blah
blah

in the text visualizer.

So you could try

string modifiedString = originalString
    .Replace(Environment.NewLine, "<br />")
    .Replace("\r", "<br />")
    .Replace("\n", "<br />");

Map isn't showing on Google Maps JavaScript API v3 when nested in a div tag

I solved this problem with:

    <div id="map" style="width: 100%; height: 100%; position: absolute;">
                 <div id="map-canvas"></div>
     </div>

python: How do I know what type of exception occurred?

You usually should not catch all possible exceptions with try: ... except as this is overly broad. Just catch those that are expected to happen for whatever reason. If you really must, for example if you want to find out more about some problem while debugging, you should do

try:
    ...
except Exception as ex:
    print ex # do whatever you want for debugging.
    raise    # re-raise exception.

Convert JSON to Map

One more alternative is json-simple which can be found in Maven Central:

(JSONObject)JSONValue.parse(someString); //JSONObject is actually a Map.

The artifact is 24kbytes, doesn't have other runtime dependencies.

Export query result to .csv file in SQL Server 2008

You can use PowerShell

$AttachmentPath = "CV File location"
$QueryFmt= "Query"

Invoke-Sqlcmd -ServerInstance Server -Database DBName -Query $QueryFmt | Export-CSV $AttachmentPath

Standard way to embed version into python package?

  1. Use a version.py file only with __version__ = <VERSION> param in the file. In the setup.py file import the __version__ param and put it's value in the setup.py file like this: version=__version__
  2. Another way is to use just a setup.py file with version=<CURRENT_VERSION> - the CURRENT_VERSION is hardcoded.

Since we don't want to manually change the version in the file every time we create a new tag (ready to release a new package version), we can use the following..

I highly recommend bumpversion package. I've been using it for years to bump a version.

start by adding version=<VERSION> to your setup.py file if you don't have it already.

You should use a short script like this every time you bump a version:

bumpversion (patch|minor|major) - choose only one option
git push
git push --tags

Then add one file per repo called: .bumpversion.cfg:

[bumpversion]
current_version = <CURRENT_TAG>
commit = True
tag = True
tag_name = {new_version}
[bumpversion:file:<RELATIVE_PATH_TO_SETUP_FILE>]

Note:

  • You can use __version__ parameter under version.py file like it was suggested in other posts and update the bumpversion file like this: [bumpversion:file:<RELATIVE_PATH_TO_VERSION_FILE>]
  • You must git commit or git reset everything in your repo, otherwise you'll get a dirty repo error.
  • Make sure that your virtual environment includes the package of bumpversion, without it it will not work.

Accessing UI (Main) Thread safely in WPF

You can use

Dispatcher.Invoke(Delegate, object[])

on the Application's (or any UIElement's) dispatcher.

You can use it for example like this:

Application.Current.Dispatcher.Invoke(new Action(() => { /* Your code here */ }));

or

someControl.Dispatcher.Invoke(new Action(() => { /* Your code here */ }));

Converting rows into columns and columns into rows using R

Simply use the base transpose function t, wrapped with as.data.frame:

final_df <- as.data.frame(t(starting_df))
final_df
     A    B    C    D
a    1    2    3    4
b 0.02 0.04 0.06 0.08
c Aaaa Bbbb Cccc Dddd

Above updated. As docendo discimus pointed out, t returns a matrix. As Mark suggested wrapping it with as.data.frame gets back a data frame instead of a matrix. Thanks!

Rails: select unique values from a column

Some answers don't take into account the OP wants a array of values

Other answers don't work well if your Model has thousands of records

That said, I think a good answer is:

    Model.uniq.select(:ratings).map(&:ratings)
    => "SELECT DISTINCT ratings FROM `models` " 

Because, first you generate a array of Model (with diminished size because of the select), then you extract the only attribute those selected models have (ratings)

Can you force Vue.js to reload/re-render?

This has worked for me.

created() {
            EventBus.$on('refresh-stores-list', () => {
                this.$forceUpdate();
            });
        },

The other component fires the refresh-stores-list event will cause the current component to rerender

How to kill a running SELECT statement

Oh! just read comments in question, dear I missed it. but just letting the answer be here in case it can be useful to some other person

I tried "Ctrl+C" and "Ctrl+ Break" none worked. I was using SQL Plus that came with Oracle Client 10.2.0.1.0. SQL Plus is used by most as client for connecting with Oracle DB. I used the Cancel, option under File menu and it stopped the execution!

File Menu, Oracle SQL*Plus

Once you click File wait for few mins then the select command halts and menu appears click on Cancel.

Changing the current working directory in Java?

The smarter/easier thing to do here is to just change your code so that instead of opening the file assuming that it exists in the current working directory (I assume you are doing something like new File("blah.txt"), just build the path to the file yourself.

Let the user pass in the base directory, read it from a config file, fall back to user.dir if the other properties can't be found, etc. But it's a whole lot easier to improve the logic in your program than it is to change how environment variables work.

How to conclude your merge of a file?

Check status (git status) of your repository. Every unmerged file (after you resolve conficts by yourself) should be added (git add), and if there is no unmerged file you should git commit

Why does git say "Pull is not possible because you have unmerged files"?

There was same issue with me
In my case, steps are as below-

  1. Removed all file which was being start with U (unmerged) symbol. as-

U   project/app/pages/file1/file.ts
U   project/www/assets/file1/file-name.html
  1. Pull code from master

$ git pull origin master
  1. Checked for status

 $ git status

Here is the message which It appeared-
and have 2 and 1 different commit each, respectively.
(use "git pull" to merge the remote branch into yours)
You have unmerged paths.
(fix conflicts and run "git commit")

Unmerged paths:
(use "git add ..." to mark resolution)

both modified:   project/app/pages/file1/file.ts
both modified:   project/www/assets/file1/file-name.html
  1. Added all new changes -

    $ git add project/app/pages/file1/file.ts
project/www/assets/file1/file-name.html
  1. Commit changes on head-

$ git commit -am "resolved conflict of the app."
  1. Pushed the code -

$ git push origin master

Which turn may issue resolved with this image - enter image description here

How to start up spring-boot application via command line?

You will need to build the jar file first. Here is the syntax to run the main class from a jar file.

java -jar path/to/your/jarfile.jar fully.qualified.package.Application 

Hex transparency in colors

try this on google search (or click here)

255 * .2 to hex

it will generate 0x33 as a result.

However, google does not round off values so you can only use 1-digit multipliers. if you want to use say .85, you have to get the rounded-off value of 255 * .85 first, then type (rounded-value here) to hex in google search.

JavaScriptSerializer.Deserialize - how to change field names

There is no standard support for renaming properties in JavaScriptSerializer however you can quite easily add your own:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;
using System.Reflection;

public class JsonConverter : JavaScriptConverter
{
    public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
    {
        List<MemberInfo> members = new List<MemberInfo>();
        members.AddRange(type.GetFields());
        members.AddRange(type.GetProperties().Where(p => p.CanRead && p.CanWrite && p.GetIndexParameters().Length == 0));

        object obj = Activator.CreateInstance(type);

        foreach (MemberInfo member in members)
        {
            JsonPropertyAttribute jsonProperty = (JsonPropertyAttribute)Attribute.GetCustomAttribute(member, typeof(JsonPropertyAttribute));

            if (jsonProperty != null && dictionary.ContainsKey(jsonProperty.Name))
            {
                SetMemberValue(serializer, member, obj, dictionary[jsonProperty.Name]);
            }
            else if (dictionary.ContainsKey(member.Name))
            {
                SetMemberValue(serializer, member, obj, dictionary[member.Name]);
            }
            else
            {
                KeyValuePair<string, object> kvp = dictionary.FirstOrDefault(x => string.Equals(x.Key, member.Name, StringComparison.InvariantCultureIgnoreCase));

                if (!kvp.Equals(default(KeyValuePair<string, object>)))
                {
                    SetMemberValue(serializer, member, obj, kvp.Value);
                }
            }
        }

        return obj;
    }


    private void SetMemberValue(JavaScriptSerializer serializer, MemberInfo member, object obj, object value)
    {
        if (member is PropertyInfo)
        {
            PropertyInfo property = (PropertyInfo)member;                
            property.SetValue(obj, serializer.ConvertToType(value, property.PropertyType), null);
        }
        else if (member is FieldInfo)
        {
            FieldInfo field = (FieldInfo)member;
            field.SetValue(obj, serializer.ConvertToType(value, field.FieldType));
        }
    }


    public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
    {
        Type type = obj.GetType();
        List<MemberInfo> members = new List<MemberInfo>();
        members.AddRange(type.GetFields());
        members.AddRange(type.GetProperties().Where(p => p.CanRead && p.CanWrite && p.GetIndexParameters().Length == 0));

        Dictionary<string, object> values = new Dictionary<string, object>();

        foreach (MemberInfo member in members)
        {
            JsonPropertyAttribute jsonProperty = (JsonPropertyAttribute)Attribute.GetCustomAttribute(member, typeof(JsonPropertyAttribute));

            if (jsonProperty != null)
            {
                values[jsonProperty.Name] = GetMemberValue(member, obj);
            }
            else
            {
                values[member.Name] = GetMemberValue(member, obj);
            }
        }

        return values;
    }

    private object GetMemberValue(MemberInfo member, object obj)
    {
        if (member is PropertyInfo)
        {
            PropertyInfo property = (PropertyInfo)member;
            return property.GetValue(obj, null);
        }
        else if (member is FieldInfo)
        {
            FieldInfo field = (FieldInfo)member;
            return field.GetValue(obj);
        }

        return null;
    }


    public override IEnumerable<Type> SupportedTypes
    {
        get 
        {
            return new[] { typeof(DataObject) };
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class JsonPropertyAttribute : Attribute
{
    public JsonPropertyAttribute(string name)
    {
        Name = name;
    }

    public string Name
    {
        get;
        set;
    }
}

The DataObject class then becomes:

public class DataObject
{
    [JsonProperty("user_id")]
    public int UserId { get; set; }

    [JsonProperty("detail_level")]
    public DetailLevel DetailLevel { get; set; }
}

I appreicate this might be a little late but thought other people wanting to use the JavaScriptSerializer rather than the DataContractJsonSerializer might appreciate it.

How to properly exit a C# application?

I know this is not the problem you had, however another reason this could happen is you have a non background thread open in your application.

using System;
using System.Threading;
using System.Windows.Forms;

namespace Sandbox_Form
{
    static class Program
    {
        private static Thread thread;

        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            thread = new Thread(BusyWorkThread);
            thread.IsBackground = false;
            thread.Start();

            Application.Run(new Form());

        }

        public static void BusyWorkThread()
        {
            while (true)
            {
                Thread.Sleep(1000);
            }
        }
    }
}

When IsBackground is false it will keep your program open till the thread completes, if you set IsBackground to true the thread will not keep the program open. Things like BackgroundWoker, ThreadPool, and Task all internally use a thread with IsBackground set to true.

How to present a modal atop the current view in Swift

The only way I able to get this to work was by doing this on the presenting view controller:

    func didTapButton() {
    self.definesPresentationContext = true
    self.modalTransitionStyle = .crossDissolve
    let yourVC = self.storyboard?.instantiateViewController(withIdentifier: "YourViewController") as! YourViewController
    let navController = UINavigationController(rootViewController: yourVC)
    navController.modalPresentationStyle = .overCurrentContext
    navController.modalTransitionStyle = .crossDissolve
    self.present(navController, animated: true, completion: nil)
}

What is the official name for a credit card's 3 digit code?

You can't find a consistent reference because it seems to go by at least six different names!

  • Card Security Code
  • Card Verification Value (CVV or CV2)
  • Card Verification Value Code (CVVC)
  • Card Verification Code (CVC)
  • Verification Code (V-Code or V Code)
  • Card Code Verification (CCV)

What is $@ in Bash?

Yes. Please see the man page of bash ( the first thing you go to ) under Special Parameters

Special Parameters

The shell treats several parameters specially. These parameters may only be referenced; assignment to them is not allowed.

* Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable. That is, "$*" is equivalent to "$1c$2c...", where c is the first character of the value of the IFS variable. If IFS is unset, the parameters are separated by spaces. If IFS is null, the parameters are joined without intervening separators.

@ Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is, "$@" is equivalent to "$1" "$2" ... If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. When there are no positional parameters, "$@" and $@ expand to nothing (i.e., they are removed).

What's the difference between "Solutions Architect" and "Applications Architect"?

The spelling?

Seriously though - they're both BS job title fluffing. "Programmer" not good enough for you? Become an "Architect"!

Really... What is the world coming to?!

Edit: I clearly hurt some "architects'" feelings!

Edit 2: Though I agree with the sentiments that the phrasing can be interpreted to mean some people deal with the whole problem domain (eg hardware, software, deployment, maintaining), most people who want to satisfy a client (and make more money) will provide a full service, if required, regardless of their title.

In real life, it's just marketing fluff.

MongoDB: How To Delete All Records Of A Collection in MongoDB Shell?

Delete all documents from a collection in cmd:

cd C:\Program Files\MongoDB\Server\4.2\bin
mongo
use yourdb
db.yourcollection.remove( { } )

Explain why constructor inject is better than other options

To make it simple, let us say that we can use constructor based dependency injection for mandatory dependencies and setter based injection for optional dependencies. It is a rule of thumb!!

Let's say for example.

If you want to instantiate a class you always do it with its constructor. So if you are using constructor based injection, the only way to instantiate the class is through that constructor. If you pass the dependency through constructor it becomes evident that it is a mandatory dependency.

On the other hand, if you have a setter method in a POJO class, you may or may not set value for your class variable using that setter method. It is completely based on your need. i.e. it is optional. So if you pass the dependency through setter method of a class it implicitly means that it is an optional dependency. Hope this is clear!!

django templates: include and extends

You can't pull in blocks from an included file into a child template to override the parent template's blocks. However, you can specify a parent in a variable and have the base template specified in the context.

From the documentation:

{% extends variable %} uses the value of variable. If the variable evaluates to a string, Django will use that string as the name of the parent template. If the variable evaluates to a Template object, Django will use that object as the parent template.

Instead of separate "page1.html" and "page2.html", put {% extends base_template %} at the top of "commondata.html". And then in your view, define base_template to be either "base1.html" or "base2.html".

Why do I get TypeError: can't multiply sequence by non-int of type 'float'?

You can't multiply string and float.instead of you try as below.it works fine

totalAmount = salesAmount * float(salesTax)

in angularjs how to access the element that triggered the event?

To pass the source element in Angular 5 :

_x000D_
_x000D_
<input #myInput type="text" (change)="someFunction(myInput)">
_x000D_
_x000D_
_x000D_

How to list npm user-installed packages?

You can get a list of all globally installed modules using:

ls `npm root -g`

Can I use Homebrew on Ubuntu?

You can just follow instructions from the Homebrew on Linux docs, but I think it is better to understand what the instructions are trying to achieve.

Understanding the installation steps can save some time


Step 1: Choose location

First of all, it is important to understand that linuxbrew will be installed on the /home directory and not inside /home/your-user (the ~ directory).
(See the reason for that at the end of answer).
Keep this in mind when you run the other steps below.

Step 2: Add linuxbrew binaries to /home :

The installation script will do it for us:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

Step 3: Check that /linuxbrew was added to the relevant location

This can be done by simply navigating to /home.
Notice that the docs are showing it as a one-liner by adding test -d <linuxbrew location> before each command.

(Read more about the test command in here).

Step 4: Export relevant environment variables to terminal

We need to add linuxbrew to PATH and add some more environment variables to the current terminal.

We can just add the following exports to terminal (wait don't do it..):

export PATH="/home/linuxbrew/.linuxbrew/bin:/home/linuxbrew/.linuxbrew/sbin${PATH+:$PATH}";

export HOMEBREW_PREFIX="/home/linuxbrew/.linuxbrew";
export HOMEBREW_CELLAR="/home/linuxbrew/.linuxbrew/Cellar";
export HOMEBREW_REPOSITORY="/home/linuxbrew/.linuxbrew/Homebrew";
export MANPATH="/home/linuxbrew/.linuxbrew/share/man${MANPATH+:$MANPATH}:";
export INFOPATH="/home/linuxbrew/.linuxbrew/share/info:${INFOPATH:-}";

Or simply run (If your linuxbrew folder is on other location then /home - change the path):

eval $(/home/linuxbrew/.linuxbrew/bin/brew shellenv)

(*) Because brew command is not yet identified by the current terminal (this is what we're solving right now) we'll have to specify the full path to the brew binary: /home/linuxbrew/.linuxbrew/bin/brew shellenv

Test this step by:

1 ) Run brew from current terminal to see if it identifies the command.

2 ) Run printenv and check if all environment variables were exported and that you see /home/linuxbrew/.linuxbrew/bin:/home/linuxbrew/.linuxbrew/sbin on PATH.

Step 5: Ensure step 4 is running on each terminal

We need to add step 4 to ~/.profile (in case of Debian/Ubuntu):

echo "eval \$($(brew --prefix)/bin/brew shellenv)" >> ~/.profile

For CentOS/Fedora/Red Hat - replace ~/.profile with ~/.bash_profile.

Step 6: Ensure that ~/.profile or ~/.bash_profile are being executed when new terminal is opened

If you executed step 5 and failed to run brew from new terminal - add a test command like echo "Hi!" to ~/.profile or ~/.bash_profile.
If you don't see Hi! when you open a new terminal - go to the terminal preferences and ensure that the attribute of 'run command as login shell' is set.
Read more in here.


Why the installation script installs Homebrew to /home/linuxbrew/.linuxbrew - from here:

The installation script installs Homebrew to /home/linuxbrew/.linuxbrew using sudo if possible and in your home directory at ~/.linuxbrew otherwise. Homebrew does not use sudo after installation.
Using /home/linuxbrew/.linuxbrew allows the use of more binary packages (bottles) than installing in your personal home directory.

The prefix /home/linuxbrew/.linuxbrew was chosen so that users without admin access can ask an admin to create a linuxbrew role account and still benefit from precompiled binaries.

If you do not yourself have admin privileges, consider asking your admin staff to create a linuxbrew role account for you with home directory /home/linuxbrew.

How can I specify a local gem in my Gemfile?

I believe you can do this:

gem "foo", path: "/path/to/foo"

Git copy file preserving history

For completeness, I would add that, if you wanted to copy an entire directory full of controlled AND uncontrolled files, you could use the following:

git mv old new
git checkout HEAD old

The uncontrolled files will be copied over, so you should clean them up:

git clean -fdx new

Is it ok having both Anacondas 2.7 and 3.5 installed in the same time?

Yes, It should be alright to have both versions installed. It's actually pretty much expected nowadays. A lot of stuff is written in 2.7, but 3.5 is becoming the norm. I would recommend updating all your python to 3.5 ASAP, though.

How to center the text in a JLabel?

String text = "In early March, the city of Topeka, Kansas," + "<br>" +
              "temporarily changed its name to Google..." + "<br>" + "<br>" +
              "...in an attempt to capture a spot" + "<br>" +
              "in Google's new broadband/fiber-optics project." + "<br>" + "<br>" +"<br>" +
              "source: http://en.wikipedia.org/wiki/Google_server#Oil_Tanker_Data_Center";
JLabel label = new JLabel("<html><div style='text-align: center;'>" + text + "</div></html>");

Getting RSA private key from PEM BASE64 Encoded private key file

Make sure your id_rsa file doesn't have any extension like .txt or .rtf. Rich Text Format adds additional characters to your file and those gets added to byte array. Which eventually causes invalid private key error. Long story short, Copy the file, not content.

How to create a string with format?

Simple functionality is not included in Swift, expected because it's included in other languages, can often be quickly coded for reuse. Pro tip for programmers to create a bag of tricks file that contains all this reuse code.

So from my bag of tricks we first need string multiplication for use in indentation.

@inlinable func * (string: String, scalar: Int) -> String {
    let array = [String](repeating: string, count: scalar)
    return array.joined(separator: "")
}

and then the code to add commas.

extension Int {
    @inlinable var withCommas:String {
        var i = self
        var retValue:[String] = []
        while i >= 1000 {
            retValue.append(String(format:"%03d",i%1000))
            i /= 1000
        }
        retValue.append("\(i)")
        return retValue.reversed().joined(separator: ",")
    }

    @inlinable func withCommas(_ count:Int = 0) -> String {
        let retValue = self.withCommas
        let indentation = count - retValue.count
        let indent:String = indentation >= 0 ? " " * indentation : ""

        return indent + retValue
    }
}

I just wrote this last function so I could get the columns to line up.

The @inlinable is great because it takes small functions and reduces their functionality so they run faster.

You can use either the variable version or, to get a fixed column, use the function version. Lengths set less than the needed columns will just expand the field.

Now you have something that is pure Swift and does not rely on some old objective C routine for NSString.

How to check currently internet connection is available or not in android

public boolean isNetworkAvailable(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context
            .getSystemService(context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager
            .getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

Httpd returning 503 Service Unavailable with mod_proxy for Tomcat 8

this worked for me:

ProxyRequests     Off
ProxyPreserveHost On
RewriteEngine On

<Proxy http://localhost:8123>
Order deny,allow
Allow from all
</Proxy>

ProxyPass         /node  http://localhost:8123  
ProxyPassReverse  /node  http://localhost:8123

Convert SVG to PNG in Python

Try this: http://cairosvg.org/

The site says:

CairoSVG is written in pure python and only depends on Pycairo. It is known to work on Python 2.6 and 2.7.

Update November 25, 2016:

2.0.0 is a new major version, its changelog includes:

  • Drop Python 2 support

How can I position my div at the bottom of its container?

CSS Grid

Since the usage of CSS Grid is increasing, I would like to suggest align-self to the element that is inside a grid container.

align-self can contain any of the values: end, self-end, flex-end for the following example.

_x000D_
_x000D_
#parent {_x000D_
  display: grid;_x000D_
}_x000D_
_x000D_
#child1 {_x000D_
  align-self: end;_x000D_
}_x000D_
_x000D_
/* Extra Styling for Snippet */_x000D_
_x000D_
#parent {_x000D_
  height: 150px;_x000D_
  background: #5548B0;_x000D_
  color: #fff;_x000D_
  padding: 10px;_x000D_
  font-family: sans-serif;_x000D_
}_x000D_
_x000D_
#child1 {_x000D_
  height: 50px;_x000D_
  width: 50px;_x000D_
  background: #6A67CE;_x000D_
  text-align: center;_x000D_
  vertical-align: middle;_x000D_
  line-height: 50px;_x000D_
}
_x000D_
<div id="parent">_x000D_
  <!-- Other elements here -->_x000D_
  <div id="child1">_x000D_
    1_x000D_
  </div>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is the purpose of the HTML "no-js" class?

Modernizr.js will remove the no-js class.

This allows you to make CSS rules for .no-js something to apply them only if Javascript is disabled.

SQL Server: IF EXISTS ; ELSE

I know its been a while since the original post but I like using CTE's and this worked for me:

WITH cte_table_a
AS
(
    SELECT [id] [id]
    , MAX([value]) [value]
    FROM table_a
    GROUP BY [id]
)
UPDATE table_b
SET table_b.code = CASE WHEN cte_table_a.[value] IS NOT NULL THEN cte_table_a.[value] ELSE 124 END
FROM table_b
LEFT OUTER JOIN  cte_table_a
ON table_b.id = cte_table_a.id

Right to Left support for Twitter Bootstrap 3

in every version of bootstrap,you can do it manually

  1. set rtl direction to your body
  2. in bootstrap.css file, look for ".col-sm-9{float:left}" expression,change it to float:right

this do most things that you want for rtl

default value for struct member in C

Even more so, to add on the existing answers, you may use a macro that hides a struct initializer:

#define DEFAULT_EMPLOYEE { 0, "none" }

Then in your code:

employee john = DEFAULT_EMPLOYEE;

How to check the function's return value if true or false

false != 'false'

For good measures, put the result of validate into a variable to avoid double validation and use that in the IF statement. Like this:

var result = ValidateForm();
if(result == false) {
...
}

Adding open/closed icon to Twitter Bootstrap collapsibles (accordions)

Here is a solution that creates a section that is expandable using somewhat material design, bootstrap 4.5/5 alpha and entirely non-javascript.

Style for head section

<style>
[data-toggle="collapse"] .fa:before {
    content: "\f077";
}

[data-toggle="collapse"].collapsed .fa:before {
    content: "\f078";
}
</style>

Body html

<div class="pt-3 pb-3" style="border-top: 1px solid #eeeeee; border-bottom: 1px solid #eeeeee; cursor: pointer;">
<a href="#expandId" class="text-dark float-right collapsed" data-toggle="collapse" role="button" aria-expanded="false" aria-controls="expandId">
    <i class="fa" aria-hidden="false"></i>
</a>
<a href="#expandId" class="text-dark collapsed" data-toggle="collapse" role="button" aria-expanded="false" aria-controls="expandId">Expand Header</a>
<div class="collapse" id="expandId">
    CONTENT GOES IN HERE
</div>

pycharm running way slow

In my case, it was very slow and i needed to change inspections settings, i tried everything, the only thing that worked was going from 2018.2 version to 2016.2, sometimes is better to be some updates behind...

Displaying better error message than "No JSON object could be decoded"

You wont be able to get python to tell you where the JSON is incorrect. You will need to use a linter online somewhere like this

This will show you error in the JSON you are trying to decode.

CSS white space at bottom of page despite having both min-height and height tag

Try setting the height of the html element to 100% as well.

html {
    min-height: 100%;
    overflow-y: scroll;
}    
body {
     min-height: 100%;
}

Reference from this answer..

Best JavaScript compressor

Here's the source code of an HttpHandler which does that, maybe it'll help you

How to break out or exit a method in Java?

How to break out in java??

Ans: Best way: System.exit(0);

Java language provides three jump statemnts that allow you to interrupt the normal flow of program.

These include break , continue ,return ,labelled break statement for e.g

import java.util.Scanner;
class demo
{   
    public static void main(String args[])
    {
            outerLoop://Label
            for(int i=1;i<=10;i++)
            {
                    for(int j=1;j<=i;j++)
                    {   
                        for(int k=1;k<=j;k++)
                        {
                            System.out.print(k+"\t");
                            break outerLoop;
                        }
                     System.out.println();                  
                    }
             System.out.println();
            }
    }   
}

Output: 1

Now Note below Program:

import java.util.Scanner;
class demo
{   
    public static void main(String args[])
    {
            for(int i=1;i<=10;i++)
            {
                    for(int j=1;j<=i;j++)
                    {   
                        for(int k=1;k<=j;k++)
                        {
                            System.out.print(k+"\t");
                            break ;
                        }                   
                    }
             System.out.println();
            }
    }   
}

output:

1
11
111
1111

and so on upto

1111111111

Similarly you can use continue statement just replace break with continue in above example.

Things to Remember :

A case label cannot contain a runtime expressions involving variable or method calls

outerLoop:
Scanner s1=new Scanner(System.in);
int ans=s1.nextInt();
// Error s1 cannot be resolved

R memory management / cannot allocate vector of size n Mb

I encountered a similar problem, and I used 2 flash drives as 'ReadyBoost'. The two drives gave additional 8GB boost of memory (for cache) and it solved the problem and also increased the speed of the system as a whole. To use Readyboost, right click on the drive, go to properties and select 'ReadyBoost' and select 'use this device' radio button and click apply or ok to configure.

How to install/start Postman native v4.10.3 on Ubuntu 16.04 LTS 64-bit?

Don't forget to add sudo otherwise you will get postman.tar.gz: Permission denied error. And unlink postman if you get error like failed to create symbolic link /usr/bin/postman: File exists. So below is the full code:

sudo wget https://dl.pstmn.io/download/latest/linux64 -O postman.tar.gz
sudo tar -xzf postman.tar.gz -C /opt
sudo rm postman.tar.gz

sudo unlink /usr/bin/postman
sudo ln -s /opt/Postman/Postman /usr/bin/postman

Then just run postman in the terminal.

How to properly seed random number generator

Small update due to golang api change, please omit .UTC() :

time.Now().UTC().UnixNano() -> time.Now().UnixNano()

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    rand.Seed(time.Now().UnixNano())
    fmt.Println(randomInt(100, 1000))
}

func randInt(min int, max int) int {
    return min + rand.Intn(max-min)
}

CKEditor instance already exists

For ajax requests,

 for(k in CKEDITOR.instances){
    var instance = CKEDITOR.instances[k];
    instance.destroy()
 }
  CKEDITOR.replaceAll();

this snipped removes all instances from document. Then creates new instances.

Forward declaring an enum in C++

[My answer is wrong, but I've left it here because the comments are useful].

Forward declaring enums is non-standard, because pointers to different enum types are not guaranteed to be the same size. The compiler may need to see the definition to know what size pointers can be used with this type.

In practice, at least on all the popular compilers, pointers to enums are a consistent size. Forward declaration of enums is provided as a language extension by Visual C++, for example.

Redirect From Action Filter Attribute

I am using MVC4, I used following approach to redirect a custom html screen upon authorization breach.

Extend AuthorizeAttribute say CutomAuthorizer override the OnAuthorization and HandleUnauthorizedRequest

Register the CustomAuthorizer in the RegisterGlobalFilters.

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{

    filters.Add(new CustomAuthorizer());
}

upon identifying the unAuthorized access call HandleUnauthorizedRequestand redirect to the concerned controller action as shown below.


public class CustomAuthorizer : AuthorizeAttribute
{

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        bool isAuthorized = IsAuthorized(filterContext); // check authorization
        base.OnAuthorization(filterContext);
        if (!isAuthorized && !filterContext.ActionDescriptor.ActionName.Equals("Unauthorized", StringComparison.InvariantCultureIgnoreCase)
            && !filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.Equals("LogOn", StringComparison.InvariantCultureIgnoreCase))
        {

            HandleUnauthorizedRequest(filterContext);

        }
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.Result =
       new RedirectToRouteResult(
           new RouteValueDictionary{{ "controller", "LogOn" },
                                          { "action", "Unauthorized" }

                                         });

    }
}

Why do we need virtual functions in C++?

The bottom line is that virtual functions make life easier. Let's use some of M Perry's ideas and describe what would happen if we didn't have virtual functions and instead only could use member-function pointers. We have, in the normal estimation without virtual functions:

 class base {
 public:
 void helloWorld() { std::cout << "Hello World!"; }
  };

 class derived: public base {
 public:
 void helloWorld() { std::cout << "Greetings World!"; }
 };

 int main () {
      base hwOne;
      derived hwTwo = new derived();
      base->helloWorld(); //prints "Hello World!"
      derived->helloWorld(); //prints "Hello World!"

Ok, so that is what we know. Now let's try to do it with member-function pointers:

 #include <iostream>
 using namespace std;

 class base {
 public:
 void helloWorld() { std::cout << "Hello World!"; }
 };

 class derived : public base {
 public:
 void displayHWDerived(void(derived::*hwbase)()) { (this->*hwbase)(); }
 void(derived::*hwBase)();
 void helloWorld() { std::cout << "Greetings World!"; }
 };

 int main()
 {
 base* b = new base(); //Create base object
 b->helloWorld(); // Hello World!
 void(derived::*hwBase)() = &derived::helloWorld; //create derived member 
 function pointer to base function
 derived* d = new derived(); //Create derived object. 
 d->displayHWDerived(hwBase); //Greetings World!

 char ch;
 cin >> ch;
 }

While we can do some things with member-function pointers, they aren't as flexible as virtual functions. It is tricky to use a member-function pointer in a class; the member-function pointer almost, at least in my practice, always must be called in the main function or from within a member function as in the above example.

On the other hand, virtual functions, while they might have some function-pointer overhead, do simplify things dramatically.

EDIT: There is another method which is similar by eddietree: c++ virtual function vs member function pointer (performance comparison) .

Why do I have to "git push --set-upstream origin <branch>"?

TL;DR: git branch --set-upstream-to origin/solaris


The answer to the question you asked—which I'll rephrase a bit as "do I have to set an upstream"—is: no, you don't have to set an upstream at all.

If you do not have upstream for the current branch, however, Git changes its behavior on git push, and on other commands as well.

The complete push story here is long and boring and goes back in history to before Git version 1.5. To shorten it a whole lot, git push was implemented poorly.1 As of Git version 2.0, Git now has a configuration knob spelled push.default which now defaults to simple. For several versions of Git before and after 2.0, every time you ran git push, Git would spew lots of noise trying to convince you to set push.default just to get git push to shut up.

You do not mention which version of Git you are running, nor whether you have configured push.default, so we must guess. My guess is that you are using Git version 2-point-something, and that you have set push.default to simple to get it to shut up. Precisely which version of Git you have, and what if anything you have push.default set to, does matter, due to that long and boring history, but in the end, the fact that you're getting yet another complaint from Git indicates that your Git is configured to avoid one of the mistakes from the past.

What is an upstream?

An upstream is simply another branch name, usually a remote-tracking branch, associated with a (regular, local) branch.

Every branch has the option of having one (1) upstream set. That is, every branch either has an upstream, or does not have an upstream. No branch can have more than one upstream.

The upstream should, but does not have to be, a valid branch (whether remote-tracking like origin/B or local like master). That is, if the current branch B has upstream U, git rev-parse U should work. If it does not work—if it complains that U does not exist—then most of Git acts as though the upstream is not set at all. A few commands, like git branch -vv, will show the upstream setting but mark it as "gone".

What good is an upstream?

If your push.default is set to simple or upstream, the upstream setting will make git push, used with no additional arguments, just work.

That's it—that's all it does for git push. But that's fairly significant, since git push is one of the places where a simple typo causes major headaches.

If your push.default is set to nothing, matching, or current, setting an upstream does nothing at all for git push.

(All of this assumes your Git version is at least 2.0.)

The upstream affects git fetch

If you run git fetch with no additional arguments, Git figures out which remote to fetch from by consulting the current branch's upstream. If the upstream is a remote-tracking branch, Git fetches from that remote. (If the upstream is not set or is a local branch, Git tries fetching origin.)

The upstream affects git merge and git rebase too

If you run git merge or git rebase with no additional arguments, Git uses the current branch's upstream. So it shortens the use of these two commands.

The upstream affects git pull

You should never2 use git pull anyway, but if you do, git pull uses the upstream setting to figure out which remote to fetch from, and then which branch to merge or rebase with. That is, git pull does the same thing as git fetch—because it actually runs git fetch—and then does the same thing as git merge or git rebase, because it actually runs git merge or git rebase.

(You should usually just do these two steps manually, at least until you know Git well enough that when either step fails, which they will eventually, you recognize what went wrong and know what to do about it.)

The upstream affects git status

This may actually be the most important. Once you have an upstream set, git status can report the difference between your current branch and its upstream, in terms of commits.

If, as is the normal case, you are on branch B with its upstream set to origin/B, and you run git status, you will immediately see whether you have commits you can push, and/or commits you can merge or rebase onto.

This is because git status runs:

  • git rev-list --count @{u}..HEAD: how many commits do you have on B that are not on origin/B?
  • git rev-list --count HEAD..@{u}: how many commits do you have on origin/B that are not on B?

Setting an upstream gives you all of these things.

How come master already has an upstream set?

When you first clone from some remote, using:

$ git clone git://some.host/path/to/repo.git

or similar, the last step Git does is, essentially, git checkout master. This checks out your local branch master—only you don't have a local branch master.

On the other hand, you do have a remote-tracking branch named origin/master, because you just cloned it.

Git guesses that you must have meant: "make me a new local master that points to the same commit as remote-tracking origin/master, and, while you're at it, set the upstream for master to origin/master."

This happens for every branch you git checkout that you do not already have. Git creates the branch and makes it "track" (have as an upstream) the corresponding remote-tracking branch.

But this doesn't work for new branches, i.e., branches with no remote-tracking branch yet.

If you create a new branch:

$ git checkout -b solaris

there is, as yet, no origin/solaris. Your local solaris cannot track remote-tracking branch origin/solaris because it does not exist.

When you first push the new branch:

$ git push origin solaris

that creates solaris on origin, and hence also creates origin/solaris in your own Git repository. But it's too late: you already have a local solaris that has no upstream.3

Shouldn't Git just set that, now, as the upstream automatically?

Probably. See "implemented poorly" and footnote 1. It's hard to change now: There are millions4 of scripts that use Git and some may well depend on its current behavior. Changing the behavior requires a new major release, nag-ware to force you to set some configuration field, and so on. In short, Git is a victim of its own success: whatever mistakes it has in it, today, can only be fixed if the change is either mostly invisible, clearly-much-better, or done slowly over time.

The fact is, it doesn't today, unless you use --set-upstream or -u during the git push. That's what the message is telling you.

You don't have to do it like that. Well, as we noted above, you don't have to do it at all, but let's say you want an upstream. You have already created branch solaris on origin, through an earlier push, and as your git branch output shows, you already have origin/solaris in your local repository.

You just don't have it set as the upstream for solaris.

To set it now, rather than during the first push, use git branch --set-upstream-to. The --set-upstream-to sub-command takes the name of any existing branch, such as origin/solaris, and sets the current branch's upstream to that other branch.

That's it—that's all it does—but it has all those implications noted above. It means you can just run git fetch, then look around, then run git merge or git rebase as appropriate, then make new commits and run git push, without a bunch of additional fussing-around.


1To be fair, it was not clear back then that the initial implementation was error-prone. That only became clear when every new user made the same mistakes every time. It's now "less poor", which is not to say "great".

2"Never" is a bit strong, but I find that Git newbies understand things a lot better when I separate out the steps, especially when I can show them what git fetch actually did, and they can then see what git merge or git rebase will do next.

3If you run your first git push as git push -u origin solaris—i.e., if you add the -u flag—Git will set origin/solaris as the upstream for your current branch if (and only if) the push succeeds. So you should supply -u on the first push. In fact, you can supply it on any later push, and it will set or change the upstream at that point. But I think git branch --set-upstream-to is easier, if you forgot.

4Measured by the Austin Powers / Dr Evil method of simply saying "one MILLLL-YUN", anyway.

Convert char* to string C++

Use the string's constructor

basic_string(const charT* s,size_type n, const Allocator& a = Allocator());

EDIT:

OK, then if the C string length is not given explicitly, use the ctor:

basic_string(const charT* s, const Allocator& a = Allocator());

Callback functions in C++

There isn't an explicit concept of a callback function in C++. Callback mechanisms are often implemented via function pointers, functor objects, or callback objects. The programmers have to explicitly design and implement callback functionality.

Edit based on feedback:

In spite of the negative feedback this answer has received, it is not wrong. I'll try to do a better job of explaining where I'm coming from.

C and C++ have everything you need to implement callback functions. The most common and trivial way to implement a callback function is to pass a function pointer as a function argument.

However, callback functions and function pointers are not synonymous. A function pointer is a language mechanism, while a callback function is a semantic concept. Function pointers are not the only way to implement a callback function - you can also use functors and even garden variety virtual functions. What makes a function call a callback is not the mechanism used to identify and call the function, but the context and semantics of the call. Saying something is a callback function implies a greater than normal separation between the calling function and the specific function being called, a looser conceptual coupling between the caller and the callee, with the caller having explicit control over what gets called. It is that fuzzy notion of looser conceptual coupling and caller-driven function selection that makes something a callback function, not the use of a function pointer.

For example, the .NET documentation for IFormatProvider says that "GetFormat is a callback method", even though it is just a run-of-the-mill interface method. I don't think anyone would argue that all virtual method calls are callback functions. What makes GetFormat a callback method is not the mechanics of how it is passed or invoked, but the semantics of the caller picking which object's GetFormat method will be called.

Some languages include features with explicit callback semantics, typically related to events and event handling. For example, C# has the event type with syntax and semantics explicitly designed around the concept of callbacks. Visual Basic has its Handles clause, which explicitly declares a method to be a callback function while abstracting away the concept of delegates or function pointers. In these cases, the semantic concept of a callback is integrated into the language itself.

C and C++, on the other hand, does not embed the semantic concept of callback functions nearly as explicitly. The mechanisms are there, the integrated semantics are not. You can implement callback functions just fine, but to get something more sophisticated which includes explicit callback semantics you have to build it on top of what C++ provides, such as what Qt did with their Signals and Slots.

In a nutshell, C++ has what you need to implement callbacks, often quite easily and trivially using function pointers. What it does not have is keywords and features whose semantics are specific to callbacks, such as raise, emit, Handles, event +=, etc. If you're coming from a language with those types of elements, the native callback support in C++ will feel neutered.

How to configure Glassfish Server in Eclipse manually

This questions seems a little bit outdated but here is my solution.

I assume that you have already downloaded GlassFish on your hard drive and unzipped the files on a directory.

A - Eclipse MarketPlace / Installing GlassFish Tools

The first thing as it is said on previous answers, you have to downloaded GlassFish Tools from eclipse marketplace;

Help -> EclipseMarket Place

enter image description here

And install GlassFish on the screen below;

enter image description here

B - Adding GlassFish Server

Open Server View, if it is not visible on the bottom of the eclipse, then;

Window -> Show View -> Servers

enter image description here

As the server view is visible, simply click "No servers are available. Click this link to create a new server..." as shown below;

enter image description here

C - Adding GlassFish Server

On the New Server window, select GlassFish as shown below. On my experience, there is only one GlassFish option that I can select, instead of several GlassFish options with versions as you can see down below;

enter image description here

D - Configuring GlassFish & Java Locations

Enter the exact GlassFish location and also Java location as you can see below;

enter image description here

E - Last Step

On the last step of this configuration, just leave everything as it is. For simplicity, I don't define an admin password;

enter image description here

Now everything is all set, hope that this helps!

MySQL LIKE IN()?

You can use like this too:

SELECT * FROM fiberbox WHERE fiber IN('140 ', '1938 ', '1940 ')

Correct way to set Bearer token with CURL

Guzzle example:

use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;

$token = 'your_token';

$httpClient = new Client();

$response = $httpClient->get(
    'https://httpbin.org/bearer',
    [
        RequestOptions::HEADERS => [
            'Accept' => 'application/json',
            'Authorization' => 'Bearer ' . $token,
        ]
    ]
);

print_r($response->getBody()->getContents());

See https://github.com/andriichuk/php-curl-cookbook#bearer-auth

PHP: How to check if image file exists?

If you are using curl, you can try the following script:

function checkRemoteFile($url)
{
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL,$url);
 // don't download content
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if(curl_exec($ch)!==FALSE)
{
    return true;
}
else
{
    return false;
}

}

Reference URL: https://hungred.com/how-to/php-check-remote-email-url-image-link-exist/

How to condense if/else into one line in Python?

There is the conditional expression:

a if cond else b

but this is an expression, not a statement.

In if statements, the if (or elif or else) can be written on the same line as the body of the block if the block is just one like:

if something: somefunc()
else: otherfunc()

but this is discouraged as a matter of formatting-style.

How to count down in for loop?

The range function in python has the syntax:

range(start, end, step)

It has the same syntax as python lists where the start is inclusive but the end is exclusive.

So if you want to count from 5 to 1, you would use range(5,0,-1) and if you wanted to count from last to posn you would use range(last, posn - 1, -1).

How can I set the background color of <option> in a <select> element?

_x000D_
_x000D_
select.list1 option.option2
{
    background-color: #007700;
}
_x000D_
<select class="list1">
  <option value="1">Option 1</option>
  <option value="2" class="option2">Option 2</option>
</select>
_x000D_
_x000D_
_x000D_

Twitter Bootstrap alert message close and open again

I just used a model variable to show/hide the dialog and removed the data-dismiss="alert"

Example:

<div data-ng-show="vm.result == 'error'" class="alert alert-danger alert-dismissable">
    <button type="button" class="close" data-ng-click="vm.result = null" aria-hidden="true">&times;</button>
    <strong>Error  !  </strong>{{vm.exception}}
</div>

works for me and stops the need to go out to jquery

Restore a postgres backup file using the command line?

You might need to be logged in as postgres in order to have full privileges on databases.

su - postgres
psql -l                      # will list all databases on Postgres cluster

pg_dump/pg_restore

  pg_dump -U username -f backup.dump database_name -Fc 

switch -F specify format of backup file:

  • c will use custom PostgreSQL format which is compressed and results in smallest backup file size
  • d for directory where each file is one table
  • t for TAR archive (bigger than custom format)
  • -h/--host Specifies the host name of the machine on which the server is running
  • -W/--password Force pg_dump to prompt for a password before connecting to a database

restore backup:

   pg_restore -d database_name -U username -C backup.dump

Parameter -C should create database before importing data. If it doesn't work you can always create database eg. with command (as user postgres or other account that has rights to create databases) createdb db_name -O owner

pg_dump/psql

In case that you didn't specify the argument -F default plain text SQL format was used (or with -F p). Then you can't use pg_restore. You can import data with psql.

backup:

pg_dump -U username -f backup.sql database_name

restore:

psql -d database_name -f backup.sql

Place a button right aligned

_x000D_
_x000D_
<div style = "display: flex; justify-content:flex-end">
    <button>Click me!</button>
</div>
_x000D_
_x000D_
_x000D_

<div style = "display: flex; justify-content: flex-end">
    <button>Click me!</button>
</div>

How are Anonymous inner classes used in Java?

i use anonymous objects for calling new Threads..

new Thread(new Runnable() {
    public void run() {
        // you code
    }
}).start();

Formula px to dp, dp to px android

Note: The widely used solution above is based on displayMetrics.density. However, the docs explain that this value is a rounded value, used with the screen 'buckets'. Eg. on my Nexus 10 it returns 2, where the real value would be 298dpi (real) / 160dpi (default) = 1.8625.

Depending on your requirements, you might need the exact transformation, which can be achieved like this:

[Edit] This is not meant to be mixed with Android's internal dp unit, as this is of course still based on the screen buckets. Use this where you want a unit that should render the same real size on different devices.

Convert dp to pixel:

public int dpToPx(int dp) {
    DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
    return Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));     
}

Convert pixel to dp:

public int pxToDp(int px) {
    DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
    return Math.round(px / (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
}

Note that there are xdpi and ydpi properties, you might want to distinguish, but I can't imagine a sane display where these values differ greatly.

How to Create a real one-to-one relationship in SQL Server

I'm pretty sure it is technically impossible in SQL Server to have a True 1 to 1 relationship, as that would mean you would have to insert both records at the same time (otherwise you'd get a constraint error on insert), in both tables, with both tables having a foreign key relationship to each other.

That being said, your database design described with a foreign key is a 1 to 0..1 relationship. There is no constrain possible that would require a record in tableB. You can have a pseudo-relationship with a trigger that creates the record in tableB.

So there are a few pseudo-solutions

First, store all the data in a single table. Then you'll have no issues in EF.

Or Secondly, your entity must be smart enough to not allow an insert unless it has an associated record.

Or thirdly, and most likely, you have a problem you are trying to solve, and you are asking us why your solution doesn't work instead of the actual problem you are trying to solve (an XY Problem).

UPDATE

To explain in REALITY how 1 to 1 relationships don't work, I'll use the analogy of the Chicken or the egg dilemma. I don't intend to solve this dilemma, but if you were to have a constraint that says in order to add a an Egg to the Egg table, the relationship of the Chicken must exist, and the chicken must exist in the table, then you couldn't add an Egg to the Egg table. The opposite is also true. You cannot add a Chicken to the Chicken table without both the relationship to the Egg and the Egg existing in the Egg table. Thus no records can be every made, in a database without breaking one of the rules/constraints.

Database nomenclature of a one-to-one relationship is misleading. All relationships I've seen (there-fore my experience) would be more descriptive as one-to-(zero or one) relationships.

Android: how to get the current day of the week (Monday, etc...) in the user's language?

Try this:

int dayOfWeek = date.get(Calendar.DAY_OF_WEEK);  
String weekday = new DateFormatSymbols().getShortWeekdays()[dayOfWeek];

HTML for the Pause symbol in audio and video control

I'm using ▐ ▌

HTML: &#9616;&nbsp;&#9612;

CSS: \2590\A0\258C

Hibernate Error: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session

Another thing that worked for me was to make the instance variable Long in place of long


I had my primary key variable long id; changing it to Long id; worked

All the best

Saving data to a file in C#

One liner:

System.IO.File.WriteAllText(@"D:\file.txt", content);

It creates the file if it doesn't exist and overwrites it if it exists. Make sure you have appropriate privileges to write to the location, otherwise you will get an exception.

https://msdn.microsoft.com/en-us/library/ms143375%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396

Write string to text file and ensure it always overwrites the existing content.

Git blame -- prior commits?

Build on stangls's answer, I put this script in my PATH (even on Windows) as git-bh:

That allows me to look for all commits where a word was involved:

git bh path/to/myfile myWord

Script:

#!/bin/bash
f=$1
shift
csha=""
{ git log --pretty=format:%H -- "$f"; echo; } | {
  while read hash; do
    res=$(git blame -L"/$1/",+1 $hash -- "$f" 2>/dev/null | sed 's/^/  /')
    sha=${res%% (*}
    if [[ "${res}" != "" && "${csha}" != "${sha}" ]]; then
      echo "--- ${hash}"
      echo "${res}"
      csha="${sha}"
    fi
  done
}

Setting Different Bar color in matplotlib Python

Simple, just use .set_color

>>> barlist=plt.bar([1,2,3,4], [1,2,3,4])
>>> barlist[0].set_color('r')
>>> plt.show()

enter image description here

For your new question, not much harder either, just need to find the bar from your axis, an example:

>>> f=plt.figure()
>>> ax=f.add_subplot(1,1,1)
>>> ax.bar([1,2,3,4], [1,2,3,4])
<Container object of 4 artists>
>>> ax.get_children()
[<matplotlib.axis.XAxis object at 0x6529850>, 
 <matplotlib.axis.YAxis object at 0x78460d0>,  
 <matplotlib.patches.Rectangle object at 0x733cc50>, 
 <matplotlib.patches.Rectangle object at 0x733cdd0>, 
 <matplotlib.patches.Rectangle object at 0x777f290>, 
 <matplotlib.patches.Rectangle object at 0x777f710>, 
 <matplotlib.text.Text object at 0x7836450>, 
 <matplotlib.patches.Rectangle object at 0x7836390>, 
 <matplotlib.spines.Spine object at 0x6529950>, 
 <matplotlib.spines.Spine object at 0x69aef50>,
 <matplotlib.spines.Spine object at 0x69ae310>, 
 <matplotlib.spines.Spine object at 0x69aea50>]
>>> ax.get_children()[2].set_color('r') 
 #You can also try to locate the first patches.Rectangle object 
 #instead of direct calling the index.

If you have a complex plot and want to identify the bars first, add those:

>>> import matplotlib
>>> childrenLS=ax.get_children()
>>> barlist=filter(lambda x: isinstance(x, matplotlib.patches.Rectangle), childrenLS)
[<matplotlib.patches.Rectangle object at 0x3103650>, 
 <matplotlib.patches.Rectangle object at 0x3103810>, 
 <matplotlib.patches.Rectangle object at 0x3129850>, 
 <matplotlib.patches.Rectangle object at 0x3129cd0>, 
 <matplotlib.patches.Rectangle object at 0x3112ad0>]

Using Javascript in CSS

IE and Firefox both contain ways to execute JavaScript from CSS. As Paolo mentions, one way in IE is the expression technique, but there's also the more obscure HTC behavior, in which a seperate XML that contains your script is loaded via CSS. A similar technique for Firefox exists, using XBL. These techniques don't exectue JavaScript from CSS directly, but the effect is the same.

HTC with IE

Use a CSS rule like so:

body {
  behavior:url(script.htc);
}

and within that script.htc file have something like:

<PUBLIC:COMPONENT TAGNAME="xss">
   <PUBLIC:ATTACH EVENT="ondocumentready" ONEVENT="main()" LITERALCONTENT="false"/>
</PUBLIC:COMPONENT>
<SCRIPT>
   function main() 
   {
     alert("HTC script executed.");
   }
</SCRIPT>

The HTC file executes the main() function on the event ondocumentready (referring to the HTC document's readiness.)

XBL with Firefox

Firefox supports a similar XML-script-executing hack, using XBL.

Use a CSS rule like so:

body {
  -moz-binding: url(script.xml#mycode);
}

and within your script.xml:

<?xml version="1.0"?>
<bindings xmlns="http://www.mozilla.org/xbl" xmlns:html="http://www.w3.org/1999/xhtml">

<binding id="mycode">
  <implementation>
    <constructor>
      alert("XBL script executed.");
    </constructor>
  </implementation>
</binding>

</bindings>

All of the code within the constructor tag will be executed (a good idea to wrap code in a CDATA section.)

In both techniques, the code doesn't execute unless the CSS selector matches an element within the document. By using something like body, it will execute immediately on page load.

Progress during large file copy (Copy-Item & Write-Progress?)

Hate to be the one to bump an old subject, but I found this post extremely useful. After running performance tests on the snippets by stej and it's refinement by Graham Gold, plus the BITS suggestion by Nacht, I have decuded that:

  1. I really liked Graham's command with time estimations and speed readings.
  2. I also really liked the significant speed increase of using BITS as my transfer method.

Faced with the decision between the two... I found that Start-BitsTransfer supported Asynchronous mode. So here is the result of my merging the two.

function Copy-File {
    # ref: https://stackoverflow.com/a/55527732/3626361
    param([string]$From, [string]$To)

    try {
        $job = Start-BitsTransfer -Source $From -Destination $To `
            -Description "Moving: $From => $To" `
            -DisplayName "Backup" -Asynchronous

        # Start stopwatch
        $sw = [System.Diagnostics.Stopwatch]::StartNew()
        Write-Progress -Activity "Connecting..."

        while ($job.JobState.ToString() -ne "Transferred") {
            switch ($job.JobState.ToString()) {
                "Connecting" {
                    break
                }
                "Transferring" {
                    $pctcomp = ($job.BytesTransferred / $job.BytesTotal) * 100
                    $elapsed = ($sw.elapsedmilliseconds.ToString()) / 1000

                    if ($elapsed -eq 0) {
                        $xferrate = 0.0
                    }
                    else {
                        $xferrate = (($job.BytesTransferred / $elapsed) / 1mb);
                    }

                    if ($job.BytesTransferred % 1mb -eq 0) {
                        if ($pctcomp -gt 0) {
                            $secsleft = ((($elapsed / $pctcomp) * 100) - $elapsed)
                        }
                        else {
                            $secsleft = 0
                        }

                        Write-Progress -Activity ("Copying file '" + ($From.Split("\") | Select-Object -last 1) + "' @ " + "{0:n2}" -f $xferrate + "MB/s") `
                            -PercentComplete $pctcomp `
                            -SecondsRemaining $secsleft
                    }
                    break
                }
                "Transferred" {
                    break
                }
                Default {
                    throw $job.JobState.ToString() + " unexpected BITS state."
                }
            }
        }

        $sw.Stop()
        $sw.Reset()
    }
    finally {
        Complete-BitsTransfer -BitsJob $job
        Write-Progress -Activity "Completed" -Completed
    }
}

How do I redirect with JavaScript?

Compared to window.location="url"; it is much easyer to do just location="url"; I always use that

Disabling vertical scrolling in UIScrollView

You need to pass 0 in content size to disable in which direction you want.

To disable vertical scrolling

scrollView.contentSize = CGSizeMake(scrollView.contentSize.width,0);

To disable horizontal scrolling

scrollView.contentSize = CGSizeMake(0,scrollView.contentSize.height);

Determine SQL Server Database Size

According to SQL2000 help, sp_spaceused includes data and indexes.

This script should do:

CREATE TABLE #t (name SYSNAME, rows CHAR(11), reserved VARCHAR(18), 
data VARCHAR(18), index_size VARCHAR(18), unused VARCHAR(18))

EXEC sp_msforeachtable 'INSERT INTO #t EXEC sp_spaceused ''?'''
-- SELECT * FROM #t ORDER BY name
-- SELECT name, CONVERT(INT, SUBSTRING(data, 1, LEN(data)-3)) FROM #t ORDER BY name
SELECT SUM(CONVERT(INT, SUBSTRING(data, 1, LEN(data)-3))) FROM #t
DROP TABLE #t

css to make bootstrap navbar transparent

This works for 4.0.

<nav class="navbar navbar-expand-sm fixed-top navbar-light">
or
<nav class="navbar navbar-expand-lg fixed-top navbar-dark">

key item is fixed-top, otherwise, white or default page background is displayed even if there is a image top. navbar-light gives dark letters, navbar-dark shows light text.

Compare objects in Angular

Bit late on this thread. angular.equals does deep check, however does anyone know that why its behave differently if one of the member contain "$" in prefix ?

You can try this Demo with following input

var obj3 = {}
obj3.a=  "b";
obj3.b={};
obj3.b.$c =true;

var obj4 = {}
obj4.a=  "b";
obj4.b={};
obj4.b.$c =true;

angular.equals(obj3,obj4);

What does \d+ mean in regular expression terms?

\d means 'digit'. + means, '1 or more times'. So \d+ means one or more digit. It will match 12 and 1.

Replace all elements of Python NumPy Array that are greater than some value

You can also use &, | (and/or) for more flexibility:

values between 5 and 10: A[(A>5)&(A<10)]

values greater than 10 or smaller than 5: A[(A<5)|(A>10)]

How can I wait for set of asynchronous callback functions?

Checking in from 2015: We now have native promises in most recent browser (Edge 12, Firefox 40, Chrome 43, Safari 8, Opera 32 and Android browser 4.4.4 and iOS Safari 8.4, but not Internet Explorer, Opera Mini and older versions of Android).

If we want to perform 10 async actions and get notified when they've all finished, we can use the native Promise.all, without any external libraries:

function asyncAction(i) {
    return new Promise(function(resolve, reject) {
        var result = calculateResult();
        if (result.hasError()) {
            return reject(result.error);
        }
        return resolve(result);
    });
}

var promises = [];
for (var i=0; i < 10; i++) {
    promises.push(asyncAction(i));
}

Promise.all(promises).then(function AcceptHandler(results) {
    handleResults(results),
}, function ErrorHandler(error) {
    handleError(error);
});

How can I validate a string to only allow alphanumeric characters in it?

In order to check if the string is both a combination of letters and digits, you can re-write @jgauffin answer as follows using .NET 4.0 and LINQ:

if(!string.IsNullOrWhiteSpace(yourText) && 
yourText.Any(char.IsLetter) && yourText.Any(char.IsDigit))
{
   // do something here
}

Using HTML5/Canvas/JavaScript to take in-browser screenshots

Here is a complete screenshot example that works with chrome in 2021. The end result is a blob ready to be transmitted. Flow is: request media > grab frame > draw to canvas > transfer to blob. If you want to do it more memory efficient explore OffscreenCanvas or possibly ImageBitmapRenderingContext

https://jsfiddle.net/v24hyd3q/1/

// Request media
navigator.mediaDevices.getDisplayMedia().then(stream => 
{
  // Grab frame from stream
  let track = stream.getVideoTracks()[0];
  let capture = new ImageCapture(track);
  capture.grabFrame().then(bitmap => 
  {
    // Stop sharing
    track.stop();
      
    // Draw the bitmap to canvas
    canvas.width = bitmap.width;
    canvas.height = bitmap.height;
    canvas.getContext('2d').drawImage(bitmap, 0, 0);
      
    // Grab blob from canvas
    canvas.toBlob(blob => {
        // Do things with blob here
        console.log('output blob:', blob);
    });
  });
})
.catch(e => console.log(e));

How can I add a Google search box to my website?

Sorry for replying on an older question, but I would like to clarify the last question.

You use a "get" method for your form. When the name of your input-field is "g", it will make a URL like this:

https://www.google.com/search?g=[value from input-field]

But when you search with google, you notice the following URL:

https://www.google.nl/search?q=google+search+bar

Google uses the "q" Querystring variable as it's search-query. Therefor, renaming your field from "g" to "q" solved the problem.

"application blocked by security settings" prevent applets running using oracle SE 7 update 51 on firefox on Linux mint

As an alternative answer, there's a command line to invoke directly the Control Panel, which is javaws -viewer, should work for both openJDK and Oracle's JDK (thanks @Nasser for checking the availability in Oracle's JDK)

Same caution to run as the user you need to access permissions with applies.

How to upload a file from Windows machine to Linux machine using command lines via PuTTy?

Try using SCP on Windows to transfer files, you can download SCP from Putty's website. Then try running:

pscp.exe filename.extension [email protected]:directory/subdirectory

There is a full length guide here.

REST URI convention - Singular or plural name of resource while creating it

The premise of using /resources is that it is representing "all" resources. If you do a GET /resources, you will likely return the entire collection. By POSTing to /resources, you are adding to the collection.

However, the individual resources are available at /resource. If you do a GET /resource, you will likely error, as this request doesn't make any sense, whereas /resource/123 makes perfect sense.

Using /resource instead of /resources is similar to how you would do this if you were working with, say, a file system and a collection of files and /resource is the "directory" with the individual 123, 456 files in it.

Neither way is right or wrong, go with what you like best.

Mongoose limit/offset and count query

After having to tackle this issue myself, I would like to build upon user854301's answer.

Mongoose ^4.13.8 I was able to use a function called toConstructor() which allowed me to avoid building the query multiple times when filters are applied. I know this function is available in older versions too but you'll have to check the Mongoose docs to confirm this.

The following uses Bluebird promises:

let schema = Query.find({ name: 'bloggs', age: { $gt: 30 } });

// save the query as a 'template'
let query = schema.toConstructor();

return Promise.join(
    schema.count().exec(),
    query().limit(limit).skip(skip).exec(),

    function (total, data) {
        return { data: data, total: total }
    }
);

Now the count query will return the total records it matched and the data returned will be a subset of the total records.

Please note the () around query() which constructs the query.

JavaScript/jQuery: replace part of string?

You need to set the text after the replace call:

_x000D_
_x000D_
$('.element span').each(function() {_x000D_
  console.log($(this).text());_x000D_
  var text = $(this).text().replace('N/A, ', '');_x000D_
  $(this).text(text);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="element">_x000D_
  <span>N/A, Category</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_


Here's another cool way you can do it (hat tip @Felix King):

$(".element span").text(function(index, text) {
    return text.replace("N/A, ", "");
});

How to subtract X day from a Date object in Java?

Java 8 Time API:

Instant now = Instant.now(); //current date
Instant before = now.minus(Duration.ofDays(300));
Date dateBefore = Date.from(before);

How to take a first character from the string

Try this:

Dim s = "RAJAN"
Dim firstChar = s(0)

You can even do this:

Dim firstChar = "RAJAN"(0)

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

Helping you further, where Mick Sharpe left you:

It's deriveration is quite simple: see http://en.wikipedia.org/wiki/Logarithm -> Group Theory

log(n!) = log(n * (n-1) * (n-2) * ... * 2 * 1) = log(n) + log(n-1) + ... + log(2) + log(1)

Think of n as infinitly big. What is infinite minus one? or minus two? etc.

log(inf) + log(inf) + log(inf) + ... = inf * log(inf)

And then think of inf as n.

What should be in my .gitignore for an Android Studio project?

It's best to add up the .gitignore list through the development time to prevent unknown side effect when Version Control won't work for some reason because of the pre-defined (copy/paste) list from somewhere. For one of my project, the ignore list is only of:

.gradle
.idea
libs
obj
build
*.log

Java difference between FileWriter and BufferedWriter

You are right. Here is how write() method of BufferedWriter looks:

public void write(int c) throws IOException {
    synchronized (lock) {
        ensureOpen();
        if (nextChar >= nChars)
            flushBuffer();
        cb[nextChar++] = (char) c;
    }
}

As you can see it indeed checks whether the buffer is full (if (nextChar >= nChars)) and flushes the buffer. Then it adds new character to buffer (cb[nextChar++] = (char) c;).

Max size of an iOS application

Please be aware that the warning on iTunes Connect does not say anything about the limit being only for over-the-air delivery. It would be preferable if the warning mentioned this.

enter image description here

Oracle insert if not exists statement

Another approach would be to leverage the INSERT ALL syntax from oracle,

INSERT ALL 
    INTO table1(email, campaign_id) VALUES (email, campaign_id)
WITH source_data AS
 (SELECT '[email protected]' email,100 campaign_id
  FROM   dual
  UNION ALL
  SELECT '[email protected]' email,200 campaign_id
  FROM   dual)      
SELECT email
      ,campaign_id
FROM   source_data src
WHERE  NOT EXISTS (SELECT 1
        FROM   table1 dest
        WHERE  src.email = dest.email
        AND    src.campaign_id = dest.campaign_id);

INSERT ALL also allow us to perform a conditional insert into multiple tables based on a sub query as source.

There are some really clean and nice examples are there to refer.

  1. oracletutorial.com
  2. oracle-base.com/

What's the best way to dedupe a table?

Here's one I've run into, in real life.

Assume you have a table of external/3rd party logins for users, and you're going to merge two users and want to dedupe on the provider/provider key values.

    ;WITH Logins AS
    (
        SELECT [LoginId],[UserId],[Provider],[ProviderKey]
        FROM [dbo].[UserLogin] 
        WHERE [UserId]=@FromUserID -- is the user we're deleting
              OR [UserId]=@ToUserID -- is the user we're moving data to
    ), Ranked AS 
    (
        SELECT Logins.*
            , [Picker]=ROW_NUMBER() OVER (
                       PARTITION BY [Provider],[ProviderKey]
                       ORDER BY CASE WHEN [UserId]=@FromUserID THEN 1 ELSE 0 END)
        FROM Logins
    )
    MERGE Logins AS T
    USING Ranked AS S
    ON S.[LoginId]=T.[LoginID]
    WHEN MATCHED AND S.[Picker]>1 -- duplicate Provider/ProviderKey
                 AND T.[UserID]=@FromUserID -- safety check 
    THEN DELETE
    WHEN MATCHED AND S.[Picker]=1 -- the only or best one
                 AND T.[UserID]=@FromUserID
    THEN UPDATE SET T.[UserID]=@ToUserID
    OUTPUT $action, DELETED.*, INSERTED.*;

module.exports vs. export default in Node.js and ES6

You need to configure babel correctly in your project to use export default and export const foo

npm install --save-dev @babel/plugin-proposal-export-default-from

then add below configration in .babelrc

"plugins": [ 
       "@babel/plugin-proposal-export-default-from"
      ]

minimum double value in C/C++

In C, use

#include <float.h>

const double lowest_double = -DBL_MAX;

In C++pre-11, use

#include <limits>

const double lowest_double = -std::numeric_limits<double>::max();

In C++11 and onwards, use

#include <limits>

constexpr double lowest_double = std::numeric_limits<double>::lowest();

Relative frequencies / proportions with dplyr

Here is a general function implementing Henrik's solution on dplyr 0.7.1.

freq_table <- function(x, 
                       group_var, 
                       prop_var) {
  group_var <- enquo(group_var)
  prop_var  <- enquo(prop_var)
  x %>% 
    group_by(!!group_var, !!prop_var) %>% 
    summarise(n = n()) %>% 
    mutate(freq = n /sum(n)) %>% 
    ungroup
}

What is the difference between task and thread?

Task is like a operation that you wanna perform , Thread helps to manage those operation through multiple process nodes. task is a lightweight option as Threading can lead to a complex code management
I will suggest to read from MSDN(Best in world) always

Task

Thread

How often does python flush to a file?

I don't know if this applies to python as well, but I think it depends on the operating system that you are running.

On Linux for example, output to terminal flushes the buffer on a newline, whereas for output to files it only flushes when the buffer is full (by default). This is because it is more efficient to flush the buffer fewer times, and the user is less likely to notice if the output is not flushed on a newline in a file.

You might be able to auto-flush the output if that is what you need.

EDIT: I think you would auto-flush in python this way (based from here)

#0 means there is no buffer, so all output
#will be auto-flushed
fsock = open('out.log', 'w', 0)
sys.stdout = fsock
#do whatever
fsock.close()

Element count of an array in C++

There are no cases where, given an array arr, that the value of sizeof(arr) / sizeof(arr[0]) is not the count of elements, by the definition of array and sizeof.

In fact, it's even directly mentioned (§5.3.3/2):

.... When applied to an array, the result is the total number of bytes in the array. This implies that the size of an array of n elements is n times the size of an element.

Emphasis mine. Divide by the size of an element, sizeof(arr[0]), to obtain n.

What's the maximum value for an int in PHP?

From the PHP manual:

The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). PHP does not support unsigned integers. Integer size can be determined using the constant PHP_INT_SIZE, and maximum value using the constant PHP_INT_MAX since PHP 4.4.0 and PHP 5.0.5.

64-bit platforms usually have a maximum value of about 9E18, except on Windows prior to PHP 7, where it was always 32 bit.

PHP array delete by value (not key)

here is one simple but understandable solution:

$messagesFiltered = [];
foreach ($messages as $message) {
    if (401 != $message) {
        $messagesFiltered[] = $message;
    }
}
$messages = $messagesFiltered;

Angularjs simple file download causes router to redirect

https://docs.angularjs.org/guide/$location#html-link-rewriting

In cases like the following, links are not rewritten; instead, the browser will perform a full page reload to the original link.

  • Links that contain target element Example:
    <a href="/ext/link?a=b" target="_self">link</a>

  • Absolute links that go to a different domain Example:
    <a href="http://angularjs.org/">link</a>

  • Links starting with '/' that lead to a different base path when base is defined Example:
    <a href="/not-my-base/link">link</a>

So in your case, you should add a target attribute like so...

<a target="_self" href="example.com/uploads/asd4a4d5a.pdf" download="foo.pdf">

How do I connect to a SQL Server 2008 database using JDBC?

Try this.

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.Statement;

public class SQLUtil {

public void dbConnect(String db_connect_string,String db_userid, String db_password) {

try {

     Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
     Connection conn = DriverManager.getConnection(db_connect_string,
              db_userid, db_password);
     System.out.println("connected");
     Statement statement = conn.createStatement();
     String queryString = "select * from cpl";
     ResultSet rs = statement.executeQuery(queryString);
     while (rs.next()) {
        System.out.println(rs.getString(1));
     }
  } catch (Exception e) {
     e.printStackTrace();
  }    }

public static void main(String[] args) {

SQLUtil connServer = new SQLUtil();

connServer.dbConnect("jdbc:sqlserver://192.168.10.97:1433;databaseName=myDB", "sa", "0123");

}

}

What do I use for a max-heap implementation in Python?

The solution is to negate your values when you store them in the heap, or invert your object comparison like so:

import heapq

class MaxHeapObj(object):
  def __init__(self, val): self.val = val
  def __lt__(self, other): return self.val > other.val
  def __eq__(self, other): return self.val == other.val
  def __str__(self): return str(self.val)

Example of a max-heap:

maxh = []
heapq.heappush(maxh, MaxHeapObj(x))
x = maxh[0].val  # fetch max value
x = heapq.heappop(maxh).val  # pop max value

But you have to remember to wrap and unwrap your values, which requires knowing if you are dealing with a min- or max-heap.

MinHeap, MaxHeap classes

Adding classes for MinHeap and MaxHeap objects can simplify your code:

class MinHeap(object):
  def __init__(self): self.h = []
  def heappush(self, x): heapq.heappush(self.h, x)
  def heappop(self): return heapq.heappop(self.h)
  def __getitem__(self, i): return self.h[i]
  def __len__(self): return len(self.h)

class MaxHeap(MinHeap):
  def heappush(self, x): heapq.heappush(self.h, MaxHeapObj(x))
  def heappop(self): return heapq.heappop(self.h).val
  def __getitem__(self, i): return self.h[i].val

Example usage:

minh = MinHeap()
maxh = MaxHeap()
# add some values
minh.heappush(12)
maxh.heappush(12)
minh.heappush(4)
maxh.heappush(4)
# fetch "top" values
print(minh[0], maxh[0])  # "4 12"
# fetch and remove "top" values
print(minh.heappop(), maxh.heappop())  # "4 12"

Hibernate: best practice to pull all lazy collections

if you using jpa repository, set properties.put("hibernate.enable_lazy_load_no_trans",true); to jpaPropertymap

How to comment multiple lines with space or indent

  • You can customize every short cut operation according to your habbit.

Just go to Tools > Options > Environment > Keyboard > Find the action you want to set key board short-cut and change according to keyboard habbit.

How to keep form values after post

If you are looking to just repopulate the fields with the values that were posted in them, then just echo the post value back into the field, like so:

<input type="text" name="myField1" value="<?php echo isset($_POST['myField1']) ? $_POST['myField1'] : '' ?>" />

Fix height of a table row in HTML Table

the bottom cell will grow as you enter more text ... setting the table width will help too

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
</head>
<body>
<table id="content" style="min-height:525px; height:525px; width:100%; border:0px; margin:0; padding:0; border-collapse:collapse;">
<tr><td style="height:10px; background-color:#900;">Upper</td></tr>
<tr><td style="min-height:515px; height:515px; background-color:#909;">lower<br/>
</td></tr>
</table>
</body>
</html>