Programs & Examples On #Rapache

rApache is a project supporting web application development using the R statistical language and environment and the Apache web server

How do I convert from BLOB to TEXT in MySQL?

You can do it very easily.

ALTER TABLE `table_name` CHANGE COLUMN `column_name` `column_name` LONGTEXT NULL DEFAULT NULL ;

The above query worked for me. I hope it helps you too.

Presenting a UIAlertController properly on an iPad using iOS 8

You can present a UIAlertController from a popover by using UIPopoverPresentationController.

In Obj-C:

UIViewController *self; // code assumes you're in a view controller
UIButton *button; // the button you want to show the popup sheet from

UIAlertController *alertController;
UIAlertAction *destroyAction;
UIAlertAction *otherAction;

alertController = [UIAlertController alertControllerWithTitle:nil
                                                      message:nil
                           preferredStyle:UIAlertControllerStyleActionSheet];
destroyAction = [UIAlertAction actionWithTitle:@"Remove All Data"
                                         style:UIAlertActionStyleDestructive
                                       handler:^(UIAlertAction *action) {
                                           // do destructive stuff here
                                       }];
otherAction = [UIAlertAction actionWithTitle:@"Blah"
                                       style:UIAlertActionStyleDefault
                                     handler:^(UIAlertAction *action) {
                                         // do something here
                                     }];
// note: you can control the order buttons are shown, unlike UIActionSheet
[alertController addAction:destroyAction];
[alertController addAction:otherAction];
[alertController setModalPresentationStyle:UIModalPresentationPopover];

UIPopoverPresentationController *popPresenter = [alertController 
                                              popoverPresentationController];
popPresenter.sourceView = button;
popPresenter.sourceRect = button.bounds;
[self presentViewController:alertController animated:YES completion:nil];

Editing for Swift 4.2, though there are many blogs available for the same but it may save your time to go and search for them.

if let popoverController = yourAlert.popoverPresentationController {
    popoverController.sourceView = self.view //to set the source of your alert
    popoverController.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0) // you can set this as per your requirement.
    popoverController.permittedArrowDirections = [] //to hide the arrow of any particular direction
}

Search for exact match of string in excel row using VBA Macro

Try this:

Sub GetColumns()

Dim lnRow As Long, lnCol As Long

lnRow = 3 'For testing

lnCol = Sheet1.Cells(lnRow, 1).EntireRow.Find(What:="sds", LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False).Column

End Sub

Probably best not to use colIndex and rowIndex as variable names as they are already mentioned in the Excel Object Library.

How to destroy a JavaScript object?

You can't delete objects, they are removed when there are no more references to them. You can delete references with delete.

However, if you have created circular references in your objects you may have to de-couple some things.

What is the preferred syntax for defining enums in JavaScript?

Even though only static methods (and not static properties) are supported in ES2015 (see here as well, §15.2.2.2), curiously you can use the below with Babel with the es2015 preset:

class CellState {
    v: string;
    constructor(v: string) {
        this.v = v;
        Object.freeze(this);
    }
    static EMPTY       = new CellState('e');
    static OCCUPIED    = new CellState('o');
    static HIGHLIGHTED = new CellState('h');
    static values      = function(): Array<CellState> {
        const rv = [];
        rv.push(CellState.EMPTY);
        rv.push(CellState.OCCUPIED);
        rv.push(CellState.HIGHLIGHTED);
        return rv;
    }
}
Object.freeze(CellState);

I found this to be working as expected even across modules (e.g. importing the CellState enum from another module) and also when I import a module using Webpack.

The advantage this method has over most other answers is that you can use it alongside a static type checker (e.g. Flow) and you can assert, at development time using static type checking, that your variables, parameters, etc. are of the specific CellState "enum" rather than some other enum (which would be impossible to distinguish if you used generic objects or symbols).

update

The above code has a deficiency in that it allows one to create additional objects of type CellState (even though one can't assign them to the static fields of CellState since it's frozen). Still, the below more refined code offers the following advantages:

  1. no more objects of type CellState may be created
  2. you are guaranteed that no two enum instances are assigned the same code
  3. utility method to get the enum back from a string representation
  4. the values function that returns all instances of the enum does not have to create the return value in the above, manual (and error-prone) way.

    'use strict';
    
    class Status {
    
    constructor(code, displayName = code) {
        if (Status.INSTANCES.has(code))
            throw new Error(`duplicate code value: [${code}]`);
        if (!Status.canCreateMoreInstances)
            throw new Error(`attempt to call constructor(${code}`+
           `, ${displayName}) after all static instances have been created`);
        this.code        = code;
        this.displayName = displayName;
        Object.freeze(this);
        Status.INSTANCES.set(this.code, this);
    }
    
    toString() {
        return `[code: ${this.code}, displayName: ${this.displayName}]`;
    }
    static INSTANCES   = new Map();
    static canCreateMoreInstances      = true;
    
    // the values:
    static ARCHIVED    = new Status('Archived');
    static OBSERVED    = new Status('Observed');
    static SCHEDULED   = new Status('Scheduled');
    static UNOBSERVED  = new Status('Unobserved');
    static UNTRIGGERED = new Status('Untriggered');
    
    static values      = function() {
        return Array.from(Status.INSTANCES.values());
    }
    
    static fromCode(code) {
        if (!Status.INSTANCES.has(code))
            throw new Error(`unknown code: ${code}`);
        else
            return Status.INSTANCES.get(code);
    }
    }
    
    Status.canCreateMoreInstances = false;
    Object.freeze(Status);
    exports.Status = Status;
    

Sync data between Android App and webserver

one way to accomplish this to have a server side application that waits for the data. The data can be sent using HttpRequest objects in Java or you can write your own TCP/IP data transfer utility. Data can be sent using JSON format or any other format that you think is suitable. Also data can be encrypted before sending to server if it contains sensitive information. All Server application have to do is just wait for HttpRequests to come in and parse the data and store it anywhere you want.

Programmatically switching between tabs within Swift

To expand on @codester's answer, you don't need to check and then assign, you can do it in one step:

func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {
    // Override point for customization after application launch.

    if let tabBarController = self.window!.rootViewController as? UITabBarController {
        tabBarController.selectedIndex = 1
    }

    return true
}

How to create an empty array in Swift?

As per Swift 5

    // An array of 'Int' elements
    let oddNumbers = [1, 3, 5, 7, 9, 11, 13, 15]

    // An array of 'String' elements
    let streets = ["Albemarle", "Brandywine", "Chesapeake"]

    // Shortened forms are preferred
    var emptyDoubles: [Double] = []

    // The full type name is also allowed
    var emptyFloats: Array<Float> = Array()

Looping through all the properties of object php

If this is just for debugging output, you can use the following to see all the types and values as well.

var_dump($obj);

If you want more control over the output you can use this:

foreach ($obj as $key => $value) {
    echo "$key => $value\n";
}

How to check whether a file is empty or not?

import os    
os.path.getsize(fullpathhere) > 0

IndexError: too many indices for array

The message that you are getting is not for the default Exception of Python:

For a fresh python list, IndexError is thrown only on index not being in range (even docs say so).

>>> l = []
>>> l[1]
IndexError: list index out of range

If we try passing multiple items to list, or some other value, we get the TypeError:

>>> l[1, 2]
TypeError: list indices must be integers, not tuple

>>> l[float('NaN')]
TypeError: list indices must be integers, not float

However, here, you seem to be using matplotlib that internally uses numpy for handling arrays. On digging deeper through the codebase for numpy, we see:

static NPY_INLINE npy_intp
unpack_tuple(PyTupleObject *index, PyObject **result, npy_intp result_n)
{
    npy_intp n, i;
    n = PyTuple_GET_SIZE(index);
    if (n > result_n) {
        PyErr_SetString(PyExc_IndexError,
                        "too many indices for array");
        return -1;
    }
    for (i = 0; i < n; i++) {
        result[i] = PyTuple_GET_ITEM(index, i);
        Py_INCREF(result[i]);
    }
    return n;
}

where, the unpack method will throw an error if it the size of the index is greater than that of the results.

So, Unlike Python which raises a TypeError on incorrect Indexes, Numpy raises the IndexError because it supports multidimensional arrays.

String Concatenation in EL

it also can be a great idea using concat for EL + MAP + JSON problem like in this example :

#{myMap[''.concat(myid)].content}

SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known

I was having the same problem and everyone was talking about this is related to DNS configuration, which make sense, since your container maybe isn't knowing how to resolve the name of the domain where your database is.

I guess your can configure that at the moment you start your container, but I think it's better to config this once and for all.

I'm using Windows 10 and in this case docker's gui give us some facilities.

Just right click on docker's icon in the tray bar and select "Settings" item.

Docker's options

Then, on the Docker's window, select the "Network" section and change the DNS option from "Automatic" to "Fixed" and hit "Apply". Docker will restart itself after that. I putted the Google's DNS (8.8.8.8) and it worked fine to me.

docker's network section with dns config

Hope it helps.

Difference between a user and a schema in Oracle?

A user account is like relatives who holds a key to your home, but does not own anything i.e. a user account does not own any database object...no data dictionary...

Whereas a schema is an encapsulation of database objects. It's like the owner of the house who owns everything in your house and a user account will be able to access the goods at the home only when the owner i.e. schema gives needed grants to it.

Increase distance between text and title on the y-axis

Based on this forum post: https://groups.google.com/forum/#!topic/ggplot2/mK9DR3dKIBU

Sounds like the easiest thing to do is to add a line break (\n) before your x axis, and after your y axis labels. Seems a lot easier (although dumber) than the solutions posted above.

ggplot(mpg, aes(cty, hwy)) + 
    geom_point() + 
    xlab("\nYour_x_Label") + ylab("Your_y_Label\n")

Hope that helps!

Comparing two joda DateTime instances

This code (example) :

    Chronology ch1 = GregorianChronology.getInstance();     Chronology ch2 = ISOChronology.getInstance();      DateTime dt = new DateTime("2013-12-31T22:59:21+01:00",ch1);     DateTime dt2 = new DateTime("2013-12-31T22:59:21+01:00",ch2);      System.out.println(dt);     System.out.println(dt2);      boolean b = dt.equals(dt2);      System.out.println(b); 

Will print :

2013-12-31T16:59:21.000-05:00 2013-12-31T16:59:21.000-05:00 false 

You are probably comparing two DateTimes with same date but different Chronology.

Create unique constraint with null columns

Create two partial indexes:

CREATE UNIQUE INDEX favo_3col_uni_idx ON favorites (user_id, menu_id, recipe_id)
WHERE menu_id IS NOT NULL;

CREATE UNIQUE INDEX favo_2col_uni_idx ON favorites (user_id, recipe_id)
WHERE menu_id IS NULL;

This way, there can only be one combination of (user_id, recipe_id) where menu_id IS NULL, effectively implementing the desired constraint.

Possible drawbacks: you cannot have a foreign key referencing (user_id, menu_id, recipe_id), you cannot base CLUSTER on a partial index, and queries without a matching WHERE condition cannot use the partial index. (It seems unlikely you'd want a FK reference three columns wide - use the PK column instead).

If you need a complete index, you can alternatively drop the WHERE condition from favo_3col_uni_idx and your requirements are still enforced.
The index, now comprising the whole table, overlaps with the other one and gets bigger. Depending on typical queries and the percentage of NULL values, this may or may not be useful. In extreme situations it might even help to maintain all three indexes (the two partial ones and a total on top).

Aside: I advise not to use mixed case identifiers in PostgreSQL.

How to create a 100% screen width div inside a container in bootstrap?

The reason why your full-width-div doesn't stretch 100% to your screen it's because of its parent "container" which occupies only about 80% of the screen.

If you want to make it stretch 100% to the screen either you make the "full-width-div" position fixed or use the "container-fluid" class instead of "container".

see Bootstrap 3 docs: http://getbootstrap.com/css/#grid

SQL time difference between two dates result in hh:mm:ss

I came across this post today as I was trying to gather the time difference between fields located in separate tables joined together on a key field. This is the working code for such an endeavor. (tested in sql 2010) Bare in mind that my original query co-joined 6 tables on a common keyfield, in the code below I have removed the other tables as to not cause any confusion for the reader.

The purpose of the query is to calculate the difference between the variables CreatedUTC & BackupUTC, where difference is expressed in days and the field is called 'DaysActive.'

declare @CreatedUTC datetime
declare @BackupUtc datetime


SELECT TOP 500

table02.Column_CreatedUTC AS DeviceCreated,
CAST(DATEDIFF(day, table02.Column_CreatedUTC, table03.Column_EndDateUTC) AS nvarchar(5))+ ' Days' As DaysActive,
table03.Column_EndDateUTC AS LastCompleteBackup

FROM

Operations.table01 AS table01

LEFT OUTER JOIN

    dbo.table02 AS table02
ON
    table02.Column_KeyField = table01.Column_KeyField

LEFT OUTER JOIN 

    dbo.table03 AS table03
ON
    table01.Column_KeyField = table03.Column_KeyField

Where table03.Column_EndDateUTC > dateadd(hour, -24, getutcdate()) --Gathers records with an end date in the last 24 hours
AND table02.[Column_CreatedUTC] = COALESCE(@CreatedUTC, table02.[Column_CreatedUTC])
AND table03.[Column_EndDateUTC] = COALESCE(@BackupUTC, table03.[Column_EndDateUTC])

GROUP BY table03.Column_EndDateUTC, table02.Column_CreatedUTC
ORDER BY table02.Column_CreatedUTC ASC, DaysActive, table03.Column_EndDateUTC DESC

The Output will be as follows:

[DeviceCreated]..[DaysActive]..[LastCompleteBackup]
---------------------------------------------------------
[2/13/12 16:04]..[463 Days]....[5/21/13 12:14]
[2/12/13 22:37]..[97 Days].....[5/20/13 22:10]

How to use store and use session variables across pages?

Try this:

<!-- first page -->
<?php
  session_start(); 
  session_register('myvar');
  $_SESSION['myvar'] == 'myvalue';
?>

<!-- second page -->
<?php
    session_start();
    echo("1");
    if(session_is_registered('myvar'))
    {
        echo("2");
       if($_SESSION['myvar'] == 'myvalue')
       {
           echo("3");
           exit;
       }
    }
    ?>

Convenient way to parse incoming multipart/form-data parameters in a Servlet

Solutions:

Solution A:

  1. Download http://www.servlets.com/cos/index.html
  2. Invoke getParameters() on com.oreilly.servlet.MultipartRequest

Solution B:

  1. Download http://jakarta.Apache.org/commons/fileupload/
  2. Invoke readHeaders() in org.apache.commons.fileupload.MultipartStream

Solution C:

  1. Download http://users.boone.net/wbrameld/multipartformdata/
  2. Invoke getParameter on com.bigfoot.bugar.servlet.http.MultipartFormData

Solution D:

Use Struts. Struts 1.1 handles this automatically.

Reference: http://www.jguru.com/faq/view.jsp?EID=1045507

How to install SQL Server 2005 Express in Windows 8

I found that on Windows 8.1 with an instance of SQL 2014 already installed, if I ran the SQLEXPR.EXE and then dismissed the Windows 'warning this may be incompatible' dialogs, that the installer completed successfully.

I suspect having 2014 bits already in place probably helped.

Why should I use a pointer rather than the object itself?

It's very unfortunate that you see dynamic allocation so often. That just shows how many bad C++ programmers there are.

In a sense, you have two questions bundled up into one. The first is when should we use dynamic allocation (using new)? The second is when should we use pointers?

The important take-home message is that you should always use the appropriate tool for the job. In almost all situations, there is something more appropriate and safer than performing manual dynamic allocation and/or using raw pointers.

Dynamic allocation

In your question, you've demonstrated two ways of creating an object. The main difference is the storage duration of the object. When doing Object myObject; within a block, the object is created with automatic storage duration, which means it will be destroyed automatically when it goes out of scope. When you do new Object(), the object has dynamic storage duration, which means it stays alive until you explicitly delete it. You should only use dynamic storage duration when you need it. That is, you should always prefer creating objects with automatic storage duration when you can.

The main two situations in which you might require dynamic allocation:

  1. You need the object to outlive the current scope - that specific object at that specific memory location, not a copy of it. If you're okay with copying/moving the object (most of the time you should be), you should prefer an automatic object.
  2. You need to allocate a lot of memory, which may easily fill up the stack. It would be nice if we didn't have to concern ourselves with this (most of the time you shouldn't have to), as it's really outside the purview of C++, but unfortunately, we have to deal with the reality of the systems we're developing for.

When you do absolutely require dynamic allocation, you should encapsulate it in a smart pointer or some other type that performs RAII (like the standard containers). Smart pointers provide ownership semantics of dynamically allocated objects. Take a look at std::unique_ptr and std::shared_ptr, for example. If you use them appropriately, you can almost entirely avoid performing your own memory management (see the Rule of Zero).

Pointers

However, there are other more general uses for raw pointers beyond dynamic allocation, but most have alternatives that you should prefer. As before, always prefer the alternatives unless you really need pointers.

  1. You need reference semantics. Sometimes you want to pass an object using a pointer (regardless of how it was allocated) because you want the function to which you're passing it to have access that that specific object (not a copy of it). However, in most situations, you should prefer reference types to pointers, because this is specifically what they're designed for. Note this is not necessarily about extending the lifetime of the object beyond the current scope, as in situation 1 above. As before, if you're okay with passing a copy of the object, you don't need reference semantics.

  2. You need polymorphism. You can only call functions polymorphically (that is, according to the dynamic type of an object) through a pointer or reference to the object. If that's the behavior you need, then you need to use pointers or references. Again, references should be preferred.

  3. You want to represent that an object is optional by allowing a nullptr to be passed when the object is being omitted. If it's an argument, you should prefer to use default arguments or function overloads. Otherwise, you should preferably use a type that encapsulates this behavior, such as std::optional (introduced in C++17 - with earlier C++ standards, use boost::optional).

  4. You want to decouple compilation units to improve compilation time. The useful property of a pointer is that you only require a forward declaration of the pointed-to type (to actually use the object, you'll need a definition). This allows you to decouple parts of your compilation process, which may significantly improve compilation time. See the Pimpl idiom.

  5. You need to interface with a C library or a C-style library. At this point, you're forced to use raw pointers. The best thing you can do is make sure you only let your raw pointers loose at the last possible moment. You can get a raw pointer from a smart pointer, for example, by using its get member function. If a library performs some allocation for you which it expects you to deallocate via a handle, you can often wrap the handle up in a smart pointer with a custom deleter that will deallocate the object appropriately.

Extracting substrings in Go

WARNING: operating on strings alone will only work with ASCII and will count wrong when input is a non-ASCII UTF-8 encoded character, and will probably even corrupt characters since it cuts multibyte chars mid-sequence.

Here's a UTF-8-aware version:

// NOTE: this isn't multi-Unicode-codepoint aware, like specifying skintone or
//       gender of an emoji: https://unicode.org/emoji/charts/full-emoji-modifiers.html
func substr(input string, start int, length int) string {
    asRunes := []rune(input)
    
    if start >= len(asRunes) {
        return ""
    }
    
    if start+length > len(asRunes) {
        length = len(asRunes) - start
    }
    
    return string(asRunes[start : start+length])
}

Textarea onchange detection

I know this question was specific to JavaScript, however, there seems to be no good, clean way to ALWAYS detect when a textarea changes in all current browsers. I've learned jquery has taken care of it for us. It even handles contextual menu changes to text areas. The same syntax is used regardless of input type.

    $('div.lawyerList').on('change','textarea',function(){
      // Change occurred so count chars...
    });

or

    $('textarea').on('change',function(){
      // Change occurred so count chars...
    });

Groovy method with optional parameters

Just a simplification of the Tim's answer. The groovy way to do it is using a map, as already suggested, but then let's put the mandatory parameters also in the map. This will look like this:

def someMethod(def args) {
    println "MANDATORY1=${args.mandatory1}"
    println "MANDATORY2=${args.mandatory2}"
    println "OPTIONAL1=${args?.optional1}"
    println "OPTIONAL2=${args?.optional2}"
}

someMethod mandatory1:1, mandatory2:2, optional1:3

with the output:

MANDATORY1=1
MANDATORY2=2
OPTIONAL1=3
OPTIONAL2=null

This looks nicer and the advantage of this is that you can change the order of the parameters as you like.

Use mysql_fetch_array() with foreach() instead of while()

the most obvious way to make foreach a possibility includes materializing the whole resultset in an array, which will probably kill you memory-wise, sooner or later. you'd need to turn to iterators to avoid that problem. see http://www.php.net/~helly/php/ext/spl/

How to execute raw queries with Laravel 5.1?

I found the solution in this topic and I code this:

$cards = DB::select("SELECT
        cards.id_card,
        cards.hash_card,
        cards.`table`,
        users.name,
        0 as total,
        cards.card_status,
        cards.created_at as last_update
    FROM cards
    LEFT JOIN users
    ON users.id_user = cards.id_user
    WHERE hash_card NOT IN ( SELECT orders.hash_card FROM orders )
    UNION
    SELECT
        cards.id_card,
        orders.hash_card,
        cards.`table`,
        users.name,
        sum(orders.quantity*orders.product_price) as total, 
        cards.card_status, 
        max(orders.created_at) last_update 
    FROM menu.orders
    LEFT JOIN cards
    ON cards.hash_card = orders.hash_card
    LEFT JOIN users
    ON users.id_user = cards.id_user
    GROUP BY hash_card
    ORDER BY id_card ASC");

What techniques can be used to define a class in JavaScript, and what are their trade-offs?

A base

function Base(kind) {
    this.kind = kind;
}

A class

// Shared var
var _greeting;

(function _init() {
    Class.prototype = new Base();
    Class.prototype.constructor = Class;
    Class.prototype.log = function() { _log.apply(this, arguments); }
    _greeting = "Good afternoon!";
})();

function Class(name, kind) {
    Base.call(this, kind);
    this.name = name;
}

// Shared function
function _log() {
    console.log(_greeting + " Me name is " + this.name + " and I'm a " + this.kind);
}

Action

var c = new Class("Joe", "Object");
c.log(); // "Good afternoon! Me name is Joe and I'm a Object"

How can I use mySQL replace() to replace strings in multiple records?

This will help you.

UPDATE play_school_data SET title= REPLACE(title, "&#39;", "'") WHERE title = "Elmer&#39;s Parade";

Result:

title = Elmer's Parade

Python Iterate Dictionary by Index

Do this:

for i in dict.keys():
  dict[i]

Oracle SQL: Use sequence in insert with Select Statement

Assuming that you want to group the data before you generate the key with the sequence, it sounds like you want something like

INSERT INTO HISTORICAL_CAR_STATS (
    HISTORICAL_CAR_STATS_ID, 
    YEAR,
    MONTH, 
    MAKE,
    MODEL,
    REGION,
    AVG_MSRP,
    CNT) 
SELECT MY_SEQ.nextval,
       year,
       month,
       make,
       model,
       region,
       avg_msrp,
       cnt
  FROM (SELECT '2010' year,
               '12' month,
               'ALL' make,
               'ALL' model,
               REGION,
               sum(AVG_MSRP*COUNT)/sum(COUNT) avg_msrp,
               sum(cnt) cnt
          FROM HISTORICAL_CAR_STATS
         WHERE YEAR = '2010' 
           AND MONTH = '12'
           AND MAKE != 'ALL' 
         GROUP BY REGION)

Convert DateTime to TimeSpan

In case you are using WPF and Xceed's TimePicker (which seems to be using DateTime?) as a timespan picker -as I do right now- you can get the total milliseconds (or a TimeSpan) out of it like so:

var milliseconds = DateTimeToTimeSpan(timePicker.Value).TotalMilliseconds;

    TimeSpan DateTimeToTimeSpan(DateTime? ts)
    {
        if (!ts.HasValue) return TimeSpan.Zero;
        else return new TimeSpan(0, ts.Value.Hour, ts.Value.Minute, ts.Value.Second, ts.Value.Millisecond);
    }

XAML :

<Xceed:TimePicker x:Name="timePicker" Format="Custom" FormatString="H'h 'm'm 's's'" />

If not, I guess you could just adjust my DateTimeToTimeSpan() so that it also takes 'days' into account or do sth like dateTime.Substract(DateTime.MinValue).TotalMilliseconds.

How do I read a file line by line in VB Script?

When in doubt, read the documentation:

filename = "C:\Temp\vblist.txt"

Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename)

Do Until f.AtEndOfStream
  WScript.Echo f.ReadLine
Loop

f.Close

Can anyone explain me StandardScaler?

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


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

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


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


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


Example:

from sklearn.preprocessing import StandardScaler
import numpy as np

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

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

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

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

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

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

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

The maths:

enter image description here


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

How do I concatenate two arrays in C#?

For int[] what you've done looks good to me. astander's answer would also work well for List<int>.

Convert Unix timestamp to a date string

Put the following in your ~/.bashrc :

function unixts() { date -d "@$1"; }

Example usage:

$ unixts 1551276383

Wed Feb 27 14:06:23 GMT 2019

How can I make a JUnit test wait?

You can use java.util.concurrent.TimeUnit library which internally uses Thread.sleep. The syntax should look like this :

@Test
public void testExipres(){
    SomeCacheObject sco = new SomeCacheObject();
    sco.putWithExipration("foo", 1000);

    TimeUnit.MINUTES.sleep(2);

    assertNull(sco.getIfNotExipred("foo"));
}

This library provides more clear interpretation for time unit. You can use 'HOURS'/'MINUTES'/'SECONDS'.

Eclipse, regular expression search and replace

Using ...
search = (^.*import )(.*)(\(.*\):)
replace = $1$2

...replaces ...

from checks import checklist(_list):

...with...

from checks import checklist



Blocks in regex are delineated by parenthesis (which are not preceded by a "\")

(^.*import ) finds "from checks import " and loads it to $1 (eclipse starts counting at 1)

(.*) find the next "everything" until the next encountered "(" and loads it to $2. $2 stops at the "(" because of the next part (see next line below)

(\(.*\):) says "at the first encountered "(" after starting block $2...stop block $2 and start $3. $3 gets loaded with the "('any text'):" or, in the example, the "(_list):"

Then in the replace, just put the $1$2 to replace all three blocks with just the first two.



Screenshot

Exception: Serialization of 'Closure' is not allowed

As already stated: closures, out of the box, cannot be serialized.

However, using the __sleep(), __wakeup() magic methods and reflection u CAN manually make closures serializable. For more details see extending-php-5-3-closures-with-serialization-and-reflection

This makes use of reflection and the php function eval. Do note this opens up the possibility of CODE injection, so please take notice of WHAT you are serializing.

Logger slf4j advantages of formatting with {} instead of string concatenation

I think from the author's point of view, the main reason is to reduce the overhead for string concatenation.I just read the logger's documentation, you could find following words:

/**
* <p>This form avoids superfluous string concatenation when the logger
* is disabled for the DEBUG level. However, this variant incurs the hidden
* (and relatively small) cost of creating an <code>Object[]</code> before 
  invoking the method,
* even if this logger is disabled for DEBUG. The variants taking
* {@link #debug(String, Object) one} and {@link #debug(String, Object, Object) two}
* arguments exist solely in order to avoid this hidden cost.</p>
*/
*
 * @param format    the format string
 * @param arguments a list of 3 or more arguments
 */
public void debug(String format, Object... arguments);

using OR and NOT in solr query

Instead of "NOT [condition]" use "(*:* NOT [condition])"

Formatting numbers (decimal places, thousands separators, etc) with CSS

Well, for any numbers in Javascript I use next one:

var a = "1222333444555666777888999";
a = a.replace(new RegExp("^(\\d{" + (a.length%3?a.length%3:0) + "})(\\d{3})", "g"), "$1 $2").replace(/(\d{3})+?/gi, "$1 ").trim();

and if you need to use any other separator as comma for example:

var sep = ",";
a = a.replace(/\s/g, sep);

or as a function:

function numberFormat(_number, _sep) {
    _number = typeof _number != "undefined" && _number > 0 ? _number : "";
    _number = _number.replace(new RegExp("^(\\d{" + (_number.length%3? _number.length%3:0) + "})(\\d{3})", "g"), "$1 $2").replace(/(\d{3})+?/gi, "$1 ").trim();
    if(typeof _sep != "undefined" && _sep != " ") {
        _number = _number.replace(/\s/g, _sep);
    }
    return _number;
}

PHP - concatenate or directly insert variables in string

I use a dot(.) to concate string and variable. like this-

echo "Hello ".$var;

Sometimes, I use curly braces to concate string and variable that looks like this-

echo "Hello {$var}";

Import error No module named skimage

Hey this is pretty simple to solve this error.Just follow this steps:

First uninstall any existing installation:

pip uninstall scikit-image

or, on conda-based systems:

conda uninstall scikit-image

Now, clone scikit-image on your local computer, and install:

git clone https://github.com/scikit-image/scikit-image.git
cd scikit-image
pip install -e .

To update the installation:

git pull  # Grab latest source
pip install -e .  # Reinstall

For other os and manual process please check this Link.

Python safe method to get value of nested dictionary

A simple class that can wrap a dict, and retrieve based on a key:

class FindKey(dict):
    def get(self, path, default=None):
        keys = path.split(".")
        val = None

        for key in keys:
            if val:
                if isinstance(val, list):
                    val = [v.get(key, default) if v else None for v in val]
                else:
                    val = val.get(key, default)
            else:
                val = dict.get(self, key, default)

            if not val:
                break

        return val

For example:

person = {'person':{'name':{'first':'John'}}}
FindDict(person).get('person.name.first') # == 'John'

If the key doesn't exist, it returns None by default. You can override that using a default= key in the FindDict wrapper -- for example`:

FindDict(person, default='').get('person.name.last') # == doesn't exist, so ''

Bootstrap fixed header and footer with scrolling body-content area in fluid-container

Another option would be using flexbox.

While it's not supported by IE8 and IE9, you could consider:

  • Not minding about those old IE versions
  • Providing a fallback
  • Using a polyfill

Despite some additional browser-specific style prefixing would be necessary for full cross-browser support, you can see the basic usage either on this fiddle and on the following snippet:

_x000D_
_x000D_
html {_x000D_
  height: 100%;_x000D_
}_x000D_
html body {_x000D_
  height: 100%;_x000D_
  overflow: hidden;_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
}_x000D_
html body .container-fluid.body-content {_x000D_
  width: 100%;_x000D_
  overflow-y: auto;_x000D_
}_x000D_
header {_x000D_
    background-color: #4C4;_x000D_
    min-height: 50px;_x000D_
    width: 100%;_x000D_
}_x000D_
footer {_x000D_
    background-color: #4C4;_x000D_
    min-height: 30px;_x000D_
    width: 100%;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<header></header>_x000D_
<div class="container-fluid body-content">_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
</div>_x000D_
<footer></footer>
_x000D_
_x000D_
_x000D_

How can I create a Java 8 LocalDate from a long Epoch time in Milliseconds?

In a specific case where your epoch seconds timestamp comes from SQL or is related to SQL somehow, you can obtain it like this:

long startDateLong = <...>

LocalDate theDate = new java.sql.Date(startDateLong).toLocalDate();

What REALLY happens when you don't free after malloc?

It is completely fine to leave memory unfreed when you exit; malloc() allocates the memory from the memory area called "the heap", and the complete heap of a process is freed when the process exits.

That being said, one reason why people still insist that it is good to free everything before exiting is that memory debuggers (e.g. valgrind on Linux) detect the unfreed blocks as memory leaks, and if you have also "real" memory leaks, it becomes more difficult to spot them if you also get "fake" results at the end.

remove all special characters in java

use [\\W+] or "[^a-zA-Z0-9]" as regex to match any special characters and also use String.replaceAll(regex, String) to replace the spl charecter with an empty string. remember as the first arg of String.replaceAll is a regex you have to escape it with a backslash to treat em as a literal charcter.

          String c= "hjdg$h&jk8^i0ssh6";
        Pattern pt = Pattern.compile("[^a-zA-Z0-9]");
        Matcher match= pt.matcher(c);
        while(match.find())
        {
            String s= match.group();
        c=c.replaceAll("\\"+s, "");
        }
        System.out.println(c);

How to check whether a string contains a substring in JavaScript?

ECMAScript 6 introduced String.prototype.includes:

_x000D_
_x000D_
const string = "foo";_x000D_
const substring = "oo";_x000D_
_x000D_
console.log(string.includes(substring));
_x000D_
_x000D_
_x000D_

includes doesn’t have Internet Explorer support, though. In ECMAScript 5 or older environments, use String.prototype.indexOf, which returns -1 when a substring cannot be found:

_x000D_
_x000D_
var string = "foo";_x000D_
var substring = "oo";_x000D_
_x000D_
console.log(string.indexOf(substring) !== -1);
_x000D_
_x000D_
_x000D_

Github: error cloning my private repository

For me what solved the problem was when on my windows 10 box, I tried uninstalling git and resintalling, using Windows Cmd as default not Git Bash

Open CMD and run the following

//Once installed try to resintall the bin folder 
git config --system http.sslcainfo \bin/curl-ca-bundle.crt

//disable ssl verification
git config --global http.sslverify "false"

//Then try to clone repo again
git clone [email protected]:account/someproject.git

XPath - Difference between node() and text()

For me it was a big difference when I faced this scenario (here my story:)

<?xml version="1.0" encoding="UTF-8"?>
<sentence id="S1.6">When U937 cells were infected with HIV-1, 
        
    <xcope id="X1.6.3">
        <cue ref="X1.6.3" type="negation">no</cue> 
                        
                        induction of NF-KB factor was detected
        
    </xcope>
                    
, whereas high level of progeny virions was produced, 
        
    <xcope id="X1.6.2">
        <cue ref="X1.6.2" type="speculation">suggesting</cue> that this factor was 
        <xcope id="X1.6.1">
            <cue ref="X1.6.1" type="negation">not</cue> required for viral replication
        </xcope>
    </xcope>.

</sentence>

I needed to extract text between tags and aggregate (by concat) the text including in innner tags.

/node() did the job, while /text() made half job

/text() only returned text not included in inner tags, because inner tags are not "text nodes". You may think, "just extract text included in the inner tags in an additional xpath", however, it becomes challenging to sort the text in this original order because you dont know where to place the aggregated text from the inner tags!because you dont know where to place the aggregated text from the inner nodes.

  1. When U937 cells were infected with HIV-1,
  2. no induction of NF-KB factor was detected
  3. , whereas high level of progeny virions was produced,
  4. suggesting that this factor was not required for viral replication
  5. .

Finally, /node() did exactly what I wanted, because it gets the text from inner tags too.

How to set a Timer in Java?

So the first part of the answer is how to do what the subject asks as this was how I initially interpreted it and a few people seemed to find helpful. The question was since clarified and I've extended the answer to address that.

Setting a timer

First you need to create a Timer (I'm using the java.util version here):

import java.util.Timer;

..

Timer timer = new Timer();

To run the task once you would do:

timer.schedule(new TimerTask() {
  @Override
  public void run() {
    // Your database code here
  }
}, 2*60*1000);
// Since Java-8
timer.schedule(() -> /* your database code here */, 2*60*1000);

To have the task repeat after the duration you would do:

timer.scheduleAtFixedRate(new TimerTask() {
  @Override
  public void run() {
    // Your database code here
  }
}, 2*60*1000, 2*60*1000);

// Since Java-8
timer.scheduleAtFixedRate(() -> /* your database code here */, 2*60*1000, 2*60*1000);

Making a task timeout

To specifically do what the clarified question asks, that is attempting to perform a task for a given period of time, you could do the following:

ExecutorService service = Executors.newSingleThreadExecutor();

try {
    Runnable r = new Runnable() {
        @Override
        public void run() {
            // Database task
        }
    };

    Future<?> f = service.submit(r);

    f.get(2, TimeUnit.MINUTES);     // attempt the task for two minutes
}
catch (final InterruptedException e) {
    // The thread was interrupted during sleep, wait or join
}
catch (final TimeoutException e) {
    // Took too long!
}
catch (final ExecutionException e) {
    // An exception from within the Runnable task
}
finally {
    service.shutdown();
}

This will execute normally with exceptions if the task completes within 2 minutes. If it runs longer than that, the TimeoutException will be throw.

One issue is that although you'll get a TimeoutException after the two minutes, the task will actually continue to run, although presumably a database or network connection will eventually time out and throw an exception in the thread. But be aware it could consume resources until that happens.

How can I run a function from a script in command line?

Well, while the other answers are right - you can certainly do something else: if you have access to the bash script, you can modify it, and simply place at the end the special parameter "$@" - which will expand to the arguments of the command line you specify, and since it's "alone" the shell will try to call them verbatim; and here you could specify the function name as the first argument. Example:

$ cat test.sh
testA() {
  echo "TEST A $1";
}

testB() {
  echo "TEST B $2";
}

"$@"


$ bash test.sh
$ bash test.sh testA
TEST A 
$ bash test.sh testA arg1 arg2
TEST A arg1
$ bash test.sh testB arg1 arg2
TEST B arg2

For polish, you can first verify that the command exists and is a function:

# Check if the function exists (bash specific)
if declare -f "$1" > /dev/null
then
  # call arguments verbatim
  "$@"
else
  # Show a helpful error
  echo "'$1' is not a known function name" >&2
  exit 1
fi

Can't change table design in SQL Server 2008

The answer is on the MSDN site:

The Save (Not Permitted) dialog box warns you that saving changes is not permitted because the changes you have made require the listed tables to be dropped and re-created.

The following actions might require a table to be re-created:

  • Adding a new column to the middle of the table
  • Dropping a column
  • Changing column nullability
  • Changing the order of the columns
  • Changing the data type of a column

EDIT 1:

Additional useful informations from here:

To change the Prevent saving changes that require the table re-creation option, follow these steps:

  1. Open SQL Server Management Studio (SSMS).
  2. On the Tools menu, click Options.
  3. In the navigation pane of the Options window, click Designers.
  4. Select or clear the Prevent saving changes that require the table re-creation check box, and then click OK.

Note If you disable this option, you are not warned when you save the table that the changes that you made have changed the metadata structure of the table. In this case, data loss may occur when you save the table.

Risk of turning off the "Prevent saving changes that require table re-creation" option

Although turning off this option can help you avoid re-creating a table, it can also lead to changes being lost. For example, suppose that you enable the Change Tracking feature in SQL Server 2008 to track changes to the table. When you perform an operation that causes the table to be re-created, you receive the error message that is mentioned in the "Symptoms" section. However, if you turn off this option, the existing change tracking information is deleted when the table is re-created. Therefore, we recommend that you do not work around this problem by turning off the option.

Settings, screen shot

Filter rows which contain a certain string

edit included the newer across() syntax

Here's another tidyverse solution, using filter(across()) or previously filter_at. The advantage is that you can easily extend to more than one column.

Below also a solution with filter_all in order to find the string in any column, using diamonds as example, looking for the string "V"

library(tidyverse)

String in only one column

# for only one column... extendable to more than one creating a column list in `across` or `vars`!
mtcars %>% 
  rownames_to_column("type") %>% 
  filter(across(type, ~ !grepl('Toyota|Mazda', .))) %>%
  head()
#>                type  mpg cyl  disp  hp drat    wt  qsec vs am gear carb
#> 1        Datsun 710 22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
#> 2    Hornet 4 Drive 21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
#> 3 Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
#> 4           Valiant 18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
#> 5        Duster 360 14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
#> 6         Merc 240D 24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2

The now superseded syntax for the same would be:

mtcars %>% 
  rownames_to_column("type") %>% 
  filter_at(.vars= vars(type), all_vars(!grepl('Toyota|Mazda',.))) 

String in all columns:

# remove all rows where any column contains 'V'
diamonds %>%
  filter(across(everything(), ~ !grepl('V', .))) %>%
  head
#> # A tibble: 6 x 10
#>   carat cut     color clarity depth table price     x     y     z
#>   <dbl> <ord>   <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl>
#> 1  0.23 Ideal   E     SI2      61.5    55   326  3.95  3.98  2.43
#> 2  0.21 Premium E     SI1      59.8    61   326  3.89  3.84  2.31
#> 3  0.31 Good    J     SI2      63.3    58   335  4.34  4.35  2.75
#> 4  0.3  Good    J     SI1      64      55   339  4.25  4.28  2.73
#> 5  0.22 Premium F     SI1      60.4    61   342  3.88  3.84  2.33
#> 6  0.31 Ideal   J     SI2      62.2    54   344  4.35  4.37  2.71

The now superseded syntax for the same would be:

diamonds %>% 
  filter_all(all_vars(!grepl('V', .))) %>%
  head

I tried to find an across alternative for the following, but I didn't immediately come up with a good solution:

    #get all rows where any column contains 'V'
    diamonds %>%
    filter_all(any_vars(grepl('V',.))) %>%
      head
    #> # A tibble: 6 x 10
    #>   carat cut       color clarity depth table price     x     y     z
    #>   <dbl> <ord>     <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl>
    #> 1 0.23  Good      E     VS1      56.9    65   327  4.05  4.07  2.31
    #> 2 0.290 Premium   I     VS2      62.4    58   334  4.2   4.23  2.63
    #> 3 0.24  Very Good J     VVS2     62.8    57   336  3.94  3.96  2.48
    #> 4 0.24  Very Good I     VVS1     62.3    57   336  3.95  3.98  2.47
    #> 5 0.26  Very Good H     SI1      61.9    55   337  4.07  4.11  2.53
    #> 6 0.22  Fair      E     VS2      65.1    61   337  3.87  3.78  2.49

Update: Thanks to user Petr Kajzar in this answer, here also an approach for the above:

diamonds %>%
   filter(rowSums(across(everything(), ~grepl("V", .x))) > 0)

In PHP, how can I add an object element to an array?

Here is a clean method I've discovered:

$myArray = [];

array_push($myArray, (object)[
        'key1' => 'someValue',
        'key2' => 'someValue2',
        'key3' => 'someValue3',
]);

return $myArray;

Doctrine2: Best way to handle many-to-many with extra columns in reference table

You may be able to achieve what you want with Class Table Inheritance where you change AlbumTrackReference to AlbumTrack:

class AlbumTrack extends Track { /* ... */ }

And getTrackList() would contain AlbumTrack objects which you could then use like you want:

foreach($album->getTrackList() as $albumTrack)
{
    echo sprintf("\t#%d - %-20s (%s) %s\n", 
        $albumTrack->getPosition(),
        $albumTrack->getTitle(),
        $albumTrack->getDuration()->format('H:i:s'),
        $albumTrack->isPromoted() ? ' - PROMOTED!' : ''
    );
}

You will need to examine this throughly to ensure you don't suffer performance-wise.

Your current set-up is simple, efficient, and easy to understand even if some of the semantics don't quite sit right with you.

What could cause java.lang.reflect.InvocationTargetException?

From the Javadoc of Method.invoke()

Throws: InvocationTargetException - if the underlying method throws an exception.

This exception is thrown if the method called threw an exception.

ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean

Case 1:

@SpringBootApplication annotation missing in your spring boot starter class.

Case 2:

For non web application, disable web application type in properties file:

In application.properties:

spring.main.web-application-type=none

If you use application.yml then add:

  spring:
    main:
      web-application-type: none

For web applications, extends *SpringBootServletInitializer* in main class.

@SpringBootApplication
public class YourAppliationName extends SpringBootServletInitializer{
    public static void main(String[] args) {
        SpringApplication.run(YourAppliationName.class, args);
    }
}

Case 3:

If you use spring-boot-starter-webflux then also add spring-boot-starter-web as dependency.

How do you make Vim unhighlight what you searched for?

Just put this in your .vimrc

" <Ctrl-l> redraws the screen and removes any search highlighting.
nnoremap <silent> <C-l> :nohl<CR><C-l>

Read input from a JOptionPane.showInputDialog box

Your problem is that, if the user clicks cancel, operationType is null and thus throws a NullPointerException. I would suggest that you move

if (operationType.equalsIgnoreCase("Q")) 

to the beginning of the group of if statements, and then change it to

if(operationType==null||operationType.equalsIgnoreCase("Q")). 

This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.

Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.

Fatal error: "No Target Architecture" in Visual Studio

Another reason for the error (amongst many others that cropped up when changing the target build of a Win32 project to X64) was not having the C++ 64 bit compilers installed as noted at the top of this page.
Further to philipvr's comment on child headers, (in my case) an explicit include of winnt.h being unnecessary when windows.h was being used.

How can I write variables inside the tasks file in ansible

Variable definitions are meant to be used in tasks. But if you want to include them in tasks probably use the register directive. Like this:

- name: Define variable in task.
  shell: echo "http://www.my.url.com"
  register: url

- name: Download apache
  shell: wget {{ item }}
  with_items: url.stdout

You can also look at roles as a way of separating tasks depending on the different roles roles. This way you can have separate variables for each of one of your roles. For example you may have a url variable for apache1 and a separate url variable for the role apache2.

Nested select statement in SQL Server

The answer provided by Joe Stefanelli is already correct.

SELECT name FROM (SELECT name FROM agentinformation) as a  

We need to make an alias of the subquery because a query needs a table object which we will get from making an alias for the subquery. Conceptually, the subquery results are substituted into the outer query. As we need a table object in the outer query, we need to make an alias of the inner query.

Statements that include a subquery usually take one of these forms:

  • WHERE expression [NOT] IN (subquery)
  • WHERE expression comparison_operator [ANY | ALL] (subquery)
  • WHERE [NOT] EXISTS (subquery)

Check for more subquery rules and subquery types.

More examples of Nested Subqueries.

  1. IN / NOT IN – This operator takes the output of the inner query after the inner query gets executed which can be zero or more values and sends it to the outer query. The outer query then fetches all the matching [IN operator] or non matching [NOT IN operator] rows.

  2. ANY – [>ANY or ANY operator takes the list of values produced by the inner query and fetches all the values which are greater than the minimum value of the list. The

e.g. >ANY(100,200,300), the ANY operator will fetch all the values greater than 100.

  1. ALL – [>ALL or ALL operator takes the list of values produced by the inner query and fetches all the values which are greater than the maximum of the list. The

e.g. >ALL(100,200,300), the ALL operator will fetch all the values greater than 300.

  1. EXISTS – The EXISTS keyword produces a Boolean value [TRUE/FALSE]. This EXISTS checks the existence of the rows returned by the sub query.

How to find what code is run by a button or element in Chrome using Developer Tools

This solution needs the jQuery's data method.

  1. Open Chrome's console (although any browser with jQuery loaded will work)
  2. Run $._data($(".example").get(0), "events")
  3. Drill down the output to find the desired event handler.
  4. Right-click on "handler" and select "Show function definition"
  5. The code will be shown in the Sources tab

$._data() is just accessing jQuery's data method. A more readable alternative could be jQuery._data().

Interesting point by this SO answer:

As of jQuery 1.8, the event data is no longer available from the "public API" for data. Read this jQuery blog post. You should now use this instead:

jQuery._data( elem, "events" ); elem should be an HTML Element, not a jQuery object, or selector.

Please note, that this is an internal, 'private' structure, and shouldn't be modified. Use this for debugging purposes only.

In older versions of jQuery, you might have to use the old method which is:

jQuery( elem ).data( "events" );

A version agnostic jQuery would be: (jQuery._data || jQuery.data)(elem, 'events');

Debugging Spring configuration

If you use Spring Boot, you can also enable a “debug” mode by starting your application with a --debug flag.

java -jar myapp.jar --debug

You can also specify debug=true in your application.properties.

When the debug mode is enabled, a selection of core loggers (embedded container, Hibernate, and Spring Boot) are configured to output more information. Enabling the debug mode does not configure your application to log all messages with DEBUG level.

Alternatively, you can enable a “trace” mode by starting your application with a --trace flag (or trace=true in your application.properties). Doing so enables trace logging for a selection of core loggers (embedded container, Hibernate schema generation, and the whole Spring portfolio).

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html

How to configure PostgreSQL to accept all incoming connections

Addition to above great answers, if you want some range of IPs to be authorized, you could edit /var/lib/pgsql/{VERSION}/data file and put something like

host all all 172.0.0.0/8 trust

It will accept incoming connections from any host of the above range. Source: http://www.linuxtopia.org/online_books/database_guides/Practical_PostgreSQL_database/c15679_002.htm

starting file download with JavaScript

Just call window.location.href = new_url from your javascript and it will redirect the browser to that URL as it the user had typed that into the address bar

JUnit Eclipse Plugin?

Junit is included by default with Eclipse (at least the Java EE version I'm sure). You may just need to add the view to your perspective.

org.hibernate.hql.internal.ast.QuerySyntaxException: table is not mapped

In my case: spring boot 2 ,multiple datasource(default and custom). entityManager.createQuery go wrong: 'entity is not mapped'

while debug, i find out that the entityManager's unitName is wrong(should be custom,but the fact is default) the right way:

@PersistenceContext(unitName = "customer1") // !important, 
private EntityManager em;

the customer1 is from the second datasource config class:

@Bean(name = "customer1EntityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder,
        @Qualifier("customer1DataSource") DataSource dataSource) {
    return builder.dataSource(dataSource).packages("com.xxx.customer1Datasource.model")
            .persistenceUnit("customer1")
            // PersistenceUnit injects an EntityManagerFactory, and PersistenceContext
            // injects an EntityManager.
            // It's generally better to use PersistenceContext unless you really need to
            // manage the EntityManager lifecycle manually.
            // ?4?
            .properties(jpaProperties.getHibernateProperties(new HibernateSettings())).build();
}

Then,the entityManager is right.

But, em.persist(entity) doesn't work,and the transaction doesn't work.

Another important point is:

@Transactional("customer1TransactionManager") // !important
public Trade findNewestByJdpModified() {
    //test persist,working right!
    Trade t = new Trade();
    em.persist(t);
    log.info("t.id" + t.getSysTradeId());

    //test transactional, working right!
    int a = 3/0;
}

customer1TransactionManager is from the second datasource config class:

@Bean(name = "customer1TransactionManager")
public PlatformTransactionManager transactionManager(
        @Qualifier("customer1EntityManagerFactory") EntityManagerFactory entityManagerFactory) {
    return new JpaTransactionManager(entityManagerFactory);
}

The whole second datasource config class is :

package com.lichendt.shops.sync;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "customer1EntityManagerFactory", transactionManagerRef = "customer1TransactionManager",
        // ?1??????DAO???? ,????DAO?? com.xx.DAO??,????? com.xx.DAO
        basePackages = { "com.lichendt.customer1Datasource.dao" })
public class Custom1DBConfig {

    @Autowired
    private JpaProperties jpaProperties;

    @Bean(name = "customer1DatasourceProperties")
    @Qualifier("customer1DatasourceProperties")
    @ConfigurationProperties(prefix = "customer1.datasource")
    public DataSourceProperties customer1DataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean(name = "customer1DataSource")
    @Qualifier("customer1DatasourceProperties")
    @ConfigurationProperties(prefix = "customer1.datasource") //
    // ?2?datasource?????,???? ?mysql?yaml???
    public DataSource dataSource() {
        // return DataSourceBuilder.create().build();
        return customer1DataSourceProperties().initializeDataSourceBuilder().build();
    }

    @Bean(name = "customer1EntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder,
            @Qualifier("customer1DataSource") DataSource dataSource) {
        return builder.dataSource(dataSource).packages("com.lichendt.customer1Datasource.model") // ?3???????????
                .persistenceUnit("customer1")
                // PersistenceUnit injects an EntityManagerFactory, and PersistenceContext
                // injects an EntityManager.
                // It's generally better to use PersistenceContext unless you really need to
                // manage the EntityManager lifecycle manually.
                // ?4?
                .properties(jpaProperties.getHibernateProperties(new HibernateSettings())).build();
    }

    @Bean(name = "customer1TransactionManager")
    public PlatformTransactionManager transactionManager(
            @Qualifier("customer1EntityManagerFactory") EntityManagerFactory entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory);
    }
}

No suitable driver found for 'jdbc:mysql://localhost:3306/mysql

When using Netbean, go under project tab and click the dropdown button there to select Libraries folder. Right Click on d Library folder and select 'Add JAR/Folder'. Locate the mysql-connectore-java.*.jar file where u have it on ur system. This worked for me and I hope it does for u too. Revert if u encounter any problem

Check div is hidden using jquery

Did you notice your typo, $car2 instead of #car2 ?

Anyway, :hidden seems to be working as expected, try it here.

How to calculate the number of occurrence of a given character in each row of a column of strings?

The stringi package provides the functions stri_count and stri_count_fixed which are very fast.

stringi::stri_count(q.data$string, fixed = "a")
# [1] 2 1 0

benchmark

Compared to the fastest approach from @42-'s answer and to the equivalent function from the stringr package for a vector with 30.000 elements.

library(microbenchmark)

benchmark <- microbenchmark(
  stringi = stringi::stri_count(test.data$string, fixed = "a"),
  baseR = nchar(test.data$string) - nchar(gsub("a", "", test.data$string, fixed = TRUE)),
  stringr = str_count(test.data$string, "a")
)

autoplot(benchmark)

data

q.data <- data.frame(number=1:3, string=c("greatgreat", "magic", "not"), stringsAsFactors = FALSE)
test.data <- q.data[rep(1:NROW(q.data), 10000),]

enter image description here

What is a difference between unsigned int and signed int in C?

Because it's all just about memory, in the end all the numerical values are stored in binary.

A 32 bit unsigned integer can contain values from all binary 0s to all binary 1s.

When it comes to 32 bit signed integer, it means one of its bits (most significant) is a flag, which marks the value to be positive or negative.

JavaScript Number Split into individual digits

A functional approach in order to get digits from a number would be to get a string from your number, split it into an array (of characters) and map each element back into a number.

For example:

var number = 123456;

var array = number.toString()
.split('')
.map(function(item, index) {
   return parseInt(item);
});

console.log(array); // returns [1, 2, 3, 4, 5, 6]

If you also need to sum all digits, you can append the reduce() method to the previous code:

var num = 123456;

var array = num.toString()
.split('')
.map(function(item, index) {
   return parseInt(item);
})
.reduce(function(previousValue, currentValue, index, array) {
  return previousValue + currentValue;
}, 0);

console.log(array); // returns 21

As an alternative, with ECMAScript 2015 (6th Edition), you can use arrow functions:

var number = 123456;
var array = number.toString().split('').map((item, index) => parseInt(item));
console.log(array); // returns [1, 2, 3, 4, 5, 6]

If you need to sum all digits, you can append the reduce() method to the previous code:

var num = 123456;

var result = num.toString()
.split('')
.map((item, index) => parseInt(item))
.reduce((previousValue, currentValue) => previousValue + currentValue, 0);

console.log(result); // returns 21

Is there a way to create and run javascript in Chrome?

You don't necessarily need to have an HTML page. Open Chrome, press Ctrl+Shift+j and it opens the JavaScript console where you can write and test your code.

- Chrome JavaScript Console

Why use argparse rather than optparse?

Why should I use it instead of optparse? Are their new features I should know about?

@Nicholas's answer covers this well, I think, but not the more "meta" question you start with:

Why has yet another command-line parsing module been created?

That's the dilemma number one when any useful module is added to the standard library: what do you do when a substantially better, but backwards-incompatible, way to provide the same kind of functionality emerges?

Either you stick with the old and admittedly surpassed way (typically when we're talking about complicated packages: asyncore vs twisted, tkinter vs wx or Qt, ...) or you end up with multiple incompatible ways to do the same thing (XML parsers, IMHO, are an even better example of this than command-line parsers -- but the email package vs the myriad old ways to deal with similar issues isn't too far away either;-).

You may make threatening grumbles in the docs about the old ways being "deprecated", but (as long as you need to keep backwards compatibility) you can't really take them away without stopping large, important applications from moving to newer Python releases.

(Dilemma number two, not directly related to your question, is summarized in the old saying "the standard library is where good packages go to die"... with releases every year and a half or so, packages that aren't very, very stable, not needing releases any more often than that, can actually suffer substantially by being "frozen" in the standard library... but, that's really a different issue).

Hunk #1 FAILED at 1. What's that mean?

In my case, the patch was generated perfectly fine by IDEA, however, I edited the patch and saved it which changed CRLF to LF and then the patch stopped working. Curiously, converting it back to CRLF did not work. I noticed in VI editor, that even after setting to DOS format, the '^M' were not added to the end of lines. This forced me to only make changes in VI, so that the EOLs were preserved.

This may apply to you, if you make changes in a non-Windows environment to a patch covering changes between two versions both coming from Windows environment. You want to be careful how you edit such files.

BTW ignore-whitespace did not help.

How do I discover memory usage of my application in Android?

Android Studio 0.8.10+ has introduced an incredibly useful tool called Memory Monitor.

enter image description here

What it's good for:

  • Showing available and used memory in a graph, and garbage collection events over time.
  • Quickly testing whether app slowness might be related to excessive garbage collection events.
  • Quickly testing whether app crashes may be related to running out of memory.

enter image description here

Figure 1. Forcing a GC (Garbage Collection) event on Android Memory Monitor

You can have plenty good information on your app's RAM real-time consumption by using it.

How to disable textbox from editing?

        textBox1.Enabled = false;

"false" property will make the text box disable. and "true" will make it in regular form. Thanks.

Where IN clause in LINQ

public List<State> GetcountryCodeStates(List<string> countryCodes)
{
    List<State> states = new List<State>();
    states = (from a in _objdatasources.StateList.AsEnumerable()
    where countryCodes.Any(c => c.Contains(a.CountryCode))
    select a).ToList();
    return states;
}

how to increase java heap memory permanently?

This worked for me:

export _JAVA_OPTIONS="-Xmx1g"

It's important that you have no spaces because for me it did not work. I would suggest just copying and pasting. Then I ran:

java -XshowSettings:vm

and it will tell you:

Picked up _JAVA_OPTIONS: -Xmx1g

Sublime Text 2: How to delete blank/empty lines

Don't even know how this whole thing works, but I tried ^\s*$ and didn't work (leaving still some empty lines).

This instead ^\s* works for me

{sublime text 3}

How can I convert String to Int?

//May be quite some time ago but I just want throw in some line for any one who may still need it

int intValue;
string strValue = "2021";

try
{
    intValue = Convert.ToInt32(strValue);
}
catch
{
    //Default Value if conversion fails OR return specified error
    // Example 
    intValue = 2000;
}

Should I check in folder "node_modules" to Git when creating a Node.js app on Heroku?

Explicitly adding a npm version to file package.json ("npm": "1.1.x") and not checking in folder node_modules to Git worked for me.

It may be slower to deploy (since it downloads the packages each time), but I couldn't get the packages to compile when they were checked in. Heroku was looking for files that only existed on my local box.

How to call same method for a list of objects?

This will work

all = [a1, b1, b2, a2,.....]

map(lambda x: x.start(),all)    

simple example

all = ["MILK","BREAD","EGGS"]
map(lambda x:x.lower(),all)
>>>['milk','bread','eggs']

and in python3

all = ["MILK","BREAD","EGGS"]
list(map(lambda x:x.lower(),all))
>>>['milk','bread','eggs']

Call int() function on every list element?

Another way to make it in Python 3:

numbers = [*map(int, numbers)]

Best practices for API versioning?

This is a good and a tricky question. The topic of URI design is at the same time the most prominent part of a REST API and, therefore, a potentially long-term commitment towards the users of that API.

Since evolution of an application and, to a lesser extent, its API is a fact of life and that it's even similar to the evolution of a seemingly complex product like a programming language, the URI design should have less natural constraints and it should be preserved over time. The longer the application's and API's lifespan, the greater the commitment to the users of the application and API.

On the other hand, another fact of life is that it is hard to foresee all the resources and their aspects that would be consumed through the API. Luckily, it is not necessary to design the entire API which will be used until Apocalypse. It is sufficient to correctly define all the resource end-points and the addressing scheme of every resource and resource instance.

Over time you may need to add new resources and new attributes to each particular resource, but the method that API users follow to access a particular resources should not change once a resource addressing scheme becomes public and therefore final.

This method applies to HTTP verb semantics (e.g. PUT should always update/replace) and HTTP status codes that are supported in earlier API versions (they should continue to work so that API clients that have worked without human intervention should be able to continue to work like that).

Furthermore, since embedding of API version into the URI would disrupt the concept of hypermedia as the engine of application state (stated in Roy T. Fieldings PhD dissertation) by having a resource address/URI that would change over time, I would conclude that API versions should not be kept in resource URIs for a long time meaning that resource URIs that API users can depend on should be permalinks.

Sure, it is possible to embed API version in base URI but only for reasonable and restricted uses like debugging a API client that works with the the new API version. Such versioned APIs should be time-limited and available to limited groups of API users (like during closed betas) only. Otherwise, you commit yourself where you shouldn't.

A couple of thoughts regarding maintenance of API versions that have expiration date on them. All programming platforms/languages commonly used to implement web services (Java, .NET, PHP, Perl, Rails, etc.) allow easy binding of web service end-point(s) to a base URI. This way it's easy to gather and keep a collection of files/classes/methods separate across different API versions.

From the API users POV, it's also easier to work with and bind to a particular API version when it's this obvious but only for limited time, i.e. during development.

From the API maintainer's POV, it's easier to maintain different API versions in parallel by using source control systems that predominantly work on files as the smallest unit of (source code) versioning.

However, with API versions clearly visible in URI there's a caveat: one might also object this approach since API history becomes visible/aparent in the URI design and therefore is prone to changes over time which goes against the guidelines of REST. I agree!

The way to go around this reasonable objection, is to implement the latest API version under versionless API base URI. In this case, API client developers can choose to either:

  • develop against the latest one (committing themselves to maintain the application protecting it from eventual API changes that might break their badly designed API client).

  • bind to a specific version of the API (which becomes apparent) but only for a limited time

For example, if API v3.0 is the latest API version, the following two should be aliases (i.e. behave identically to all API requests):

http://shonzilla/api/customers/1234
http://shonzilla/api/v3.0/customers/1234
http://shonzilla/api/v3/customers/1234

In addition, API clients that still try to point to the old API should be informed to use the latest previous API version, if the API version they're using is obsolete or not supported anymore. So accessing any of the obsolete URIs like these:

http://shonzilla/api/v2.2/customers/1234
http://shonzilla/api/v2.0/customers/1234
http://shonzilla/api/v2/customers/1234
http://shonzilla/api/v1.1/customers/1234
http://shonzilla/api/v1/customers/1234

should return any of the 30x HTTP status codes that indicate redirection that are used in conjunction with Location HTTP header that redirects to the appropriate version of resource URI which remain to be this one:

http://shonzilla/api/customers/1234

There are at least two redirection HTTP status codes that are appropriate for API versioning scenarios:

  • 301 Moved permanently indicating that the resource with a requested URI is moved permanently to another URI (which should be a resource instance permalink that does not contain API version info). This status code can be used to indicate an obsolete/unsupported API version, informing API client that a versioned resource URI been replaced by a resource permalink.

  • 302 Found indicating that the requested resource temporarily is located at another location, while requested URI may still supported. This status code may be useful when the version-less URIs are temporarily unavailable and that a request should be repeated using the redirection address (e.g. pointing to the URI with APi version embedded) and we want to tell clients to keep using it (i.e. the permalinks).

  • other scenarios can be found in Redirection 3xx chapter of HTTP 1.1 specification

Is there any way to do HTTP PUT in python

You can use requests.request

import requests

url = "https://www.example/com/some/url/"
payload="{\"param1\": 1, \"param1\": 2}"
headers = {
  'Authorization': '....',
  'Content-Type': 'application/json'
}

response = requests.request("PUT", url, headers=headers, data=payload)

print(response.text)

Source file 'Properties\AssemblyInfo.cs' could not be found

I got the error using TFS, my AssemblyInfo wasn't mapped in the branch I was working on.

ASP.NET MVC 5 - Identity. How to get current ApplicationUser

ApplicationDbContext context = new ApplicationDbContext();
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
ApplicationUser currentUser = UserManager.FindById(User.Identity.GetUserId());

string ID = currentUser.Id;
string Email = currentUser.Email;
string Username = currentUser.UserName;

Using (Ana)conda within PyCharm

as per @cyberbikepunk answer pycharm supports Anaconda since pycharm5!

Have a look how easy is to add an environment: enter image description here

Node.js - Maximum call stack size exceeded

I had a similar issue as this. I had an issue with using multiple Array.map()'s in a row (around 8 maps at once) and was getting a maximum_call_stack_exceeded error. I solved this by changing the map's into 'for' loops

So if you are using alot of map calls, changing them to for loops may fix the problem

Edit

Just for clarity and probably-not-needed-but-good-to-know-info, using .map() causes the array to be prepped (resolving getters , etc) and the callback to be cached, and also internally keeps an index of the array (so the callback is provided with the correct index/value). This stacks with each nested call, and caution is advised when not nested as well, as the next .map() could be called before the first array is garbage collected (if at all).

Take this example:

var cb = *some callback function*
var arr1 , arr2 , arr3 = [*some large data set]
arr1.map(v => {
    *do something
})
cb(arr1)
arr2.map(v => {
    *do something // even though v is overwritten, and the first array
                  // has been passed through, it is still in memory
                  // because of the cached calls to the callback function
}) 

If we change this to:

for(var|let|const v in|of arr1) {
    *do something
}
cb(arr1)
for(var|let|const v in|of arr2) {
    *do something  // Here there is not callback function to 
                   // store a reference for, and the array has 
                   // already been passed of (gone out of scope)
                   // so the garbage collector has an opportunity
                   // to remove the array if it runs low on memory
}

I hope this makes some sense (I don't have the best way with words) and helps a few to prevent the head scratching I went through

If anyone is interested, here is also a performance test comparing map and for loops (not my work).

https://github.com/dg92/Performance-Analysis-JS

For loops are usually better than map, but not reduce, filter, or find

How do I set the timeout for a JAX-WS webservice client?

ProxyWs proxy = (ProxyWs) factory.create();
Client client = ClientProxy.getClient(proxy);
HTTPConduit http = (HTTPConduit) client.getConduit();
HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
httpClientPolicy.setConnectionTimeout(0);
httpClientPolicy.setReceiveTimeout(0);
http.setClient(httpClientPolicy);

This worked for me.

Monitoring the Full Disclosure mailinglist

Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.

You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.

But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.

You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.

HTTPS using Jersey Client

HTTPS using Jersey client has two different version if you are using java 6 ,7 and 8 then

SSLContext sc = SSLContext.getInstance("SSL");

If using java 8 then

SSLContext sc = SSLContext.getInstance("TLSv1");
System.setProperty("https.protocols", "TLSv1");

Please find working code

POM

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>WebserviceJersey2Spring</groupId>
    <artifactId>WebserviceJersey2Spring</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <properties>
        <jersey.version>2.16</jersey.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <repositories>
        <repository>
            <id>maven2-repository.java.net</id>
            <name>Java.net Repository for Maven</name>
            <url>http://download.java.net/maven/2/</url>
        </repository>
    </repositories>

    <dependencyManagement>

        <dependencies>
            <dependency>
                <groupId>org.glassfish.jersey</groupId>
                <artifactId>jersey-bom</artifactId>
                <version>${jersey.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>

        <!-- Jersey -->
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet-core</artifactId>

        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-moxy</artifactId>

        </dependency>

        <!-- Spring 3 dependencies -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>3.0.5.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>3.0.5.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>3.0.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-client</artifactId>
            </dependency>



        <!-- Jersey + Spring -->
        <dependency>
            <groupId>org.glassfish.jersey.ext</groupId>
            <artifactId>jersey-spring3</artifactId>
            <exclusions>
                <exclusion>
                    <artifactId>spring-context</artifactId>
                    <groupId>org.springframework</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>spring-beans</artifactId>
                    <groupId>org.springframework</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>spring-core</artifactId>
                    <groupId>org.springframework</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>spring-web</artifactId>
                    <groupId>org.springframework</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>jersey-server</artifactId>
                    <groupId>org.glassfish.jersey.core</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>
                    jersey-container-servlet-core
                </artifactId>
                    <groupId>org.glassfish.jersey.containers</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>hk2</artifactId>
                    <groupId>org.glassfish.hk2</groupId>
                </exclusion>
            </exclusions>
        </dependency>

    </dependencies>
    <build>
        <sourceDirectory>src</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <warSourceDirectory>WebContent</warSourceDirectory>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

JAVA CLASS

package com.example.client;




import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
import org.springframework.http.HttpStatus;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;

public class JerseyClientGet {
    public static void main(String[] args) {
        String username = "username";
            String password = "p@ssword";
        String input = "{\"userId\":\"12345\",\"name \":\"Viquar\",\"surname\":\"Khan\",\"Email\":\"[email protected]\"}";
        try {
        //SSLContext sc = SSLContext.getInstance("SSL");//Java 6
        SSLContext sc = SSLContext.getInstance("TLSv1");//Java 8
        System.setProperty("https.protocols", "TLSv1");//Java 8


        TrustManager[] trustAllCerts = { new InsecureTrustManager() };
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HostnameVerifier allHostsValid = new InsecureHostnameVerifier();

        Client client = ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier(allHostsValid).build();

        HttpAuthenticationFeature feature = HttpAuthenticationFeature.universalBuilder()
                    .credentialsForBasic(username, password).credentials(username, password).build();


            client.register(feature);
                    //PUT request, if need uncomment it 
                    //final Response response = client
                    //.target("https://localhost:7002/VaquarKhanWeb/employee/api/v1/informations")
                    //.request().put(Entity.entity(input, MediaType.APPLICATION_JSON), Response.class);
            //GET Request
            final Response response = client
                    .target("https://localhost:7002/VaquarKhanWeb/employee/api/v1/informations")
                    .request().get();




            if (response.getStatus() != HttpStatus.OK.value()) { throw new RuntimeException("Failed : HTTP error code : "
                    + response.getStatus()); }
            String output = response.readEntity(String.class);
            System.out.println("Output from Server .... \n");
            System.out.println(output);
            client.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

HELPER CLASS

package com.example.client;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

public class InsecureHostnameVerifier implements HostnameVerifier {
    @Override
    public boolean verify(String hostname, SSLSession session) {
        return true;
    }
}

Helper class

package com.example.client;

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;

public class InsecureTrustManager implements X509TrustManager {
    /**
     * {@inheritDoc}
     */
    @Override
    public void checkClientTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {
        // Everyone is trusted!
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void checkServerTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {
        // Everyone is trusted!
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return new X509Certificate[0];
    }
}

Once you start running application will get Certificate error ,download certificate from browser and add into

C:\java-8\jdk1_8_0\jre\lib\security

Add into cacerts , you will get details in following links.

Few useful link to understand error

I have tested following code for get and post method with SSL and basic Authentication here you can skip SSL Certificate , you can directly copy three class and add jar into java project and run.

package com.rest.client;
import java.io.IOException;
import java.net.*;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
import org.glassfish.jersey.filter.LoggingFilter;
import com.rest.dto.EarUnearmarkCollateralInput;

public class RestClientTest {
    /**
     * @param args
     */
    public static void main(String[] args) {
        try {
            //
            sslRestClientGETReport();
            //
            sslRestClientPostEarmark();
            //
            sslRestClientGETRankColl();
            //
        } catch (KeyManagementException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (NoSuchAlgorithmException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }

    //
    private static WebTarget    target      = null;
    private static String       userName    = "username";
    private static String       passWord    = "password";

    //
    public static void sslRestClientGETReport() throws KeyManagementException, IOException, NoSuchAlgorithmException {
        //
        //
        SSLContext sc = SSLContext.getInstance("SSL");
        TrustManager[] trustAllCerts = { new InsecureTrustManager() };
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HostnameVerifier allHostsValid = new InsecureHostnameVerifier();
        //
        Client c = ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier(allHostsValid).build();
        //
        String baseUrl = "https://localhost:7002/VaquarKhanWeb/employee/api/v1/informations/report";
        c.register(HttpAuthenticationFeature.basic(userName, passWord));
        target = c.target(baseUrl);
        target.register(new LoggingFilter());
        String responseMsg = target.request().get(String.class);
        System.out.println("-------------------------------------------------------");
        System.out.println(responseMsg);
        System.out.println("-------------------------------------------------------");
        //

    }

    public static void sslRestClientGET() throws KeyManagementException, IOException, NoSuchAlgorithmException {
        //Query param Search={JSON}
        //
        SSLContext sc = SSLContext.getInstance("SSL");
        TrustManager[] trustAllCerts = { new InsecureTrustManager() };
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HostnameVerifier allHostsValid = new InsecureHostnameVerifier();
        //
        Client c = ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier(allHostsValid).build();
        //
        String baseUrl = "https://localhost:7002/VaquarKhanWeb";

        //
        c.register(HttpAuthenticationFeature.basic(userName, passWord));
        target = c.target(baseUrl);
        target = target.path("employee/api/v1/informations/employee/data").queryParam("search","%7B\"name\":\"vaquar\",\"surname\":\"khan\",\"age\":\"30\",\"type\":\"admin\""%7D");

        target.register(new LoggingFilter());
        String responseMsg = target.request().get(String.class);
        System.out.println("-------------------------------------------------------");
        System.out.println(responseMsg);
        System.out.println("-------------------------------------------------------");
        //

    }
    //TOD need to fix
    public static void sslRestClientPost() throws KeyManagementException, IOException, NoSuchAlgorithmException {
        //
        //
        Employee employee = new Employee("vaquar", "khan", "30", "E");
        //
        SSLContext sc = SSLContext.getInstance("SSL");
        TrustManager[] trustAllCerts = { new InsecureTrustManager() };
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HostnameVerifier allHostsValid = new InsecureHostnameVerifier();
        //
        Client c = ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier(allHostsValid).build();
        //
        String baseUrl = "https://localhost:7002/VaquarKhanWeb/employee/api/v1/informations/employee";
        c.register(HttpAuthenticationFeature.basic(userName, passWord));
        target = c.target(baseUrl);
        target.register(new LoggingFilter());
        //
        Response response = target.request().put(Entity.json(employee));
        String output = response.readEntity(String.class);
        //
        System.out.println("-------------------------------------------------------");
        System.out.println(output);
        System.out.println("-------------------------------------------------------");

    }


}

Jars

repository/javax/ws/rs/javax.ws.rs-api/2.0/javax.ws.rs-api-2.0.jar"
    repository/org/glassfish/jersey/core/jersey-client/2.6/jersey-client-2.6.jar"
    repository/org/glassfish/jersey/core/jersey-common/2.6/jersey-common-2.6.jar"
    repository/org/glassfish/hk2/hk2-api/2.2.0/hk2-api-2.2.0.jar"
    repository/org/glassfish/jersey/bundles/repackaged/jersey-guava/2.6/jersey-guava-2.6.jar"
    repository/org/glassfish/hk2/hk2-locator/2.2.0/hk2-locator-2.2.0.jar"
    repository/org/glassfish/hk2/hk2-utils/2.2.0/hk2-utils-2.2.0.jar"
    repository/org/javassist/javassist/3.15.0-GA/javassist-3.15.0-GA.jar"
    repository/org/glassfish/hk2/external/javax.inject/2.2.0/javax.inject-2.2.0.jar"
    repository/javax/annotation/javax.annotation-api/1.2/javax.annotation-api-1.2.jar"
    genson-1.3.jar"

I can’t find the Android keytool

One thing that wasn't mentioned here (but kept me from running keytool altogether) was that you need to run the Command Prompt as Administrator.

Just wanted to share it...

How to call javascript from a href?

<a onClick="yourFunction(); return false;" href="fallback.html">One Way</a>

** Edit **
From the flurry of comments, I'm sharing the resources given/found.

Previous SO Q and A's:

Interesting reads:

Is it possible to create a 'link to a folder' in a SharePoint document library?

i couldn't change the permissions on the sharepoint i'm using but got a round it by uploading .url files with the drag and drop multiple files uploader.

Using the normal upload didn't work because they are intepreted by the file open dialog when you try to open them singly so it just tries to open the target not the .url file.

.url files can be made by saving a favourite with internet exploiter.

Aligning two divs side-by-side

The HTML code is for three div align side by side and can be used for two also by some changes

<div id="wrapper">
  <div id="first">first</div>
  <div id="second">second</div>
  <div id="third">third</div>
</div>

The CSS will be

#wrapper {
  display:table;
  width:100%;
}
#row {
  display:table-row;
}
#first {
  display:table-cell;
  background-color:red;
  width:33%;
}
#second {
  display:table-cell;
  background-color:blue;
  width:33%;
}
#third {
  display:table-cell;
  background-color:#bada55;
  width:34%;
}

This code will workup towards responsive layout as it will resize the

<div> 

according to device width. Even one can silent anyone

<div>

as

<!--<div id="third">third</div> --> 

and can use rest two for two

<div> 

side by side.

show validation error messages on submit in angularjs

You only need to check if the form is dirty and valid before submitting it. Checkout the following code.

<form name="frmRegister" data-ng-submit="frmRegister.$valid && frmRegister.$dirty ? register() : return false;" novalidate>      

And also you can disable your submit button with the following change:

<input type="submit" value="Save" data-ng-disable="frmRegister.$invalid || !frmRegister.$dirty" />

This should help for your initial

VSCode: How to Split Editor Vertically

By default, editor groups are laid out in vertical columns (e.g. when you split an editor to open it to the side). You can easily arrange editor groups in any layout you like, both vertically and horizontally:

To support flexible layouts, you can create empty editor groups. By default, closing the last editor of an editor group will also close the group itself, but you can change this behavior with the new setting workbench.editor.closeEmptyGroups: false:

enter image description here

There are a predefined set of editor layouts in the new View > Editor Layout menu:

enter image description here

Editors that open to the side (for example by clicking the editor toolbar Split Editor action) will by default open to the right hand side of the active editor. If you prefer to open editors below the active one, configure the new setting workbench.editor.openSideBySideDirection: down.

There are many keyboard commands for adjusting the editor layout with the keyboard alone, but if you prefer to use the mouse, drag and drop is a fast way to split the editor into any direction:

enter image description here

Keyboard shortcuts# Here are some handy keyboard shortcuts to quickly navigate between editors and editor groups.

If you'd like to modify the default keyboard shortcuts, see Key Bindings for details.

??? go to the right editor.
??? go to the left editor.
^Tab open the next editor in the editor group MRU list.
^?Tab open the previous editor in the editor group MRU list.
?1 go to the leftmost editor group.
?2 go to the center editor group.
?3 go to the rightmost editor group.
unassigned go to the previous editor group.
unassigned go to the next editor group.
?W close the active editor.
?K W close all editors in the editor group.
?K ?W close all editors.

REST API using POST instead of GET

Think about it. When your client makes a GET request to an URI X, what it's saying to the server is: "I want a representation of the resource located at X, and this operation shouldn't change anything on the server." A PUT request is saying: "I want you to replace whatever is the resource located at X with the new entity I'm giving you on the body of this request". A DELETE request is saying: "I want you to delete whatever is the resource located at X". A PATCH is saying "I'm giving you this diff, and you should try to apply it to the resource at X and tell me if it succeeds." But a POST is saying: "I'm sending you this data subordinated to the resource at X, and we have a previous agreement on what you should do with it."

If you don't have it documented somewhere that the resource expects a POST and does something with it, it doesn't make sense to send a POST to it expecting it to act like a GET.

REST relies on the standardized behavior of the underlying protocol, and POST is precisely the method used for an action that isn't standardized. The result of a GET, PUT and DELETE requests are clearly defined in the standard, but POST isn't. The result of a POST is subordinated to the server, so if it's not documented that you can use POST to do something, you have to assume that you can't.

Method Call Chaining; returning a pointer vs a reference?

Very interesting question.

I don't see any difference w.r.t safety or versatility, since you can do the same thing with pointer or reference. I also don't think there is any visible difference in performance since references are implemented by pointers.

But I think using reference is better because it is consistent with the standard library. For example, chaining in iostream is done by reference rather than pointer.

Different ways of loading a file as an InputStream

There are subtle differences as to how the fileName you are passing is interpreted. Basically, you have 2 different methods: ClassLoader.getResourceAsStream() and Class.getResourceAsStream(). These two methods will locate the resource differently.

In Class.getResourceAsStream(path), the path is interpreted as a path local to the package of the class you are calling it from. For example calling, String.class.getResourceAsStream("myfile.txt") will look for a file in your classpath at the following location: "java/lang/myfile.txt". If your path starts with a /, then it will be considered an absolute path, and will start searching from the root of the classpath. So calling String.class.getResourceAsStream("/myfile.txt") will look at the following location in your class path ./myfile.txt.

ClassLoader.getResourceAsStream(path) will consider all paths to be absolute paths. So calling String.class.getClassLoader().getResourceAsStream("myfile.txt") and String.class.getClassLoader().getResourceAsStream("/myfile.txt") will both look for a file in your classpath at the following location: ./myfile.txt.

Everytime I mention a location in this post, it could be a location in your filesystem itself, or inside the corresponding jar file, depending on the Class and/or ClassLoader you are loading the resource from.

In your case, you are loading the class from an Application Server, so your should use Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName) instead of this.getClass().getClassLoader().getResourceAsStream(fileName). this.getClass().getResourceAsStream() will also work.

Read this article for more detailed information about that particular problem.


Warning for users of Tomcat 7 and below

One of the answers to this question states that my explanation seems to be incorrect for Tomcat 7. I've tried to look around to see why that would be the case.

So I've looked at the source code of Tomcat's WebAppClassLoader for several versions of Tomcat. The implementation of findResource(String name) (which is utimately responsible for producing the URL to the requested resource) is virtually identical in Tomcat 6 and Tomcat 7, but is different in Tomcat 8.

In versions 6 and 7, the implementation does not attempt to normalize the resource name. This means that in these versions, classLoader.getResourceAsStream("/resource.txt") may not produce the same result as classLoader.getResourceAsStream("resource.txt") event though it should (since that what the Javadoc specifies). [source code]

In version 8 though, the resource name is normalized to guarantee that the absolute version of the resource name is the one that is used. Therefore, in Tomcat 8, the two calls described above should always return the same result. [source code]

As a result, you have to be extra careful when using ClassLoader.getResourceAsStream() or Class.getResourceAsStream() on Tomcat versions earlier than 8. And you must also keep in mind that class.getResourceAsStream("/resource.txt") actually calls classLoader.getResourceAsStream("resource.txt") (the leading / is stripped).

How to print HTML content on click of a button, but not the page?

I Want See This

Example http://jsfiddle.net/35vAN/

    <html>
<head>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.1.min.js" > </script> 
<script type="text/javascript">

    function PrintElem(elem)
    {
        Popup($(elem).html());
    }

    function Popup(data) 
    {
        var mywindow = window.open('', 'my div', 'height=400,width=600');
        mywindow.document.write('<html><head><title>my div</title>');
        /*optional stylesheet*/ //mywindow.document.write('<link rel="stylesheet" href="main.css" type="text/css" />');
        mywindow.document.write('</head><body >');
        mywindow.document.write(data);
        mywindow.document.write('</body></html>');

        mywindow.print();
        mywindow.close();

        return true;
    }

</script>
</head>
<body>

<div id="mydiv">
    This will be printed. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque a quam at nibh adipiscing interdum. Nulla vitae accumsan ante. 
</div>

<div>
    This will not be printed.
</div>

<div id="anotherdiv">
    Nor will this.
</div>

<input type="button" value="Print Div" onclick="PrintElem('#mydiv')" />

</body>

</html>

What's the best way to get the last element of an array without deleting it?

my simple solution, pretty and easy to understand.

array_reverse($array)[0];

any tool for java object to object mapping?

I suggest you try JMapper Framework.

It is a Java bean to Java bean mapper, allows you to perform the passage of data dynamically with annotations and / or XML.

With JMapper you can:

  • Create and enrich target objects
  • Apply a specific logic to the mapping
  • Automatically manage the XML file
  • Implement the 1 to N and N to 1 relationships
  • Implement explicit conversions
  • Apply inherited configurations

How to iterate through XML in Powershell?

You can also do it without the [xml] cast. (Although xpath is a world unto itself. https://www.w3schools.com/xml/xml_xpath.asp)

$xml = (select-xml -xpath / -path stack.xml).node
$xml.objects.object.property

Or just this, xpath is case sensitive. Both have the same output:

$xml = (select-xml -xpath /Objects/Object/Property -path stack.xml).node
$xml


Name         Type                                                #text
----         ----                                                -----
DisplayName  System.String                                       SQL Server (MSSQLSERVER)
ServiceState Microsoft.SqlServer.Management.Smo.Wmi.ServiceState Running
DisplayName  System.String                                       SQL Server Agent (MSSQLSERVER)
ServiceState Microsoft.SqlServer.Management.Smo.Wmi.ServiceState Stopped

Can I call jQuery's click() to follow an <a> link if I haven't bound an event handler to it with bind or click already?

Interesting, this is probably a "feature request" (ie bug) for jQuery. The jQuery click event only triggers the click action (called onClick event on the DOM) on the element if you bind a jQuery event to the element. You should go to jQuery mailing lists ( http://forum.jquery.com/ ) and report this. This might be the wanted behavior, but I don't think so.

EDIT:

I did some testing and what you said is wrong, even if you bind a function to an 'a' tag it still doesn't take you to the website specified by the href attribute. Try the following code:

<html>
<head>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
 <script>
  $(document).ready(function() {
   /* Try to dis-comment this:
   $('#a').click(function () {
    alert('jQuery.click()');
    return true;
   });
   */
  });
  function button_onClick() {
   $('#a').click();
  }
  function a_onClick() {
   alert('a_onClick');
  }
 </script>

</head>
<body>
 <input type="button" onclick="button_onClick()">
 <br>
 <a id='a' href='http://www.google.com' onClick="a_onClick()"> aaa </a>

</body>
</html> 

It never goes to google.com unless you directly click on the link (with or without the commented code). Also notice that even if you bind the click event to the link it still doesn't go purple once you click the button. It only goes purple if you click the link directly.

I did some research and it seems that the .click is not suppose to work with 'a' tags because the browser does not suport "fake clicking" with javascript. I mean, you can't "click" an element with javascript. With 'a' tags you can trigger its onClick event but the link won't change colors (to the visited link color, the default is purple in most browsers). So it wouldn't make sense to make the $().click event work with 'a' tags since the act of going to the href attribute is not a part of the onClick event, but hardcoded in the browser.

How to convert CSV file to multiline JSON?

As slight improvement to @MONTYHS answer, iterating through a tup of fieldnames:

import csv
import json

csvfilename = 'filename.csv'
jsonfilename = csvfilename.split('.')[0] + '.json'
csvfile = open(csvfilename, 'r')
jsonfile = open(jsonfilename, 'w')
reader = csv.DictReader(csvfile)

fieldnames = ('FirstName', 'LastName', 'IDNumber', 'Message')

output = []

for each in reader:
  row = {}
  for field in fieldnames:
    row[field] = each[field]
output.append(row)

json.dump(output, jsonfile, indent=2, sort_keys=True)

How do I resolve ClassNotFoundException?

I ran into this as well and tried all of the other solutions. I did not have the .class file in my HTML folder, I only had the .java file. Once I added the .class file the program worked fine.

The remote server returned an error: (407) Proxy Authentication Required

I had a similar proxy related problem. In my case it was enough to add:

webRequest.Proxy.Credentials = new NetworkCredential("user", "password", "domain");

parsing a tab-separated file in Python

I don't think any of the current answers really do what you said you want. (Correction: I now see that @Gareth Latty / @Lattyware has incorporated my answer into his own as an "Edit" near the end.)

Anyway, here's my take:

Say these are the tab-separated values in your input file:

1   2   3   4   5
6   7   8   9   10
11  12  13  14  15
16  17  18  19  20

then this:

with open("tab-separated-values.txt") as inp:
    print( list(zip(*(line.strip().split('\t') for line in inp))) )

would produce the following:

[('1', '6', '11', '16'), 
 ('2', '7', '12', '17'), 
 ('3', '8', '13', '18'), 
 ('4', '9', '14', '19'), 
 ('5', '10', '15', '20')]

As you can see, it put the k-th element of each row into the k-th array.

Determine device (iPhone, iPod Touch) with iOS

Update platform string.

// Created from this thread: https://gist.github.com/Jaybles/1323251

// Apple TV
if ([platform isEqualToString:@"AppleTV2,1"])   return @"Apple TV 2G";
if ([platform isEqualToString:@"AppleTV3,1"])   return @"Apple TV 3G";
if ([platform isEqualToString:@"AppleTV3,2"])   return @"Apple TV 3G";
if ([platform isEqualToString:@"AppleTV5,3"])   return @"Apple TV 4G";

// Apple Watch
if ([platform isEqualToString:@"Watch1,1"])     return @"Apple Watch";
if ([platform isEqualToString:@"Watch1,2"])     return @"Apple Watch";

// iPhone
if ([platform isEqualToString:@"iPhone1,1"])    return @"iPhone 2G";
if ([platform isEqualToString:@"iPhone1,2"])    return @"iPhone 3G";
if ([platform isEqualToString:@"iPhone2,1"])    return @"iPhone 3GS";
if ([platform isEqualToString:@"iPhone3,1"])    return @"iPhone 4 (GSM)";
if ([platform isEqualToString:@"iPhone3,2"])    return @"iPhone 4 (GSM/2012)";
if ([platform isEqualToString:@"iPhone3,3"])    return @"iPhone 4 (CDMA)";
if ([platform isEqualToString:@"iPhone4,1"])    return @"iPhone 4S";
if ([platform isEqualToString:@"iPhone5,1"])    return @"iPhone 5 (GSM)";
if ([platform isEqualToString:@"iPhone5,2"])    return @"iPhone 5 (Global)";
if ([platform isEqualToString:@"iPhone5,3"])    return @"iPhone 5c (GSM)";
if ([platform isEqualToString:@"iPhone5,4"])    return @"iPhone 5c (Global)";
if ([platform isEqualToString:@"iPhone6,1"])    return @"iPhone 5s (GSM)";
if ([platform isEqualToString:@"iPhone6,2"])    return @"iPhone 5s (Global)";
if ([platform isEqualToString:@"iPhone7,2"])    return @"iPhone 6";
if ([platform isEqualToString:@"iPhone7,1"])    return @"iPhone 6 Plus";
if ([platform isEqualToString:@"iPhone8,1"])    return @"iPhone 6s";
if ([platform isEqualToString:@"iPhone8,2"])    return @"iPhone 6s Plus";
if ([platform isEqualToString:@"iPhone8,4"])    return @"iPhone SE";
if ([platform isEqualToString:@"iPhone9,1"])    return @"iPhone 7 (Global)";
if ([platform isEqualToString:@"iPhone9,3"])    return @"iPhone 7 (GSM)";
if ([platform isEqualToString:@"iPhone9,2"])    return @"iPhone 7 Plus (Global)";
if ([platform isEqualToString:@"iPhone9,4"])    return @"iPhone 7 Plus (GSM)";

// iPad
if ([platform isEqualToString:@"iPad1,1"])      return @"iPad 1";
if ([platform isEqualToString:@"iPad2,1"])      return @"iPad 2 (WiFi)";
if ([platform isEqualToString:@"iPad2,2"])      return @"iPad 2 (GSM)";
if ([platform isEqualToString:@"iPad2,3"])      return @"iPad 2 (CDMA)";
if ([platform isEqualToString:@"iPad2,4"])      return @"iPad 2 (Mid 2012)";
if ([platform isEqualToString:@"iPad3,1"])      return @"iPad 3 (WiFi)";
if ([platform isEqualToString:@"iPad3,2"])      return @"iPad 3 (CDMA)";
if ([platform isEqualToString:@"iPad3,3"])      return @"iPad 3 (GSM)";
if ([platform isEqualToString:@"iPad3,4"])      return @"iPad 4 (WiFi)";
if ([platform isEqualToString:@"iPad3,5"])      return @"iPad 4 (GSM)";
if ([platform isEqualToString:@"iPad3,6"])      return @"iPad 4 (Global)";

// iPad Air
if ([platform isEqualToString:@"iPad4,1"])      return @"iPad Air (WiFi)";
if ([platform isEqualToString:@"iPad4,2"])      return @"iPad Air (Cellular)";
if ([platform isEqualToString:@"iPad4,3"])      return @"iPad Air (China)";
if ([platform isEqualToString:@"iPad5,3"])      return @"iPad Air 2 (WiFi)";
if ([platform isEqualToString:@"iPad5,4"])      return @"iPad Air 2 (Cellular)";

// iPad Mini
if ([platform isEqualToString:@"iPad2,5"])      return @"iPad Mini (WiFi)";
if ([platform isEqualToString:@"iPad2,6"])      return @"iPad Mini (GSM)";
if ([platform isEqualToString:@"iPad2,7"])      return @"iPad Mini (Global)";
if ([platform isEqualToString:@"iPad4,4"])      return @"iPad Mini 2 (WiFi)";
if ([platform isEqualToString:@"iPad4,5"])      return @"iPad Mini 2 (Cellular)";
if ([platform isEqualToString:@"iPad4,6"])      return @"iPad Mini 2 (China)";
if ([platform isEqualToString:@"iPad4,7"])      return @"iPad Mini 3 (WiFi)";
if ([platform isEqualToString:@"iPad4,8"])      return @"iPad Mini 3 (Cellular)";
if ([platform isEqualToString:@"iPad4,9"])      return @"iPad Mini 3 (China)";
if ([platform isEqualToString:@"iPad5,1"])      return @"iPad Mini 4 (WiFi)";
if ([platform isEqualToString:@"iPad5,2"])      return @"iPad Mini 4 (Cellular)";

// iPad Pro
if ([platform isEqualToString:@"iPad6,3"])      return @"iPad Pro (9.7 inch/WiFi)";
if ([platform isEqualToString:@"iPad6,4"])      return @"iPad Pro (9.7 inch/Cellular)";
if ([platform isEqualToString:@"iPad6,7"])      return @"iPad Pro (12.9 inch/WiFi)";
if ([platform isEqualToString:@"iPad6,8"])      return @"iPad Pro (12.9 inch/Cellular)";

// iPod
if ([platform isEqualToString:@"iPod1,1"])      return @"iPod Touch 1G";
if ([platform isEqualToString:@"iPod2,1"])      return @"iPod Touch 2G";
if ([platform isEqualToString:@"iPod3,1"])      return @"iPod Touch 3G";
if ([platform isEqualToString:@"iPod4,1"])      return @"iPod Touch 4G";
if ([platform isEqualToString:@"iPod5,1"])      return @"iPod Touch 5G";
if ([platform isEqualToString:@"iPod7,1"])      return @"iPod Touch 6G";

// Simulator
if ([platform isEqualToString:@"i386"])         return @"Simulator";
if ([platform isEqualToString:@"x86_64"])       return @"Simulator";

Constants in Kotlin -- what's a recommended way to create them?

In Kotlin, if you want to create the local constants which are supposed to be used with in the class then you can create it like below

val MY_CONSTANT = "Constants"

And if you want to create a public constant in kotlin like public static final in java, you can create it as follow.

companion object{

     const val MY_CONSTANT = "Constants"

}

Function for Factorial in Python

If you are using Python2.5 or older try

from operator import mul
def factorial(n):
    return reduce(mul, range(1,n+1))

for newer Python, there is factorial in the math module as given in other answers here

How to execute only one test spec with angular-cli

You can test only specific file with the Angular CLI (the ng command) like this:

ng test --main ./path/to/test.ts

Further docs are at https://angular.io/cli/test

Note that while this works for standalone library files, it will not work for angular components/services/etc. This is because angular files have dependencies on other files (namely src/test.ts in Angular 7). Sadly the --main flag doesn't take multiple arguments.

How to delete a record by id in Flask-SQLAlchemy

Another possible solution specially if you want batch delete

deleted_objects = User.__table__.delete().where(User.id.in_([1, 2, 3]))
session.execute(deleted_objects)
session.commit()

Show a leading zero if a number is less than 10

Try this

function pad (str, max) {
  return str.length < max ? pad("0" + str, max) : str;
}

alert(pad("5", 2));

Example

http://jsfiddle.net/

Or

var number = 5;
var i;
if (number < 10) {
    alert("0"+number);
}

Example

http://jsfiddle.net/

Install Chrome extension form outside the Chrome Web Store

For regular Windows users who are not skilled with computers, it is practically not possible to install and use extensions from outside the Chrome Web Store.

Users of other operating systems (Linux, Mac, Chrome OS) can easily install unpacked extensions (in developer mode).
Windows users can also load an unpacked extension, but they will always see an information bubble with "Disable developer mode extensions" when they start Chrome or open a new incognito window, which is really annoying. The only way for Windows users to use unpacked extensions without such dialogs is to switch to Chrome on the developer channel, by installing https://www.google.com/chrome/browser/index.html?extra=devchannel#eula.

Extensions can be loaded in unpacked mode by following the following steps:

  1. Visit chrome://extensions (via omnibox or menu -> Tools -> Extensions).
  2. Enable Developer mode by ticking the checkbox in the upper-right corner.
  3. Click on the "Load unpacked extension..." button.
  4. Select the directory containing your unpacked extension.

If you have a crx file, then it needs to be extracted first. CRX files are zip files with a different header. Any capable zip program should be able to open it. If you don't have such a program, I recommend 7-zip.

These steps will work for almost every extension, except extensions that rely on their extension ID. If you use the previous method, you will get an extension with a random extension ID. If it is important to preserve the extension ID, then you need to know the public key of your CRX file and insert this in your manifest.json. I have previously given a detailed explanation on how to get and use this key at https://stackoverflow.com/a/21500707.

Center image in table td in CSS

Another option is the use <th> instead of <td>. <th> defaults to center; <td> defaults to left.

C++ error 'Undefined reference to Class::Function()'

In the definition of your Card class, a declaration for a default construction appears:

class Card
{
    // ...

    Card(); // <== Declaration of default constructor!

    // ...
};

But no corresponding definition is given. In fact, this function definition (from card.cpp):

void Card() {
//nothing
}

Does not define a constructor, but rather a global function called Card that returns void. You probably meant to write this instead:

Card::Card() {
//nothing
}

Unless you do that, since the default constructor is declared but not defined, the linker will produce error about undefined references when a call to the default constructor is found.


The same applies to your constructor accepting two arguments. This:

void Card(Card::Rank rank, Card::Suit suit) {
    cardRank = rank;
    cardSuit = suit;
}

Should be rewritten into this:

Card::Card(Card::Rank rank, Card::Suit suit) {
    cardRank = rank;
    cardSuit = suit;
}

And the same also applies for other member functions: it seems you did not add the Card:: qualifier before the member function names in their definitions. Without it, those functions are global functions rather than definitions of member functions.


Your destructor, on the other hand, is declared but never defined. Just provide a definition for it in card.cpp:

Card::~Card() { }

CSS text-decoration underline color

You can do it if you wrap your text into a span like:

_x000D_
_x000D_
a {_x000D_
  color: red;_x000D_
  text-decoration: underline;_x000D_
}_x000D_
span {_x000D_
  color: blue;_x000D_
  text-decoration: none;_x000D_
}
_x000D_
<a href="#">_x000D_
  <span>Text</span>_x000D_
</a>
_x000D_
_x000D_
_x000D_

C# - insert values from file into two arrays

string[] lines = File.ReadAllLines("sample.txt"); List<string> list1 = new List<string>(); List<string> list2 = new List<string>();  foreach (var line in lines) {     string[] values = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);     list1.Add(values[0]);     list2.Add(values[1]);  } 

How to run composer from anywhere?

For MAC and LINUX use the following procedure:

Add the directory where composer.phar is located to you PATH:

export PATH=$PATH:/yourdirectory

and then rename composer.phar to composer:

mv composer.phar composer

Jenkins CI Pipeline Scripts not permitted to use method groovy.lang.GroovyObject

Quickfix

I had similar issue and I resolved it doing the following

  1. Navigate to jenkins > Manage jenkins > In-process Script Approval
  2. There was a pending command, which I had to approve.

In process approval link in Jenkins 2.61 Alternative 1: Disable sandbox

As this article explains in depth, groovy scripts are run in sandbox mode by default. This means that a subset of groovy methods are allowed to run without administrator approval. It's also possible to run scripts not in sandbox mode, which implies that the whole script needs to be approved by an administrator at once. This preventing users from approving each line at the time.

Running scripts without sandbox can be done by unchecking this checkbox in your project config just below your script: enter image description here

Alternative 2: Disable script security

As this article explains it also possible to disable script security completely. First install the permissive script security plugin and after that change your jenkins.xml file add this argument:

-Dpermissive-script-security.enabled=true

So you jenkins.xml will look something like this:

<executable>..bin\java</executable>
<arguments>-Dpermissive-script-security.enabled=true -Xrs -Xmx4096m -Dhudson.lifecycle=hudson.lifecycle.WindowsServiceLifecycle -jar "%BASE%\jenkins.war" --httpPort=80 --webroot="%BASE%\war"</arguments>

Make sure you know what you are doing if you implement this!

Select rows with same id but different value in another column

Use this

select * from (
 SELECT ARIDNR,LIEFNR,row_number() over 
     (partition by ARIDNR order by ARIDNR) as RowNum) a
where a.RowNum >1

Styling text input caret

Here are some vendors you might me looking for

::-webkit-input-placeholder {color: tomato}
::-moz-placeholder          {color: tomato;} /* Firefox 19+ */
:-moz-placeholder           {color: tomato;} /* Firefox 18- */
:-ms-input-placeholder      {color: tomato;}

You can also style different states, such as focus

:focus::-webkit-input-placeholder {color: transparent}
:focus::-moz-placeholder          {color: transparent}
:focus:-moz-placeholder           {color: transparent}
:focus:-ms-input-placeholder      {color: transparent}

You can also do certain transitions on it, like

::-VENDOR-input-placeholder       {text-indent: 0px;   transition: text-indent 0.3s ease;}
:focus::-VENDOR-input-placeholder  {text-indent: 500px; transition: text-indent 0.3s ease;}

Display A Popup Only Once Per User

You could get around this issue using php. You only echo out the code for the popup on first page load.

The other way... Is to set a cookie which is basically a file that sits in your browser and contains some kind of data. On the first page load you would create a cookie. Then every page after that you check if your cookie is set. If it is set do not display the pop up. However if its not set set the cookie and display the popup.

Pseudo code:

if(cookie_is_not_set) {
    show_pop_up;
    set_cookie;
}

HTML / CSS table with GRIDLINES

For internal gridlines, use the tag: td For external gridlines, use the tag: table

Read properties file outside JAR file

I have a similar case: wanting my *.jar file to access a file in a directory next to said *.jar file. Refer to THIS ANSWER as well.

My file structure is:

./ - the root of your program
|__ *.jar
|__ dir-next-to-jar/some.txt

I'm able to load a file (say, some.txt) to an InputStream inside the *.jar file with the following:

InputStream stream = null;
    try{
        stream = ThisClassName.class.getClass().getResourceAsStream("/dir-next-to-jar/some.txt");
    }
    catch(Exception e) {
        System.out.print("error file to stream: ");
        System.out.println(e.getMessage());
    }

Then do whatever you will with the stream

Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired

You cannot do an empty return on Laravel 5.6 or greater. Laravel always expects a value to be returned. (I know from past experience). This is mainly to do with how PHP 7 handles empty returns.

How do I find numeric columns in Pandas?

Please see the below code:

if(dataset.select_dtypes(include=[np.number]).shape[1] > 0):
display(dataset.select_dtypes(include=[np.number]).describe())
if(dataset.select_dtypes(include=[np.object]).shape[1] > 0):
display(dataset.select_dtypes(include=[np.object]).describe())

This way you can check whether the value are numeric such as float and int or the srting values. the second if statement is used for checking the string values which is referred by the object.

Imitating a blink tag with CSS3 animations

The original Netscape <blink> had an 80% duty cycle. This comes pretty close, although the real <blink> only affects text:

_x000D_
_x000D_
.blink {_x000D_
  animation: blink-animation 1s steps(5, start) infinite;_x000D_
  -webkit-animation: blink-animation 1s steps(5, start) infinite;_x000D_
}_x000D_
@keyframes blink-animation {_x000D_
  to {_x000D_
    visibility: hidden;_x000D_
  }_x000D_
}_x000D_
@-webkit-keyframes blink-animation {_x000D_
  to {_x000D_
    visibility: hidden;_x000D_
  }_x000D_
}
_x000D_
This is <span class="blink">blinking</span> text.
_x000D_
_x000D_
_x000D_

You can find more info about Keyframe Animations here.

How can I get onclick event on webview in android?

I think you can also use MotionEvent.ACTION_UP state, example:

@Override
public boolean onTouch(View v, MotionEvent event) {
    switch (v.getId()) {
    case R.id.iv:
        if (event.getAction() == MotionEvent.ACTION_UP) {
            if (isheadAndFootShow == false) {
                headLayout.setVisibility(View.VISIBLE);
                footLayout.setVisibility(View.VISIBLE);
                isheadAndFootShow = true;
            } else {
                headLayout.setVisibility(View.INVISIBLE);
                footLayout.setVisibility(View.INVISIBLE);
                isheadAndFootShow = false;
            }
            return true;
        }
        break;
    }

    return false;
}

Find a file in python

os.walk is the answer, this will find the first match:

import os

def find(name, path):
    for root, dirs, files in os.walk(path):
        if name in files:
            return os.path.join(root, name)

And this will find all matches:

def find_all(name, path):
    result = []
    for root, dirs, files in os.walk(path):
        if name in files:
            result.append(os.path.join(root, name))
    return result

And this will match a pattern:

import os, fnmatch
def find(pattern, path):
    result = []
    for root, dirs, files in os.walk(path):
        for name in files:
            if fnmatch.fnmatch(name, pattern):
                result.append(os.path.join(root, name))
    return result

find('*.txt', '/path/to/dir')

Adding IN clause List to a JPA Query

When using IN with a collection-valued parameter you don't need (...):

@NamedQuery(name = "EventLog.viewDatesInclude", 
    query = "SELECT el FROM EventLog el WHERE el.timeMark >= :dateFrom AND " 
    + "el.timeMark <= :dateTo AND " 
    + "el.name IN :inclList") 

Regex to match 2 digits, optional decimal, two digits

  \d{1,}(\.\d{1,2})|\d{0,9}

tested in https://regexr.com/

matches with numbers with 2 decimals or just one, or numbers without decimals.

You can change the number or decimals you want by changing the number 2

How to do logging in React Native?

I prefer to recommend you guys using React Native Debugger. You can download and install it by using this command.

brew update && brew cask install react-native-debugger

or

Just check the link below.

https://github.com/jhen0409/react-native-debugger

Happy Hacking!

PHP Undefined Index

The checking of the presence of the member before assigning it is, in my opinion, quite ugly.

Kohana has a useful function to make selecting parameters simple.

You can make your own like so...

function arrayGet($array, $key, $default = NULL)
{
    return isset($array[$key]) ? $array[$key] : $default;
}

And then do something like...

$page = arrayGet($_GET, 'p', 1);

How to find Current open Cursors in Oracle

1)your id should have sys dba access 2)

select sum(a.value) total_cur, avg(a.value) avg_cur, max(a.value) max_cur, 
 s.username, s.machine
 from v$sesstat a, v$statname b, v$session s 
 where a.statistic# = b.statistic# and s.sid=a.sid
 and b.name = 'opened cursors current' 
 group by s.username, s.machine
 order by 1 desc;

How to create javascript delay function

You do not need to use an anonymous function with setTimeout. You can do something like this:

setTimeout(doSomething, 3000);

function doSomething() {
   //do whatever you want here
}

Loop through each row of a range in Excel

Just stumbled upon this and thought I would suggest my solution. I typically like to use the built in functionality of assigning a range to an multi-dim array (I guess it's also the JS Programmer in me).

I frequently write code like this:

Sub arrayBuilder()

myarray = Range("A1:D4")

'unlike most VBA Arrays, this array doesn't need to be declared and will be automatically dimensioned

For i = 1 To UBound(myarray)

    For j = 1 To UBound(myarray, 2)

    Debug.Print (myarray(i, j))

    Next j

Next i

End Sub

Assigning ranges to variables is a very powerful way to manipulate data in VBA.

Error checking for NULL in VBScript

From your code, it looks like provider is a variant or some other variable, and not an object.

Is Nothing is for objects only, yet later you say it's a value that should either be NULL or NOT NULL, which would be handled by IsNull.

Try using:

If Not IsNull(provider) Then 
    url = url & "&provider=" & provider 
End if

Alternately, if that doesn't work, try:

If provider <> "" Then 
    url = url & "&provider=" & provider 
End if

Reverse Contents in Array

As a direct answer to your question: Your swapping is wrong

void reverse(int arr[], int count){
   int temp;
   for(int i = 0; i < count/2; ++i){
      arr[i] = temp; // <== Wrong, Should be deleted
      temp = arr[count-i-1];
      arr[count-i-1] = arr[i];
      arr[i] = temp;
    }
}

assigning arr[i] = temp causes error when it first enters the loop as temp initially contains garbage data and will ruin your array, remove it and the code should work well.

As an advice, use built-in functions whenever possible:

  • In the swapping you could just use swap like std::swap(arr[i], arr[count-i-1])
  • For the reverse as a whole just use reverse like std::reverse(arr, arr+count)

I am using C++14 and reverse works with arrays without any problems.

Perl - If string contains text?

For case-insensitive string search, use index (or rindex) in combination with fc. This example expands on the answer by Eugene Yarmash:

use feature qw( fc ); 
my $str = "Abc"; 
my $substr = "aB"; 

print "found" if index( fc $str, fc $substr ) != -1;
# Prints: found

print "found" if rindex( fc $str, fc $substr ) != -1;
# Prints: found

$str = "Abc";
$substr = "bA";

print "found" if index( fc $str, fc $substr ) != -1;
# Prints nothing

print "found" if rindex( fc $str, fc $substr ) != -1;
# Prints nothing

Both index and rindex return -1 if the substring is not found.
And fc returns a casefolded version of its string argument, and should be used here instead of the (more familiar) uc or lc. Remember to enable this function, for example with use feature qw( fc );.

What is difference between Errors and Exceptions?

Error is something that most of the time you cannot handle it.

Exception was meant to give you an opportunity to do something with it. like try something else or write to the log.

try{
  //connect to database 1
}
catch(DatabaseConnctionException err){
  //connect to database 2
  //write the err to log
}

The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)"

There are two crucial nonobvious settings that I've discovered when tuning linked servers on Excel under SQL Server 2014. With those settings, ' FROM OPENDATASOURCE(''Microsoft.ACE.OLEDB.16.0'', ...)' as well as '... FROM [' + @srv_name + ']...data AS xl ...' function properly.

Linked server creation

This is just for context.

DECLARE @DB_NAME NVARCHAR(30) = DB_NAME();
DECLARE @srv_name nvarchar(64) = N'<srv_base_name>@' + @DB_NAME; --to distinguish linked server usage by different databases

EXEC sp_addlinkedserver
    @server=@srv_name,
    @srvproduct=N'OLE DB Provider for ACE 16.0',
    @provider= N'Microsoft.ACE.OLEDB.16.0',
    @datasrc= '<local_file_path>\<excel_workbook_name>.xlsx',
    @provstr= N'Excel 12.0;HDR=YES;IMEX=0'
;
  1. @datasrc: Encoding is crucial here: varchar instead of nvarchar.
  2. @provstr: Verion, settings and sytax are important!
  3. @provider: Specify the provider installed in your SQL Server environment. Available providers are enumerated under Server Objects::Linked Servers::Providers in SSMS's Object Explorer.

Providing access to the linked server under specific SQL Server logins

This is the first crucial setting. Even for SA like for any other SQL Server login:

EXEC sp_addlinkedsrvlogin @rmtsrvname = @srv_name, @locallogin = N'sa', @useself = N'False', @rmtuser = N'admin', @rmtpassword = N''
;
  1. @rmtuser: It should be admin. Actually, there is no any admin in Windows logins on the system at the same time.
  2. @rmtpassword: It should be an empty string.

Providing access to the linked server via ad hoc queries

This is the second crucial setting. Setting Ad Hoc Distributed Queries to 1 is not enough. One should set to 0 the DisallowAdhocAccess registry key explicitly for the driver specified to @provider:

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL12.DEF_INST\Providers\Microsoft.ACE.OLEDB.16.0]
"DisallowAdhocAccess"=dword:00000000

Override and reset CSS style: auto or none don't work

"none" does not do what you assume it does. In order to "clear" a CSS property, you must set it back to its default, which is defined by the CSS standard. Thus you should look up the defaults in your favorite reference.

table.other {
    width: auto;
    min-width: 0;
    display:table;
}

How can I append a query parameter to an existing URL?

There are plenty of libraries that can help you with URI building (don't reinvent the wheel). Here are three to get you started:


Java EE 7

import javax.ws.rs.core.UriBuilder;
...
return UriBuilder.fromUri(url).queryParam(key, value).build();

org.apache.httpcomponents:httpclient:4.5.2

import org.apache.http.client.utils.URIBuilder;
...
return new URIBuilder(url).addParameter(key, value).build();

org.springframework:spring-web:4.2.5.RELEASE

import org.springframework.web.util.UriComponentsBuilder;
...
return UriComponentsBuilder.fromUriString(url).queryParam(key, value).build().toUri();

See also: GIST > URI Builder Tests

PHP Change Array Keys

To have the same key I think they must be in separate nested arrays.

for ($i = 0; $i < count($array); $i++) {
    $newArray[] = ['name' => $array[$i]];
};

Output:

0 => array:1 ["name" => "blabla"]
1 => array:1 ["name" => "blabla"]
2 => array:1 ["name" => "blblll"]

Textfield with only bottom border

Probably a duplicate of this post: A customized input text box in html/html5

_x000D_
_x000D_
input {_x000D_
  border: 0;_x000D_
  outline: 0;_x000D_
  background: transparent;_x000D_
  border-bottom: 1px solid black;_x000D_
}
_x000D_
<input></input>
_x000D_
_x000D_
_x000D_

Python: convert string to byte array

An alternative to get a byte array is to encode the string in ascii: b=s.encode('ascii').

jQuery Validate Plugin - How to create a simple custom rule?

// add a method. calls one built-in method, too.
jQuery.validator.addMethod("optdate", function(value, element) {
        return jQuery.validator.methods['date'].call(
            this,value,element
        )||value==("0000/00/00");
    }, "Please enter a valid date."
);

// connect it to a css class
jQuery.validator.addClassRules({
    optdate : { optdate : true }    
});

jQuery: How can I show an image popup onclick of the thumbnail?

I like prettyPhoto

prettyPhoto is a jQuery lightbox clone. Not only does it support images, it also support for videos, flash, YouTube, iframes and ajax. It’s a full blown media lightbox

How do you get the "object reference" of an object in java when toString() and hashCode() have been overridden?

What exactly are you planning on doing with it (what you want to do makes a difference with what you will need to call).

hashCode, as defined in the JavaDocs, says:

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java™ programming language.)

So if you are using hashCode() to find out if it is a unique object in memory that isn't a good way to do it.

System.identityHashCode does the following:

Returns the same hash code for the given object as would be returned by the default method hashCode(), whether or not the given object's class overrides hashCode(). The hash code for the null reference is zero.

Which, for what you are doing, sounds like what you want... but what you want to do might not be safe depending on how the library is implemented.

How can I clone an SQL Server database on the same server in SQL Server 2008 Express?

If the database is not very large, you might look at the 'Script Database' commands in SQL Server Management Studio Express, which are in a context menu off the database item itself in the explorer.

You can choose what all to script; you want the objects and the data, of course. You will then save the entire script to a single file. Then you can use that file to re-create the database; just make sure the USE command at the top is set to the proper database.

Getting Cannot read property 'offsetWidth' of undefined with bootstrap carousel script

Remove the class 'Carousal slide' on page load & add it dynamically when image gets loaded using jquery.This fixed for me

ORA-00054: resource busy and acquire with NOWAIT specified or timeout expired

This happens when a session other than the one used to alter a table is holding a lock likely because of a DML (update/delete/insert). If you are developing a new system, it is likely that you or someone in your team issues the update statement and you could kill the session without much consequence. Or you could commit from that session once you know who has the session open.

If you have access to a SQL admin system use it to find the offending session. And perhaps kill it.

You could use v$session and v$lock and others but I suggest you google how to find that session and then how to kill it.

In a production system, it really depends. For oracle 10g and older, you could execute

LOCK TABLE mytable in exclusive mode;
alter table mytable modify mycolumn varchar2(5);

In a separate session but have the following ready in case it takes too long.

alter system kill session '....

It depends on what system do you have, older systems are more likely to not commit every single time. That is a problem since there may be long standing locks. So your lock would prevent any new locks and wait for a lock that who knows when will be released. That is why you have the other statement ready. Or you could look for PLSQL scripts out there that do similar things automatically.

In version 11g there is a new environment variable that sets a wait time. I think it likely does something similar to what I described. Mind you that locking issues don't go away.

ALTER SYSTEM SET ddl_lock_timeout=20;
alter table mytable modify mycolumn varchar2(5);

Finally it may be best to wait until there are few users in the system to do this kind of maintenance.

nodejs mongodb object id to string

There are two ways to do this:

  1. in stead of using user._id use user.id and it will return a string for you
  2. If you really want to go the long way around you can use user._id.toString()

Get source JARs from Maven repository

In eclipse - click on the project then:

enter image description here.

How can I resize an image dynamically with CSS as the browser width/height changes?

This can be done with pure CSS and does not even require media queries.

To make the images flexible, simply add max-width:100% and height:auto. Image max-width:100% and height:auto works in IE7, but not in IE8 (yes, another weird IE bug). To fix this, you need to add width:auto\9 for IE8.

source: http://webdesignerwall.com/tutorials/responsive-design-with-css3-media-queries

CSS:

img {
    max-width: 100%;
    height: auto;
    width: auto\9; /* ie8 */
}

And if you want to enforce a fixed max width of the image, just place it inside a container, for example:

<div style="max-width:500px;">
    <img src="..." />
</div>

JSFiddle example here. No JavaScript required. Works in latest versions of Chrome, Firefox and IE (which is all I've tested).

Example using Hyperlink in WPF

Hyperlink is not a control, it is a flow content element, you can only use it in controls which support flow content, like a TextBlock. TextBoxes only have plain text.

What should every programmer know about security?

Just wanted to share this for web developers:

security-guide-for-developers
https://github.com/FallibleInc/security-guide-for-developers

Multiple "style" attributes in a "span" tag: what's supposed to happen?

In HTML, SGML and XML, (1) attributes cannot be repeated, and should only be defined in an element once.

So your example:

<span style="color:blue" style="font-style:italic">Test</span>

is non-conformant to the HTML standard, and will result in undefined behaviour, which explains why different browsers are rendering it differently.


Since there is no defined way to interpret this, browsers can interpret it however they want and merge them, or ignore them as they wish.

(1): Every article I can find states that attributes are "key/value" pairs or "attribute-value" pairs, heavily implying the keys must be unique. The best source I can find states:

Attribute names (id and status in this example) are subject to the same restrictions as other names in XML; they need not be unique across the whole DTD, however, but only within the list of attributes for a given element. (Emphasis mine.)

How do I type a TAB character in PowerShell?

TAB has a specific meaning in PowerShell. It's for command completion. So if you enter "getch" and then type a TAB. It changes what you typed into "GetChildItem" (it corrects the case, even though that's unnecessary).

From your question, it looks like TAB completion and command completion would overload the TAB key. I'm pretty sure the PowerShell designers didn't want that.

MySQL ERROR 1045 (28000): Access denied for user 'bill'@'localhost' (using password: YES)

Nowadays! Solution for :

MySQL ERROR 1045 (28000): Access denied for user 'user'@'localhost' (using password: YES);

Wampserver 3.2.0 new instalation or upgrading

Probably xamp using mariaDB as default is well.

Wamp server comes with mariaDB and mysql, and instaling mariaDB as default on 3306 port and mysql on 3307, port sometimes 3308.

Connect to mysql!

On instalation it asks to use mariaDB or MySql, But mariaDB is checked as default and you cant change it, check mysql option and install.

when instalation done both will be runing mariaDB on default port 3306 and mysql on another port 3307 or 3308.

Right click on wampserver icon where its runing should be on right bottom corner, goto tools and see your correct mysql runing port.

And include it in your database connection same as folowng :

$host = 'localhost';
$db   = 'test';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';
$port = '3308';//Port

$dsn = "mysql:host=$host;dbname=$db;port=$port;charset=$charset"; //Add in connection
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];
try {
     $pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
     throw new \PDOException($e->getMessage(), (int)$e->getCode());
}

Note : I am using pdo.

See here for more : https://sourceforge.net/projects/wampserver/

Indirectly referenced from required .class file

How are you adding your Weblogic classes to the classpath in Eclipse? Are you using WTP, and a server runtime? If so, is your server runtime associated with your project?

If you right click on your project and choose build path->configure build path and then choose the libraries tab. You should see the weblogic libraries associated here. If you do not you can click Add Library->Server Runtime. If the library is not there, then you first need to configure it. Windows->Preferences->Server->Installed runtimes

MVC3 EditorFor readOnly

Here's how I do it:

Model:

[ReadOnly(true)]
public string Email { get { return DbUser.Email; } }

View:

@Html.TheEditorFor(x => x.Email)

Extension:

namespace System.Web.Mvc
{
    public static class CustomExtensions
    {
        public static MvcHtmlString TheEditorFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes = null)
        {
            return iEREditorForInternal(htmlHelper, expression, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
        }

        private static MvcHtmlString iEREditorForInternal<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes)
        {
            if (htmlAttributes == null) htmlAttributes = new Dictionary<string, object>();

            TagBuilder builder = new TagBuilder("div");
            builder.MergeAttributes(htmlAttributes);

            var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);


            string labelHtml = labelHtml = Html.LabelExtensions.LabelFor(htmlHelper, expression).ToHtmlString();

            if (metadata.IsRequired)
                labelHtml = Html.LabelExtensions.LabelFor(htmlHelper, expression, new { @class = "required" }).ToHtmlString();


            string editorHtml = Html.EditorExtensions.EditorFor(htmlHelper, expression).ToHtmlString();

            if (metadata.IsReadOnly)
                editorHtml = Html.DisplayExtensions.DisplayFor(htmlHelper, expression).ToHtmlString();


            string validationHtml = Html.ValidationExtensions.ValidationMessageFor(htmlHelper, expression).ToHtmlString();

            builder.InnerHtml = labelHtml + editorHtml + validationHtml;

            return new MvcHtmlString(builder.ToString(TagRenderMode.Normal));
        }
    }
}

Of course my editor is doing a bunch more stuff, like adding a label, adding a required class to that label as necessary, adding a DisplayFor if the property is ReadOnly EditorFor if its not, adding a ValidateMessageFor and finally wrapping all of that in a Div that can have Html Attributes assigned to it... my Views are super clean.

How to find the files that are created in the last hour in unix

find ./ -cTime -1 -type f

OR

find ./ -cmin -60 -type f

In git, what is the difference between merge --squash and rebase?

Let's start by the following example:

enter image description here

Now we have 3 options to merge changes of feature branch into master branch:

  1. Merge commits
    Will keep all commits history of the feature branch and move them into the master branch
    Will add extra dummy commit.

  2. Rebase and merge
    Will append all commits history of the feature branch in the front of the master branch
    Will NOT add extra dummy commit.

  3. Squash and merge
    Will group all feature branch commits into one commit then append it in the front of the master branch
    Will add extra dummy commit.

You can find below how the master branch will look after each one of them.

enter image description here

In all cases:
We can safely DELETE the feature branch.

Comparing results with today's date?

For me the query that is working, if I want to compare with DrawDate for example is:

CAST(DrawDate AS DATE) = CAST (GETDATE() as DATE)

This is comparing results with today's date.

or the whole query:

SELECT TOP (1000) *
FROM test
where DrawName != 'NULL' and CAST(DrawDate AS DATE) = CAST (GETDATE() as DATE)
order by id desc

PHP: get the value of TEXTBOX then pass it to a VARIABLE

You are posting the data, so it should be $_POST. But 'name' is not the best name to use.

name = "name"

will only cause confusion IMO.

C# "internal" access modifier when doing unit testing

Keep using private by default. If a member shouldn't be exposed beyond that type, it shouldn't be exposed beyond that type, even to within the same project. This keeps things safer and tidier - when you're using the object, it's clearer which methods you're meant to be able to use.

Having said that, I think it's reasonable to make naturally-private methods internal for test purposes sometimes. I prefer that to using reflection, which is refactoring-unfriendly.

One thing to consider might be a "ForTest" suffix:

internal void DoThisForTest(string name)
{
    DoThis(name);
}

private void DoThis(string name)
{
    // Real implementation
}

Then when you're using the class within the same project, it's obvious (now and in the future) that you shouldn't really be using this method - it's only there for test purposes. This is a bit hacky, and not something I do myself, but it's at least worth consideration.

Get file size, image width and height before upload

Demo

Not sure if it is what you want, but just simple example:

var input = document.getElementById('input');

input.addEventListener("change", function() {
    var file  = this.files[0];
    var img = new Image();

    img.onload = function() {
        var sizes = {
            width:this.width,
            height: this.height
        };
        URL.revokeObjectURL(this.src);

        console.log('onload: sizes', sizes);
        console.log('onload: this', this);
    }

    var objectURL = URL.createObjectURL(file);

    console.log('change: file', file);
    console.log('change: objectURL', objectURL);
    img.src = objectURL;
});

JRE 1.7 - java version - returns: java/lang/NoClassDefFoundError: java/lang/Object

So, I went on trying everything and at last it seems that reinstalling java after uninstalling it fixed my problem.

Java Web Service client basic authentication

Some context additional about basic authentication, it consists in a header which contains the key/value pair:

Authorization: Basic Z2VybWFuOmdlcm1hbg==

where "Authorization" is the headers key, and the headers value has a string ( "Basic" word plus blank space) concatenated to "Z2VybWFuOmdlcm1hbg==", which are the user and password in base 64 joint by double dot

String name = "username";
String password = "secret";
String authString = name + ":" + password;
String authStringEnc = new BASE64Encoder().encode(authString.getBytes());
...
objectXXX.header("Authorization", "Basic " + authStringEnc);

SQL Server reports 'Invalid column name', but the column is present and the query works through management studio

In my case I restart Microsoft SQL Sever Management Studio and this works well for me.

Sql select rows containing part of string

SELECT *
FROM myTable
WHERE URL = LEFT('mysyte.com/?id=2&region=0&page=1', LEN(URL))

Or use CHARINDEX http://msdn.microsoft.com/en-us/library/aa258228(v=SQL.80).aspx

Listing available com ports with Python

You can use:

python -c "import serial.tools.list_ports;print serial.tools.list_ports.comports()"

Filter by know port: python -c "import serial.tools.list_ports;print [port for port in serial.tools.list_ports.comports() if port[2] != 'n/a']"

See more info here: https://pyserial.readthedocs.org/en/latest/tools.html#module-serial.tools.list_ports

How to build & install GLFW 3 and use it in a Linux project

Note that you do not need that many -ls if you install glfw with the BUILD_SHARED_LIBS option. (You can enable this option by running ccmake first).

This way sudo make install will install the shared library in /usr/local/lib/libglfw.so. You can then compile the example file with a simple:

g++ main.cpp -L /usr/local/lib/ -lglfw

Then do not forget to add /usr/local/lib/ to the search path for shared libraries before running your program. This can be done using:

export LD_LIBRARY_PATH=/usr/local/lib:${LD_LIBRARY_PATH}

And you can put that in your ~/.bashrc so you don't have to type it all the time.

Bootstrap 3: Scroll bars

You need to use overflow option like below:

.nav{
    max-height: 300px;
    overflow-y: scroll; 
}

Change the height according to amount of items you need to show

Fastest way(s) to move the cursor on a terminal command line?

It might not be the fastest, but this need to be here, some reading about ANSI cursor movements

ANSI escape sequences allow you to move the cursor around the screen at will. This is more useful for full screen user interfaces generated by shell scripts, but can also be used in prompts. The movement escape sequences are as follows:

- Position the Cursor:
  \033[<L>;<C>H
     Or
  \033[<L>;<C>f
  puts the cursor at line L and column C.
- Move the cursor up N lines:
  \033[<N>A
- Move the cursor down N lines:
  \033[<N>B
- Move the cursor forward N columns:
  \033[<N>C
- Move the cursor backward N columns:
  \033[<N>D

- Clear the screen, move to (0,0):
  \033[2J  or \033c
- Erase to end of line:
  \033[K

- Save cursor position:
  \033[s
- Restore cursor position:
  \033[u

(...)

Try putting in the following line of code at the prompt (it's a little clearer what it does if the prompt is several lines down the terminal when you put this in): echo -en "\033[7A\033[1;35m BASH \033[7B\033[6D" This should move the cursor seven lines up screen, print the word " BASH ", and then return to where it started to produce a normal prompt.


Examples:

Move the cursor back 7 lines:

echo -e "\033[7A"

Move the cursor to line 10, column 5:

echo -e "\033[10;5H"

Quickly echo colors codes, to colorize a program:

echo -e "\033[35;42m" ; ifconfig

How to automatically indent source code?

In 2010 it is ctrl +k +d for indentation

How to check for an undefined or null variable in JavaScript?

I think the most efficient way to test for "value is null or undefined" is

if ( some_variable == null ){
  // some_variable is either null or undefined
}

So these two lines are equivalent:

if ( typeof(some_variable) !== "undefined" && some_variable !== null ) {}
if ( some_variable != null ) {}

Note 1

As mentioned in the question, the short variant requires that some_variable has been declared, otherwise a ReferenceError will be thrown. However in many use cases you can assume that this is safe:

check for optional arguments:

function(foo){
    if( foo == null ) {...}

check for properties on an existing object

if(my_obj.foo == null) {...}

On the other hand typeof can deal with undeclared global variables (simply returns undefined). Yet these cases should be reduced to a minimum for good reasons, as Alsciende explained.

Note 2

This - even shorter - variant is not equivalent:

if ( !some_variable ) {
  // some_variable is either null, undefined, 0, NaN, false, or an empty string
}

so

if ( some_variable ) {
  // we don't get here if some_variable is null, undefined, 0, NaN, false, or ""
}

Note 3

In general it is recommended to use === instead of ==. The proposed solution is an exception to this rule. The JSHint syntax checker even provides the eqnull option for this reason.

From the jQuery style guide:

Strict equality checks (===) should be used in favor of ==. The only exception is when checking for undefined and null by way of null.

// Check for both undefined and null values, for some important reason. 
undefOrNull == null;

Cannot set property 'innerHTML' of null

There are different possible cause as discussed would just like to add this for someone who might have the same issue as mine.

In my case I had a missing close div as shown below

   <!DOCTYPE HTML>
   <html>
   <head>
   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
   <title>Untitled Document</title>
   </head>
   <body>
   <div> //I am an open div
    <div id="hello"></div>
   <script type ="text/javascript">
       what();
       function what(){
          document.getElementById('hello').innerHTML = 'hi';
       };
   </script>
   </body>
   </html>

Missing a close div can result in disorganization of the transversal from child to parent or parent to child hence resulting in an error when you try to access an element in the DOM

TERM environment variable not set

You've answered the question with this statement:

Cron calls this .sh every 2 minutes

Cron does not run in a terminal, so why would you expect one to be set?

The most common reason for getting this error message is because the script attempts to source the user's .profile which does not check that it's running in a terminal before doing something tty related. Workarounds include using a shebang line like:

#!/bin/bash -p

Which causes the sourcing of system-level profile scripts which (one hopes) does not attempt to do anything too silly and will have guards around code that depends on being run from a terminal.

If this is the entirety of the script, then the TERM error is coming from something other than the plain content of the script.

How does one sum only those rows in excel not filtered out?

You need to use the SUBTOTAL function. The SUBTOTAL function ignores rows that have been excluded by a filter.

The formula would look like this:

=SUBTOTAL(9,B1:B20)

The function number 9, tells it to use the SUM function on the data range B1:B20.

If you are 'filtering' by hiding rows, the function number should be updated to 109.

=SUBTOTAL(109,B1:B20)

The function number 109 is for the SUM function as well, but hidden rows are ignored.

String.equals versus ==

It's good to notice that in some cases use of "==" operator can lead to the expected result, because the way how java handles strings - string literals are interned (see String.intern()) during compilation - so when you write for example "hello world" in two classes and compare those strings with "==" you could get result: true, which is expected according to specification; when you compare same strings (if they have same value) when the first one is string literal (ie. defined through "i am string literal") and second is constructed during runtime ie. with "new" keyword like new String("i am string literal"), the == (equality) operator returns false, because both of them are different instances of the String class.

Only right way is using .equals() -> datos[0].equals(usuario). == says only if two objects are the same instance of object (ie. have same memory address)

Update: 01.04.2013 I updated this post due comments below which are somehow right. Originally I declared that interning (String.intern) is side effect of JVM optimization. Although it certainly save memory resources (which was what i meant by "optimization") it is mainly feature of language

How to add key,value pair to dictionary?

I got here looking for a way to add a key/value pair(s) as a group - in my case it was the output of a function call, so adding the pair using dictionary[key] = value would require me to know the name of the key(s).

In this case, you can use the update method: dictionary.update(function_that_returns_a_dict(*args, **kwargs)))

Beware, if dictionary already contains one of the keys, the original value will be overwritten.

New to MongoDB Can not run command mongo

Specify the database path explicitly like so, and see if that resolves the issue.

mongod --dbpath data/db

Jersey stopped working with InjectionManagerFactory not found

Jersey 2.26 and newer are not backward compatible with older versions. The reason behind that has been stated in the release notes:

Unfortunately, there was a need to make backwards incompatible changes in 2.26. Concretely jersey-proprietary reactive client API is completely gone and cannot be supported any longer - it conflicts with what was introduced in JAX-RS 2.1 (that's the price for Jersey being "spec playground..").

Another bigger change in Jersey code is attempt to make Jersey core independent of any specific injection framework. As you might now, Jersey 2.x is (was!) pretty tightly dependent on HK2, which sometimes causes issues (esp. when running on other injection containers. Jersey now defines it's own injection facade, which, when implemented properly, replaces all internal Jersey injection.


As for now one should use the following dependencies:

Maven

<dependency>
    <groupId>org.glassfish.jersey.inject</groupId>
    <artifactId>jersey-hk2</artifactId>
    <version>2.26</version>
</dependency>

Gradle

compile 'org.glassfish.jersey.core:jersey-common:2.26'
compile 'org.glassfish.jersey.inject:jersey-hk2:2.26'

How to format a Date in MM/dd/yyyy HH:mm:ss format in JavaScript?

Try something like this

var d = new Date,
    dformat = [d.getMonth()+1,
               d.getDate(),
               d.getFullYear()].join('/')+' '+
              [d.getHours(),
               d.getMinutes(),
               d.getSeconds()].join(':');

If you want leading zero's for values < 10, use this number extension

Number.prototype.padLeft = function(base,chr){
    var  len = (String(base || 10).length - String(this).length)+1;
    return len > 0? new Array(len).join(chr || '0')+this : this;
}
// usage
//=> 3..padLeft() => '03'
//=> 3..padLeft(100,'-') => '--3' 

Applied to the previous code:

var d = new Date,
    dformat = [(d.getMonth()+1).padLeft(),
               d.getDate().padLeft(),
               d.getFullYear()].join('/') +' ' +
              [d.getHours().padLeft(),
               d.getMinutes().padLeft(),
               d.getSeconds().padLeft()].join(':');
//=> dformat => '05/17/2012 10:52:21'

See this code in jsfiddle

[edit 2019] Using ES20xx, you can use a template literal and the new padStart string extension.

_x000D_
_x000D_
var dt = new Date();_x000D_
_x000D_
console.log(`${_x000D_
    (dt.getMonth()+1).toString().padStart(2, '0')}/${_x000D_
    dt.getDate().toString().padStart(2, '0')}/${_x000D_
    dt.getFullYear().toString().padStart(4, '0')} ${_x000D_
    dt.getHours().toString().padStart(2, '0')}:${_x000D_
    dt.getMinutes().toString().padStart(2, '0')}:${_x000D_
    dt.getSeconds().toString().padStart(2, '0')}`_x000D_
);
_x000D_
_x000D_
_x000D_

See also

What exactly does big ? notation represent?

It means that the algorithm is both big-O and big-Omega in the given function.

For example, if it is ?(n), then there is some constant k, such that your function (run-time, whatever), is larger than n*k for sufficiently large n, and some other constant K such that your function is smaller than n*K for sufficiently large n.

In other words, for sufficiently large n, it is sandwiched between two linear functions :

For k < K and n sufficiently large, n*k < f(n) < n*K