Programs & Examples On #Rfc3339

A RFC entitled "Date and Time on the Internet: Timestamps"

How do I parse an ISO 8601-formatted date?

If you don't want to use dateutil, you can try this function:

def from_utc(utcTime,fmt="%Y-%m-%dT%H:%M:%S.%fZ"):
    """
    Convert UTC time string to time.struct_time
    """
    # change datetime.datetime to time, return time.struct_time type
    return datetime.datetime.strptime(utcTime, fmt)

Test:

from_utc("2007-03-04T21:08:12.123Z")

Result:

datetime.datetime(2007, 3, 4, 21, 8, 12, 123000)

How to convert a timezone aware string to datetime in Python without dateutil?

Here is the Python Doc for datetime object using dateutil package..

from dateutil.parser import parse

get_date_obj = parse("2012-11-01T04:16:13-04:00")
print get_date_obj

Parse rfc3339 date strings in Python?

You should have a look at moment which is a python port of the excellent js lib momentjs.

One advantage of it is the support of ISO 8601 strings formats, as well as a generic "% format" :

import moment
time_string='2012-10-09T19:00:55Z'

m = moment.date(time_string, '%Y-%m-%dT%H:%M:%SZ')
print m.format('YYYY-M-D H:M')
print m.weekday

Result:

2012-10-09 19:10
2

How can I parse / create a date time stamp formatted with fractional seconds UTC timezone (ISO 8601, RFC 3339) in Swift?

Swift 5

If you're targeting iOS 11.0+ / macOS 10.13+, you simply use ISO8601DateFormatter with the withInternetDateTime and withFractionalSeconds options, like so:

let date = Date()

let iso8601DateFormatter = ISO8601DateFormatter()
iso8601DateFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
let string = iso8601DateFormatter.string(from: date)

// string looks like "2020-03-04T21:39:02.112Z"

What exactly does the T and Z mean in timestamp?

The T doesn't really stand for anything. It is just the separator that the ISO 8601 combined date-time format requires. You can read it as an abbreviation for Time.

The Z stands for the Zero timezone, as it is offset by 0 from the Coordinated Universal Time (UTC).

Both characters are just static letters in the format, which is why they are not documented by the datetime.strftime() method. You could have used Q or M or Monty Python and the method would have returned them unchanged as well; the method only looks for patterns starting with % to replace those with information from the datetime object.

How to use the DropDownList's SelectedIndexChanged event

The most basic way you can do this in SelectedIndexChanged events of DropDownLists. Check this code..

    <asp:DropDownList ID="DropDownList1" runat="server" onselectedindexchanged="DropDownList1_SelectedIndexChanged" Width="224px"
        AutoPostBack="True" AppendDataBoundItems="true">
    <asp:DropDownList ID="DropDownList2" runat="server"
        onselectedindexchanged="DropDownList2_SelectedIndexChanged">
    </asp:DropDownList> 


protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    //Load DropDownList2

}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
    //Load DropDownList3
}

Flutter - Layout a Grid

There are few named constructors in GridView for different scenarios,

Constructors

  1. GridView
  2. GridView.builder
  3. GridView.count
  4. GridView.custom
  5. GridView.extent

Below is a example of GridView constructor:

import 'package:flutter/material.dart';

void main() => runApp(
  MaterialApp(
    home: ExampleGrid(),
  ),
);

class ExampleGrid extends StatelessWidget {
  List<String> images = [
    "https://uae.microless.com/cdn/no_image.jpg",
    "https://images-na.ssl-images-amazon.com/images/I/81aF3Ob-2KL._UX679_.jpg",
    "https://www.boostmobile.com/content/dam/boostmobile/en/products/phones/apple/iphone-7/silver/device-front.png.transform/pdpCarousel/image.jpg",
    "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSgUgs8_kmuhScsx-J01d8fA1mhlCR5-1jyvMYxqCB8h3LCqcgl9Q",
    "https://ae01.alicdn.com/kf/HTB11tA5aiAKL1JjSZFoq6ygCFXaw/Unlocked-Samsung-GALAXY-S2-I9100-Mobile-Phone-Android-Wi-Fi-GPS-8-0MP-camera-Core-4.jpg_640x640.jpg",
    "https://media.ed.edmunds-media.com/gmc/sierra-3500hd/2018/td/2018_gmc_sierra-3500hd_f34_td_411183_1600.jpg",
    "https://hips.hearstapps.com/amv-prod-cad-assets.s3.amazonaws.com/images/16q1/665019/2016-chevrolet-silverado-2500hd-high-country-diesel-test-review-car-and-driver-photo-665520-s-original.jpg",
    "https://www.galeanasvandykedodge.net/assets/stock/ColorMatched_01/White/640/cc_2018DOV170002_01_640/cc_2018DOV170002_01_640_PSC.jpg",
    "https://media.onthemarket.com/properties/6191869/797156548/composite.jpg",
    "https://media.onthemarket.com/properties/6191840/797152761/composite.jpg",
  ];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GridView(
        physics: BouncingScrollPhysics(), // if you want IOS bouncing effect, otherwise remove this line
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),//change the number as you want
        children: images.map((url) {
          return Card(child: Image.network(url));
        }).toList(),
      ),
    );
  }
}

If you want your GridView items to be dynamic according to the content, you can few lines to do that but the simplest way to use StaggeredGridView package. I have provided an answer with example here.

Below is an example for a GridView.count:

import 'package:flutter/material.dart';

void main() => runApp(
      MaterialApp(
        home: ExampleGrid(),
      ),
    );

class ExampleGrid extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GridView.count(
        crossAxisCount: 4,
        children: List.generate(40, (index) {
          return Card(
            child: Image.network("https://robohash.org/$index"),
          ); //robohash.org api provide you different images for any number you are giving
        }),
      ),
    );
  }
}

Screenshot for above snippet:

Flutter gridview example by blasanka using card widget and robohash api

Example for a SliverGridView:

import 'package:flutter/material.dart';

void main() => runApp(
      MaterialApp(
        home: ExampleGrid(),
      ),
    );

class ExampleGrid extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        primary: false,
        slivers: <Widget>[
          SliverPadding(
            padding: const EdgeInsets.all(20.0),
            sliver: SliverGrid.count(
              crossAxisSpacing: 10.0,
              crossAxisCount: 2,
              children: List.generate(20, (index) {
                return Card(child: Image.network("https://robohash.org/$index"));
              }),
            ),
          ),
        ],
      )
    );
  }
}

MySQL: How to add one day to datetime field in query

You can try this:

SELECT DATE(DATE_ADD(m_inv_reqdate, INTERVAL + 1 DAY)) FROM  tr08_investment

How to insert current datetime in postgresql insert query

For current datetime, you can use now() function in postgresql insert query.

You can also refer following link.

insert statement in postgres for data type timestamp without time zone NOT NULL,.

Change key pair for ec2 instance

I noticed that when managed by Elastic Beanstalk, you can change your active EC2 key pair. Under Elastic Beanstalk > Configuration > Security, choose the new key from the EC2 key pair drop-down. You'll see this message asking if you're sure:

EC2KeyName: Changes to option EC2KeyName settings will not take effect immediately. Each of your existing EC2 instances will be replaced and your new settings will take effect then.

My instance was already terminated when I did this. It then started, terminated, and started again. Apparently "replacing" means terminating and creating a new instance. If you've modified your boot volume, create an AMI first, then specify that AMI in the same Elastic Beanstalk > Configuration > Instances form as the Custom AMI ID. This also warns about replacing the EC2 instances.

After you've modified your EC2 key pair and Custom AMI ID, and after seeing warnings about both, click Save to continue.

Remember that the IP address changes when the instance is re-created so you'll need to retrieve a new IP address from the EC2 console to use when connecting via SSH.

How to create our own Listener interface in android?

Create listener interface.

public interface YourCustomListener
{
    public void onCustomClick(View view);
            // pass view as argument or whatever you want.
}

And create method setOnCustomClick in another activity(or fragment) , where you want to apply your custom listener......

  public void setCustomClickListener(YourCustomListener yourCustomListener)
{
    this.yourCustomListener= yourCustomListener;
}

Call this method from your First activity, and pass the listener interface...

Server is already running in Rails

It happens when you kill your server process and the pid file was not updated. The best solution is to delete the file Server.pid.

Use the command

rm <path to file Server.pid>

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

I have this method for deserializing an XML and converting the type:

public <T> Object deserialize(String xml, Class objClass ,TypeReference<T> typeReference ) throws IOException {
    XmlMapper xmlMapper = new XmlMapper();
    Object obj = xmlMapper.readValue(xml,objClass);
    return  xmlMapper.convertValue(obj,typeReference );   
}

and this is the call:

List<POJO> pojos = (List<POJO>) MyUtilClass.deserialize(xml, ArrayList.class,new TypeReference< List< POJO >>(){ });

jQuery check if it is clicked or not

Using jQuery, I would suggest a shorter solution.

var elementClicked;
$("element").click(function(){
   elementClicked = true;
});
if( elementClicked != true ) {
    alert("element not clicked");
}else{
    alert("element clicked");
}

("element" here is to be replaced with the actual name tag)

Neither BindingResult nor plain target object for bean name available as request attribute

I had problem like this, but with several "actions". My solution looks like this:

    <form method="POST" th:object="${searchRequest}" action="searchRequest" >
          <input type="text" th:field="*{name}"/>
          <input type="submit" value="find" th:value="find" />
    </form>
        ...
    <form method="POST" th:object="${commodity}" >
        <input type="text" th:field="*{description}"/>
        <input type="submit" value="add" />
    </form>

And controller

@Controller
@RequestMapping("/goods")
public class GoodsController {
    @RequestMapping(value = "add", method = GET)
    public String showGoodsForm(Model model){
           model.addAttribute(new Commodity());
           model.addAttribute("searchRequest", new SearchRequest());
           return "goodsForm";
    }
    @RequestMapping(value = "add", method = POST)
    public ModelAndView processAddCommodities(
            @Valid Commodity commodity,
            Errors errors) {
        if (errors.hasErrors()) {
            ModelAndView model = new ModelAndView("goodsForm");
            model.addObject("searchRequest", new SearchRequest());
            return model;
        }
        ModelAndView model = new ModelAndView("redirect:/goods/" + commodity.getName());
        model.addObject(new Commodity());
        model.addObject("searchRequest", new SearchRequest());
        return model;
    }
    @RequestMapping(value="searchRequest", method=POST)
    public String processFindCommodity(SearchRequest commodity, Model model) {
    ...
        return "catalog";
    }

I'm sure - here is not "best practice", but it is works without "Neither BindingResult nor plain target object for bean name available as request attribute".

#1071 - Specified key was too long; max key length is 1000 bytes

I had this issue, and solved by following:

Cause

There is a known bug with MySQL related to MyISAM, the UTF8 character set and indexes that you can check here.

Resolution

  • Make sure MySQL is configured with the InnoDB storage engine.

  • Change the storage engine used by default so that new tables will always be created appropriately:

    set GLOBAL storage_engine='InnoDb';

  • For MySQL 5.6 and later, use the following:

    SET GLOBAL default_storage_engine = 'InnoDB';

  • And finally make sure that you're following the instructions provided in Migrating to MySQL.

Reference

Jquery - How to get the style display attribute "none / block"

You could try:

$j('div.contextualError.ckgcellphone').css('display')

R Not in subset

The expression df1$id %in% idNums1 produces a logical vector. To negate it, you need to negate the whole vector:

!(df1$id %in% idNums1)

base 64 encode and decode a string in angular (2+)

For encoding to base64 in Angular2, you can use btoa() function.

Example:-

console.log(btoa("stringAngular2")); 
// Output:- c3RyaW5nQW5ndWxhcjI=

For decoding from base64 in Angular2, you can use atob() function.

Example:-

console.log(atob("c3RyaW5nQW5ndWxhcjI=")); 
// Output:- stringAngular2

SQL Server: Query fast, but slow from procedure

I had the same problem as the original poster but the quoted answer did not solve the problem for me. The query still ran really slow from a stored procedure.

I found another answer here "Parameter Sniffing", Thanks Omnibuzz. Boils down to using "local Variables" in your stored procedure queries, but read the original for more understanding, it's a great write up. e.g.

Slow way:

CREATE PROCEDURE GetOrderForCustomers(@CustID varchar(20))
AS
BEGIN
    SELECT * 
    FROM orders
    WHERE customerid = @CustID
END

Fast way:

CREATE PROCEDURE GetOrderForCustomersWithoutPS(@CustID varchar(20))
AS
BEGIN
    DECLARE @LocCustID varchar(20)
    SET @LocCustID = @CustID

    SELECT * 
    FROM orders
    WHERE customerid = @LocCustID
END

Hope this helps somebody else, doing this reduced my execution time from 5+ minutes to about 6-7 seconds.

How to check visibility of software keyboard in Android?

It has been forever in terms of computer but this question is still unbelievably relevant!

So I've taken the above answers and have combined and refined them a bit...

public interface OnKeyboardVisibilityListener {


    void onVisibilityChanged(boolean visible);
}

public final void setKeyboardListener(final OnKeyboardVisibilityListener listener) {
    final View activityRootView = ((ViewGroup) getActivity().findViewById(android.R.id.content)).getChildAt(0);

    activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

        private boolean wasOpened;

        private final int DefaultKeyboardDP = 100;

        // From @nathanielwolf answer...  Lollipop includes button bar in the root. Add height of button bar (48dp) to maxDiff
        private final int EstimatedKeyboardDP = DefaultKeyboardDP + (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? 48 : 0);

        private final Rect r = new Rect();

        @Override
        public void onGlobalLayout() {
            // Convert the dp to pixels.
            int estimatedKeyboardHeight = (int) TypedValue
                    .applyDimension(TypedValue.COMPLEX_UNIT_DIP, EstimatedKeyboardDP, activityRootView.getResources().getDisplayMetrics());

            // Conclude whether the keyboard is shown or not.
            activityRootView.getWindowVisibleDisplayFrame(r);
            int heightDiff = activityRootView.getRootView().getHeight() - (r.bottom - r.top);
            boolean isShown = heightDiff >= estimatedKeyboardHeight;

            if (isShown == wasOpened) {
                Log.d("Keyboard state", "Ignoring global layout change...");
                return;
            }

            wasOpened = isShown;
            listener.onVisibilityChanged(isShown);
        }
    });
}

Works for me :)

NOTE: If you notice that the DefaultKeyboardDP does not fit your device play with the value and post a comment for everyone to know what should be the value... eventually we will get the correct value to fit all devices!

For more details, check out the implementation on Cyborg

get all keys set in memcached

Bash

To get list of keys in Bash, follow the these steps.

First, define the following wrapper function to make it simple to use (copy and paste into shell):

function memcmd() {
  exec {memcache}<>/dev/tcp/localhost/11211
  printf "%s\n%s\n" "$*" quit >&${memcache}
  cat <&${memcache}
}

Memcached 1.4.31 and above

You can use lru_crawler metadump all command to dump (most of) the metadata for (all of) the items in the cache.

As opposed to cachedump, it does not cause severe performance problems and has no limits on the amount of keys that can be dumped.

Example command by using the previously defined function:

memcmd lru_crawler metadump all

See: ReleaseNotes1431.


Memcached 1.4.30 and below

Get list of slabs by using items statistics command, e.g.:

memcmd stats items

For each slub class, you can get list of items by specifying slub id along with limit number (0 - unlimited):

memcmd stats cachedump 1 0
memcmd stats cachedump 2 0
memcmd stats cachedump 3 0
memcmd stats cachedump 4 0
...

Note: You need to do this for each memcached server.

To list all the keys from all stubs, here is the one-liner (per one server):

for id in $(memcmd stats items | grep -o ":[0-9]\+:" | tr -d : | sort -nu); do
    memcmd stats cachedump $id 0
done

Note: The above command could cause severe performance problems while accessing the items, so it's not advised to run on live.


Notes:

stats cachedump only dumps the HOT_LRU (IIRC?), which is managed by a background thread as activity happens. This means under a new enough version which the 2Q algo enabled, you'll get snapshot views of what's in just one of the LRU's.

If you want to view everything, lru_crawler metadump 1 (or lru_crawler metadump all) is the new mostly-officially-supported method that will asynchronously dump as many keys as you want. you'll get them out of order but it hits all LRU's, and unless you're deleting/replacing items multiple runs should yield the same results.

Source: GH-405.


Related:

Android Fastboot devices not returning device

TLDR - In addition to the previous responses. There might be a problem with the version of the fastboot command. Try to download the newest one via Android SDK Manager instead of default one available in the OS repository.

There is one more thing you can do to fix this issue. I had the similar problem when trying to flash Nexus Player. All the adb commands we working fine while in normal boot mode. However, after switching to fastboot mode I wasn't able to execute fastboot commands. My device was not visible in the output of the fastboot devices command. I've set the right rules in /etc/udev/rules.d/11-android.rules file. The lsusb command showed that the device has been pluged in.

The soultion was quite simple. I've downloaded the the fastboot via Android Studio's SDK Manager instead of using the default one available in Ubuntu packages.

All you need is sdkmanager. Download the Android SDK Platform Tools and replace the default /usr/bin/fastboot with the new one.

Android Studio: Unable to start the daemon process

If you are on mac try this :

cd Users/<Your name> 

Make sure that you are on the right path by looking for .gradle with

ls -la

then run that to delete .gradle

rm -rf .gradle

This will remove everything. Then launch your commande again and it will work !

How do I check out an SVN project into Eclipse as a Java project?

Here are the steps:

  • Install the subclipse plugin (provides svn connectivity in eclipse) and connect to the repository. Instructions here: http://subclipse.tigris.org/install.html
  • Go to File->New->Other->Under the SVN category, select Checkout Projects from SVN.
  • Select your project's root folder and select checkout as a project in the workspace.

It seems you are checking the .project file into the source repository. I would suggest not checking in the .project file so users can have their own version of the file. Also, if you use the subclipse plugin it allows you to check out and configure a source folder as a java project. This process creates the correct .project for you(with the java nature),

Using gradle to find dependency tree

Note that you may need to do something like ./gradlew <module_directory>:<module_name>:dependencies if the module has extra directory before reach its build.gradle. When in doubt, do ./gradlew tasks --all to check the name.

Java project in Eclipse: The type java.lang.Object cannot be resolved. It is indirectly referenced from required .class files

I had same problem in eclipse windows that I couldn't added dependant .class files from the JNI. In order resolve the same, I ported all the code to NetBeans IDE.

Can not add all the classes files from the JNI/JNA folder in Eclipse (JAVA, Windows 7)

Converting char* to float or double

printf("price: %d, %f",temp,ftemp); 
              ^^^

This is your problem. Since the arguments are type double and float, you should be using %f for both (since printf is a variadic function, ftemp will be promoted to double).

%d expects the corresponding argument to be type int, not double.

Variadic functions like printf don't really know the types of the arguments in the variable argument list; you have to tell it with the conversion specifier. Since you told printf that the first argument is supposed to be an int, printf will take the next sizeof (int) bytes from the argument list and interpret it as an integer value; hence the first garbage number.

Now, it's almost guaranteed that sizeof (int) < sizeof (double), so when printf takes the next sizeof (double) bytes from the argument list, it's probably starting with the middle byte of temp, rather than the first byte of ftemp; hence the second garbage number.

Use %f for both.

How do I encode/decode HTML entities in Ruby?

HTMLEntities can do it:

: jmglov@laurana; sudo gem install htmlentities
Successfully installed htmlentities-4.2.4
: jmglov@laurana;  irb
irb(main):001:0> require 'htmlentities'
=> []
irb(main):002:0> HTMLEntities.new.decode "&iexcl;I&#39;m highly&nbsp;annoyed with character references!"
=> "¡I'm highly annoyed with character references!"

How do I create a Java string from the contents of a file?

If you need a string processing (parallel processing) Java 8 has the great Stream API.

String result = Files.lines(Paths.get("file.txt"))
                    .parallel() // for parallel processing 
                    .map(String::trim) // to change line   
                    .filter(line -> line.length() > 2) // to filter some lines by a predicate                        
                    .collect(Collectors.joining()); // to join lines

More examples are available in JDK samples sample/lambda/BulkDataOperations that can be downloaded from Oracle Java SE 8 download page

Another one liner example

String out = String.join("\n", Files.readAllLines(Paths.get("file.txt")));

How to list all `env` properties within jenkins pipeline job?

Here's a quick script you can add as a pipeline job to list all environment variables:

node {
    echo(env.getEnvironment().collect({environmentVariable ->  "${environmentVariable.key} = ${environmentVariable.value}"}).join("\n"))
    echo(System.getenv().collect({environmentVariable ->  "${environmentVariable.key} = ${environmentVariable.value}"}).join("\n"))
}

This will list both system and Jenkins variables.

Why do I need to explicitly push a new branch?

At first check

Step-1: git remote -v
//if found git initialize then remove or skip step-2

Step-2: git remote rm origin
//Then configure your email address globally git

Step-3: git config --global user.email "[email protected]"

Step-4: git initial

Step-5: git commit -m "Initial Project"
//If already add project repo then skip step-6

Step-6: git remote add origin %repo link from bitbucket.org%

Step-7: git push -u origin master

How do I set <table> border width with CSS?

Like this:

border: 1px solid black;

Why it didn't work? because:

Always declare the border-style (solid in my example) property before the border-width property. An element must have borders before you can change the color.

Lazy Method for Reading Big File in Python?

I'm in a somewhat similar situation. It's not clear whether you know chunk size in bytes; I usually don't, but the number of records (lines) that is required is known:

def get_line():
     with open('4gb_file') as file:
         for i in file:
             yield i

lines_required = 100
gen = get_line()
chunk = [i for i, j in zip(gen, range(lines_required))]

Update: Thanks nosklo. Here's what I meant. It almost works, except that it loses a line 'between' chunks.

chunk = [next(gen) for i in range(lines_required)]

Does the trick w/o losing any lines, but it doesn't look very nice.

Calling a JavaScript function named in a variable

If it´s in the global scope it´s better to use:

function foo()
{
    alert('foo');
}

var a = 'foo';
window[a]();

than eval(). Because eval() is evaaaaaal.

Exactly like Nosredna said 40 seconds before me that is >.<

Parsing Query String in node.js

require('url').parse('/status?name=ryan', {parseQueryString: true}).query

returns

{ name: 'ryan' }

ref: https://nodejs.org/api/url.html#url_urlobject_query

Global Angular CLI version greater than local version

Two ways to solve this global and local angular CLI version issue.
1. Keep a specific angular-cli version for both environments.
2. Goto latest angular-cli version for both environments.

1. Specific angular-cli version

First, find out which angular version you want to keep on the global and local environment.

ng --version

for example: here we keeping local angular CLI version 8.3.27

So, we have to change the global version also on 8.3.27. use cmd>

npm install --save-dev @angular/[email protected] -g

here, '-g' flag for a set global angular-cli version.

2. Goto latest angular version for both CLI environment.

npm install --save-dev @angular/cli@latest -g  
npm install --save-dev @angular/cli@latest 

Convert blob URL to normal URL

A URL that was created from a JavaScript Blob can not be converted to a "normal" URL.

A blob: URL does not refer to data the exists on the server, it refers to data that your browser currently has in memory, for the current page. It will not be available on other pages, it will not be available in other browsers, and it will not be available from other computers.

Therefore it does not make sense, in general, to convert a Blob URL to a "normal" URL. If you wanted an ordinary URL, you would have to send the data from the browser to a server and have the server make it available like an ordinary file.

It is possible convert a blob: URL into a data: URL, at least in Chrome. You can use an AJAX request to "fetch" the data from the blob: URL (even though it's really just pulling it out of your browser's memory, not making an HTTP request).

Here's an example:

_x000D_
_x000D_
var blob = new Blob(["Hello, world!"], { type: 'text/plain' });_x000D_
var blobUrl = URL.createObjectURL(blob);_x000D_
_x000D_
var xhr = new XMLHttpRequest;_x000D_
xhr.responseType = 'blob';_x000D_
_x000D_
xhr.onload = function() {_x000D_
   var recoveredBlob = xhr.response;_x000D_
_x000D_
   var reader = new FileReader;_x000D_
_x000D_
   reader.onload = function() {_x000D_
     var blobAsDataUrl = reader.result;_x000D_
     window.location = blobAsDataUrl;_x000D_
   };_x000D_
_x000D_
   reader.readAsDataURL(recoveredBlob);_x000D_
};_x000D_
_x000D_
xhr.open('GET', blobUrl);_x000D_
xhr.send();
_x000D_
_x000D_
_x000D_

data: URLs are probably not what you mean by "normal" and can be problematically large. However they do work like normal URLs in that they can be shared; they're not specific to the current browser or session.

How to set up a Web API controller for multipart/form-data

You're getting HTTP 415 "The request entity's media type 'multipart/form-data' is not supported for this resource." because you haven't mention the correct content type in your request.

Difference between UTF-8 and UTF-16?

Simple way to differentiate UTF-8 and UTF-16 is to identify commonalities between them.

Other than sharing same unicode number for given character, each one is their own format.

UTF-8 try to represent, every unicode number given to character with one byte(If it is ASCII), else 2 two bytes, else 4 bytes and so on...

UTF-16 try to represent, every unicode number given to character with two byte to start with. If two bytes are not sufficient, then uses 4 bytes. IF that is also not sufficient, then uses 6 bytes.

Theoretically, UTF-16 is more space efficient, but in practical UTF-8 is more space efficient as most of the characters(98% of data) for processing are ASCII and UTF-8 try to represent them with single byte and UTF-16 try to represent them with 2 bytes.

Also, UTF-8 is superset of ASCII encoding. So every app that expects ASCII data would also accepted by UTF-8 processor. This is not true for UTF-16. UTF-16 could not understand ASCII, and this is big hurdle for UTF-16 adoption.

Another point to note is, all UNICODE as of now could be fit in 4 bytes of UTF-8 maximum(Considering all languages of world). This is same as UTF-16 and no real saving in space compared to UTF-8 ( https://stackoverflow.com/a/8505038/3343801 )

So, people use UTF-8 where ever possible.

SQL recursive query on self referencing table (Oracle)

Using the new nested query syntax

with q(name, id, parent_id, parent_name) as (
    select 
      t1.name, t1.id, 
      null as parent_id, null as parent_name 
    from t1
    where t1.id = 1
  union all
    select 
      t1.name, t1.id, 
      q.id as parent_id, q.name as parent_name 
    from t1, q
    where t1.parent_id = q.id
)
select * from q

String escape into XML

Following functions will do the work. Didn't test against XmlDocument, but I guess this is much faster.

public static string XmlEncode(string value)
{
    System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings 
    {
        ConformanceLevel = System.Xml.ConformanceLevel.Fragment
    };

    StringBuilder builder = new StringBuilder();

    using (var writer = System.Xml.XmlWriter.Create(builder, settings))
    {
        writer.WriteString(value);
    }

    return builder.ToString();
}

public static string XmlDecode(string xmlEncodedValue)
{
    System.Xml.XmlReaderSettings settings = new System.Xml.XmlReaderSettings
    {
        ConformanceLevel = System.Xml.ConformanceLevel.Fragment
    };

    using (var stringReader = new System.IO.StringReader(xmlEncodedValue))
    {
        using (var xmlReader = System.Xml.XmlReader.Create(stringReader, settings))
        {
            xmlReader.Read();
            return xmlReader.Value;
        }
    }
}

How to configure log4j.properties for SpringJUnit4ClassRunner?

I have the log4j.properties configured properly. That's not the problem. After a while I discovered that the problem was in Eclipse IDE which had an old build in "cache" and didn't create a new one (Maven dependecy problem). I had to build the project manually and now it works.

How can you print a variable name in python?

Rather than ask for details to a specific solution, I recommend describing the problem you face; I think you'll get better answers. I say this since there's almost certainly a better way to do whatever it is you're trying to do. Accessing variable names in this way is not commonly needed to solve problems in any language.

That said, all of your variable names are already in dictionaries which are accessible through the built-in functions locals and globals. Use the correct one for the scope you are inspecting.

One of the few common idioms for inspecting these dictionaries is for easy string interpolation:

>>> first = 'John'
>>> last = 'Doe'
>>> print '%(first)s %(last)s' % globals()
John Doe

This sort of thing tends to be a bit more readable than the alternatives even though it requires inspecting variables by name.

Hive query output to file

This will put the results in tab delimited file(s) under a directory:

INSERT OVERWRITE LOCAL DIRECTORY '/home/hadoop/YourTableDir'
ROW FORMAT DELIMITED
FIELDS TERMINATED BY '\t'
STORED AS TEXTFILE
SELECT * FROM table WHERE id > 100;

HTTP Error 404.3-Not Found in IIS 7.5

In my case, along with Mekanik's suggestions, I was receiving this error in Windows Server 2012 and I had to tick "HTTP Activation" in "Add Role Services".

Search for string and get count in vi editor

(similar as Gustavo said, but additionally: )

For any previously search, you can do simply:

:%s///gn

A pattern is not needed, because it is already in the search-register (@/).

"%" - do s/ in the whole file
"g" - search global (with multiple hits in one line)
"n" - prevents any replacement of s/ -- nothing is deleted! nothing must be undone!
(see: :help s_flag for more informations)

(This way, it works perfectly with "Search for visually selected text", as described in vim-wikia tip171)

What is the difference between static_cast<> and C style casting?

Since there are many different kinds of casting each with different semantics, static_cast<> allows you to say "I'm doing a legal conversion from one type to another" like from int to double. A plain C-style cast can mean a lot of things. Are you up/down casting? Are you reinterpreting a pointer?

Using Java with Microsoft Visual Studio 2012

theoretically it could be done by defining a custom build step to the VS project. And you can make a file template to create a new java file, don't know if you could have it throw things in the right package or not, so you may end up writing quite a bit of the stuff a java ide would throw in already. it's not impossible, but from experience (I've used xcode on mac, vs in windows, eclipse, netbeans, code::blocks, and ended up compiling from command line for both java and c++ a lot) it's easier just to learn the new ide.

if you are insistent, i found this: http://improve.dk/compiling-java-in-visual-studio/

i plan on following and trying to modify it to create a general template for java

if possible (meaning if i understand enough of what im doing) im goint to implement a custom wizard for java projects and files.

How to refer to Excel objects in Access VBA?

First you need to set a reference (Menu: Tools->References) to the Microsoft Excel Object Library then you can access all Excel Objects.

After you added the Reference you have full access to all Excel Objects. You need to add Excel in front of everything for example:

Dim xlApp as Excel.Application

Let's say you added an Excel Workbook Object in your Form and named it xLObject.

Here is how you Access a Sheet of this Object and change a Range

Dim sheet As Excel.Worksheet
Set sheet = xlObject.Object.Sheets(1)
sheet.Range("A1") = "Hello World"

(I copied the above from my answer to this question)

Another way to use Excel in Access is to start Excel through a Access Module (the way shahkalpesh described it in his answer)

Apache 2.4.3 (with XAMPP 1.8.1) not starting in windows 8

So here is the solution for this:

I check port 80 used by Skype, after that I changes port to 81 and also along with that somewhere i read this error may be because of SSL Port then I changed SSL port to 444. However this got resolved easily.

One most important thing to notice here, all the port changes should be done inside config files, for http port change: httpd.conf for SSL httpd-ssl.conf. Otherwise changes will not replicate to Apache, Sometime PC reboot is also required.

Edit: Make Apache use port 80 and make Skype communicate on other Port

For those who are struggling with Skype, want to change its port and to make Apache to use port 80.

No need to Re-Install, Here is simply how to change Skype Port

Goto: Tools > Options > Advanced > Connection

There you need to uncheck Use port 80 and 443 as alternative for incoming connections.

That's it, here is screen shot of it.

Changing Skype Port

R: Select values from data table in range

Construct some data

df <- data.frame( name=c("John", "Adam"), date=c(3, 5) )

Extract exact matches:

subset(df, date==3)

  name date
1 John    3

Extract matches in range:

subset(df, date>4 & date<6)

  name date
2 Adam    5

The following syntax produces identical results:

df[df$date>4 & df$date<6, ]

  name date
2 Adam    5

MySQL Error: #1142 - SELECT command denied to user

This error also arises for a syntax error occurred due to aliasing tablename.

For instance, when executed below query,

select * from a.table1, b.table2 where a.table1= b.table2

below error occurs:

MySQL Error: #1142. Response form the database. SELECT command denied to user "username@ip" for table "table1"

Solution : Syntax to alias tablename should be used proper, syntax solution for above instance >select * from table1 a, table2 b where a.table1= b.table2

docker entrypoint running bash script gets "permission denied"

If you do not use DockerFile, you can simply add permission as command line argument of the bash:

docker run -t <image>  /bin/bash -c "chmod +x /usr/src/app/docker-entrypoint.sh; /usr/src/app/docker-entrypoint.sh"

How do I configure modprobe to find my module?

You can make a symbolic link of your module to the standard path, so depmod will see it and you'll be able load it as any other module.

sudo ln -s /path/to/module.ko /lib/modules/`uname -r`
sudo depmod -a
sudo modprobe module

If you add the module name to /etc/modules it will be loaded any time you boot.

Anyway I think that the proper configuration is to copy the module to the standard paths.

Doctrine 2: Update query with query builder

I think you need to use Expr with ->set() (However THIS IS NOT SAFE and you shouldn't do it):

$qb = $this->em->createQueryBuilder();
$q = $qb->update('models\User', 'u')
        ->set('u.username', $qb->expr()->literal($username))
        ->set('u.email', $qb->expr()->literal($email))
        ->where('u.id = ?1')
        ->setParameter(1, $editId)
        ->getQuery();
$p = $q->execute();

It's much safer to make all your values parameters instead:

$qb = $this->em->createQueryBuilder();
$q = $qb->update('models\User', 'u')
        ->set('u.username', '?1')
        ->set('u.email', '?2')
        ->where('u.id = ?3')
        ->setParameter(1, $username)
        ->setParameter(2, $email)
        ->setParameter(3, $editId)
        ->getQuery();
$p = $q->execute();

Targeting only Firefox with CSS

Using -engine specific rules ensures effective browser targeting.

<style type="text/css">

    //Other browsers
    color : black;


    //Webkit (Chrome, Safari)
    @media screen and (-webkit-min-device-pixel-ratio:0) { 
        color:green;
    }

    //Firefox
    @media screen and (-moz-images-in-menus:0) {
        color:orange;
    }
</style>

//Internet Explorer
<!--[if IE]>
     <style type='text/css'>
        color:blue;
    </style>
<![endif]-->

Difference between two numpy arrays in python

This is pretty simple with numpy, just subtract the arrays:

diffs = array1 - array2

I get:

diffs == array([ 0.1,  0.2,  0.3])

Check if a String is in an ArrayList of Strings

temp = bankAccNos.contains(no) ? 1 : 2;

Visual Studio Expand/Collapse keyboard shortcuts

Visual Studio 2015:

Tools > Options > Settings > Environment > Keyboard

Defaults:

Edit.CollapsetoDefinitions: CTRL + M + O

Edit.CollapseCurrentRegion: CTRL + M +CTRL + S

Edit.ExpandAllOutlining: CTRL + M + CTRL + X

Edit.ExpandCurrentRegion: CTRL + M + CTRL + E

I like to set and use IntelliJ's shortcuts:

Edit.CollapsetoDefinitions: CTRL + SHIFT + NUM-

Edit.CollapseCurrentRegion: CTRL + NUM-

Edit.ExpandAllOutlining: CTRL + SHIFT + NUM+

Edit.ExpandCurrentRegion: CTRL + NUM+

How to playback MKV video in web browser?

HTML5 and the VLC web plugin were a no go for me but I was able to get this work using the following setup:

DivX Web Player (NPAPI browsers only)

AC3 Audio Decoder

And here is the HTML:

<embed id="divxplayer" type="video/divx" width="1024" height="768" 
src ="path_to_file" autoPlay=\"true\" 
pluginspage=\"http://go.divx.com/plugin/download/\"></embed>

The DivX player seems to allow for a much wider array of video and audio options than the native HTML5, so far I am very impressed by it.

Change Spinner dropdown icon

Try applying following style to your spinner using

style="@style/SpinnerTheme"

//Spinner Style:

<style name="SpinnerTheme" parent="android:Widget.Spinner">
    <item name="android:background">@drawable/bg_spinner</item>
</style>

//bg_spinner.xml Replace the arrow_down_gray with your arrow

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item>

        <layer-list>

            <item>
                <shape>
                    <gradient android:angle="90" android:endColor="#ffffff" android:startColor="#ffffff" android:type="linear" />

                    <stroke android:width="0.33dp" android:color="#0fb1fa" />

                    <corners android:radius="0dp" />

                    <padding android:bottom="3dp" android:left="3dp" android:right="3dp" android:top="3dp" />
                </shape>
            </item>

            <item android:right="5dp">

                <bitmap android:gravity="center_vertical|right" android:src="@drawable/arrow_down_gray" />

            </item>

        </layer-list>

    </item>

</selector>

How do I 'overwrite', rather than 'merge', a branch on another branch in Git?

What you want is this (actually the exact inverse of the currently accepted answer):

git checkout email
git merge --strategy-option=theirs staging  

What this does is:

  • email branch files will now be exactly the same as staging branch
  • email branch's history will be maintained
  • staging branch's history will be added to email history

As added value, if you don't want all of staging branch's history, you can use squash to summarize it into a single commit message.

git checkout email
git merge --squash --strategy-option=theirs staging  
git commit -m "Single commit message for squash branch's history here'

So in summary, what this second version does is:

  • email branch files will now be exactly the same as staging branch
  • email branch's history will be maintained
  • A single commit will be added on top of email branch's history. This commit will represent ALL the changes that took place in the staging branch

how to use Blob datatype in Postgres

I think this is the most comprehensive answer on the PostgreSQL wiki itself: https://wiki.postgresql.org/wiki/BinaryFilesInDB

Read the part with the title 'What is the best way to store the files in the Database?'

Is Java's assertEquals method reliable?

The JUnit assertEquals(obj1, obj2) does indeed call obj1.equals(obj2).

There's also assertSame(obj1, obj2) which does obj1 == obj2 (i.e., verifies that obj1 and obj2 are referencing the same instance), which is what you're trying to avoid.

So you're fine.

doGet and doPost in Servlets

The servlet container's implementation of HttpServlet.service() method will automatically forward to doGet() or doPost() as necessary, so you shouldn't need to override the service method.

how to delete a specific row in codeigniter?

It will come in the url so you can get it by two ways. Fist one

<td><?php echo anchor('textarea/delete_row', 'DELETE', 'id="$row->id"'); ?></td>
$id = $this->input->get('id');

2nd one.

$id = $this->uri->segment(3);

But in the second method you have to count the no. of segments in the url that on which no. your id come. 2,3,4 etc. then you have to pass. then in the ();

Delete a row in DataGridView Control in VB.NET

If dgv(11, dgv.CurrentRow.Index).Selected = True Then
    dgv.Rows.RemoveAt(dgv.CurrentRow.Index)
Else
    Exit Sub
End If

How do I add an image to a JButton

It looks like a location problem because that code is perfectly fine for adding the icon.

Since I don't know your folder structure, I suggest adding a simple check:

File imageCheck = new File("water.bmp");

if(imageCheck.exists()) 
    System.out.println("Image file found!")
else 
    System.out.println("Image file not found!");

This way if you ever get your path name wrong it will tell you instead of displaying nothing. Exception should be thrown if file would not exist, tho.

MySQL: Curdate() vs Now()

Just for the fun of it:

CURDATE() = DATE(NOW())

Or

NOW() = CONCAT(CURDATE(), ' ', CURTIME())

Array of Matrices in MATLAB

I was doing some volume rendering in octave (matlab clone) and building my 3D arrays (ie an array of 2d slices) using

buffer=zeros(1,512*512*512,"uint16");
vol=reshape(buffer,512,512,512);

Memory consumption seemed to be efficient. (can't say the same for the subsequent speed of computations :^)

Truncate a SQLite table if it exists?

**It is Simple, just follow 2 steps. Step #1. Fire query "Delete from tableName", It will delete all records from table.

Step #2. There is table named "sqlite_sequence" in Sqlite Database, just browse it and you can set sequence table wise to "0" so it will start from auto id "1".** See the screenshot attached.

enter image description here

IntelliJ does not show project folders

Select the module settings and do these changes, it will work

In File > Project Structure > Modules, click the "+" button,

add new module as per your project specific like Java or RUBY or something then apply and ok

Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."

On top of all the answers i found one nice solution. Actually The issue related to network connection fail for iOS 12 onword is because there is a bug in the iOS 12.0 onword. And it Yet to resolved. I had gone through the git hub community for AFNetworking related issue when app came from background and tries to do network call and fails on connection establish. I spend 3 days on this and tries many things to get to the root cause for this and found nothing. Finally i got some light in the dark when i red this blog https://github.com/AFNetworking/AFNetworking/issues/4279

It is saying that there is a bug in the iOS 12. Basically you cannot expect a network call to ever complete if the app os not in foreground. And due to this bug the network calls get dropped and we get network fails in logs.

My best suggestion to you is provide some delay when your app are coming from background to foreground and there is network call. Make that network call in the dispatch async with some delay. You'll never get network call drop or connection loss.

Do not wait for Apple to let this issue solve for iOS 12 as its still yet to fix. You may go with this workaround by providing some delay for your network request being its NSURLConnection, NSURLSession or AFNetworking or ALAMOFIRE. Cheers :)

How to calculate difference between two dates in oracle 11g SQL

basically the to_char(sysdate,'DDD') returns no of days from 1-jan-yyyy to sysdate so that if subtract two dates it will return that,you will get difference between two dates

select to_char(sysdate,'DDD') -to_char(to_date('19-08-1995','dd-mm-yyyy'),'DDD') from dual;

<hr> tag in Twitter Bootstrap not functioning correctly?

By default, the hr element in Twitter Bootstrap CSS file has a top and bottom margin of 18px. That's what creates a gap. If you want the gap to be smaller you'll need to adjust margin property of the hr element.

In your example, do something like this:

.container hr {
margin: 2px 0;
}

How does one reorder columns in a data frame?

The three top-rated answers have a weakness.

If your dataframe looks like this

df <- data.frame(Time=c(1,2), In=c(2,3), Out=c(3,4), Files=c(4,5))

> df
  Time In Out Files
1    1  2   3     4
2    2  3   4     5

then it's a poor solution to use

> df2[,c(1,3,2,4)]

It does the job, but you have just introduced a dependence on the order of the columns in your input.

This style of brittle programming is to be avoided.

The explicit naming of the columns is a better solution

data[,c("Time", "Out", "In", "Files")]

Plus, if you intend to reuse your code in a more general setting, you can simply

out.column.name <- "Out"
in.column.name <- "In"
data[,c("Time", out.column.name, in.column.name, "Files")]

which is also quite nice because it fully isolates literals. By contrast, if you use dplyr's select

data <- data %>% select(Time, out, In, Files)

then you'd be setting up those who will read your code later, yourself included, for a bit of a deception. The column names are being used as literals without appearing in the code as such.

Java String new line

It can be done several ways. I am mentioning 2 simple ways.

  1. Very simple way as below:

    System.out.println("I\nam\na\nboy");
    
  2. It can also be done with concatenation as below:

    System.out.println("I" + '\n' + "am" + '\n' + "a" + '\n' + "boy");
    

How to make Python script run as service?

I use this code to daemonize my applications. It allows you start/stop/restart the script using the following commands.

python myscript.py start
python myscript.py stop
python myscript.py restart

In addition to this I also have an init.d script for controlling my service. This allows you to automatically start the service when your operating system boots-up.

Here is a simple example to get your going. Simply move your code inside a class, and call it from the run function inside MyDeamon.

import sys
import time

from daemon import Daemon


class YourCode(object):
    def run(self):
        while True:
            time.sleep(1)


class MyDaemon(Daemon):
    def run(self):
        # Or simply merge your code with MyDaemon.
        your_code = YourCode()
        your_code.run()


if __name__ == "__main__":
    daemon = MyDaemon('/tmp/daemon-example.pid')
    if len(sys.argv) == 2:
        if 'start' == sys.argv[1]:
            daemon.start()
        elif 'stop' == sys.argv[1]:
            daemon.stop()
        elif 'restart' == sys.argv[1]:
            daemon.restart()
        else:
            print "Unknown command"
            sys.exit(2)
        sys.exit(0)
    else:
        print "usage: %s start|stop|restart" % sys.argv[0]
        sys.exit(2)

Upstart

If you are running an operating system that is using Upstart (e.g. CentOS 6) - you can also use Upstart to manage the service. If you use Upstart you can keep your script as is, and simply add something like this under /etc/init/my-service.conf

start on started sshd
stop on runlevel [!2345]

exec /usr/bin/python /opt/my_service.py
respawn

You can then use start/stop/restart to manage your service.

e.g.

start my-service
stop my-service
restart my-service

A more detailed example of working with upstart is available here.

Systemd

If you are running an operating system that uses Systemd (e.g. CentOS 7) you can take a look at the following Stackoverflow answer.

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip

You need to add the package containing the executable pg_config.

A prior answer should have details you need: pg_config executable not found

How to cancel a pull request on github?

GitHub now supports closing a pull request

Basically, you need to do the following steps:

  1. Visit the pull request page
  2. Click on the pull request
  3. Click the "close pull request" button

Example (button on the very bottom):

github close pull request

This way the pull request gets closed (and ignored), without merging it.

How to create an object property from a variable value in JavaScript?

As $scope is an object, you can try with JavaScript by:

$scope['something'] = 'hey'

It is equal to:

$scope.something = 'hey'

I created a fiddle to test.

'Invalid update: invalid number of rows in section 0

Here is some code from above added with actual action code (point 1 and 2);

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let deleteAction = UIContextualAction(style: .destructive, title: "Delete") { _, _, completionHandler in

        // 1. remove object from your array
        scannedItems.remove(at: indexPath.row)
        // 2. reload the table, otherwise you get an index out of bounds crash
        self.tableView.reloadData()

        completionHandler(true)
    }
    deleteAction.backgroundColor = .systemOrange
    let configuration = UISwipeActionsConfiguration(actions: [deleteAction])
    configuration.performsFirstActionWithFullSwipe = true
    return configuration
}

Compute a confidence interval from sample data

Start with looking up the z-value for your desired confidence interval from a look-up table. The confidence interval is then mean +/- z*sigma, where sigma is the estimated standard deviation of your sample mean, given by sigma = s / sqrt(n), where s is the standard deviation computed from your sample data and n is your sample size.

Change language for bootstrap DateTimePicker

1.First add this js file to your HTML.

<script th:src="@{${webLinkFactory.jsLibRootPath()}+'/bootstrap-datepicker.nl.min.js'}" charset="UTF-8"type="text/javascript"></script>

obviously after moment.min.js.

content of bootstrap-datepicker.nl.min.js will be

;(function($){
    $.fn.datepicker.dates['nl'] = {
        days: ["Zondag", "Maandag", "Dinsdag", "Woensdag", "Donderdag", "Vrijdag", "Zaterdag", "Zondag"],
        daysShort: ["Zon", "Man", "Din", "Woe", "Don", "Vri", "Zat", "Zon"],
        daysMin: ["Zo", "Ma", "Di", "Wo", "Do", "Vr", "Za", "Zo"],
        months: ["Januari", "Februari", "Maart", "April", "Mei", "Juni", "Juli", "Augustus", "September", "Oktober", "November", "December"],
        monthsShort: ["Jan", "Feb", "Mrt", "Apr", "Mei", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"],
        today: "Vandaag",
        suffix: [],
        meridiem: []
    };
    $.fn.datetimepicker.dates['nl'] = {
        days: ["Zondag", "Maandag", "Dinsdag", "Woensdag", "Donderdag", "Vrijdag", "Zaterdag", "Zondag"],
        daysShort: ["Zon", "Man", "Din", "Woe", "Don", "Vri", "Zat", "Zon"],
        daysMin: ["Zo", "Ma", "Di", "Wo", "Do", "Vr", "Za", "Zo"],
        months: ["Januari", "Februari", "Maart", "April", "Mei", "Juni", "Juli", "Augustus", "September", "Oktober", "November", "December"],
        monthsShort: ["Jan", "Feb", "Mrt", "Apr", "Mei", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"],
        today: "Vandaag",
        suffix: [],
        meridiem: []
    };
}(jQuery));

2.set this line in the ready function of your js file.

$(document).ready(function () {
    $.fn.datetimepicker.defaults.language = 'nl';
}

3.initialize your datetimepicker in this way

$(this).datetimepicker({
                        format: "yyyy-mm-dd hh:ii",
                        autoclose: true,
                        weekStart: 1,
                        locale: 'nl',
                        language: 'nl'
                    });

following this steps i was able to convert my english datepicker and datetimepicker to dutch successfully.

How to pass parameters to the DbContext.Database.ExecuteSqlCommand method?

If your underlying database data types are varchar then you should stick with the approach below. Otherwise the query would have a huge performance impact.

var firstName = new SqlParameter("@firstName", System.Data.SqlDbType.VarChar, 20)
                            {
                                Value = "whatever"
                            };

var id = new SqlParameter("@id", System.Data.SqlDbType.Int)
                            {
                                Value = 1
                            };
ctx.Database.ExecuteSqlCommand(@"Update [User] SET FirstName = @firstName WHERE Id = @id"
                               , firstName, id);

You can check Sql profiler to see the difference.

javascript date to string

use this polyfill https://github.com/UziTech/js-date-format

var d = new Date("1/1/2014 10:00 am");
d.format("DDDD 'the' DS 'of' MMMM YYYY h:mm TT");
//output: Wednesday the 1st of January 2014 10:00 AM

Turn off auto formatting in Visual Studio

VS2015 settings that helped me prevent auto formatting:

(and Tools > Options > Text Editor > Basic > Advanced, just like Tango91 suggested)

enter image description here

How to check SQL Server version

select charindex(  'Express',@@version)

if this value is 0 is not a express edition

How to set an environment variable only for the duration of the script?

Just put

export HOME=/blah/whatever

at the point in the script where you want the change to happen. Since each process has its own set of environment variables, this definition will automatically cease to have any significance when the script terminates (and with it the instance of bash that has a changed environment).

Using UPDATE in stored procedure with optional parameters

   UPDATE tbl_ClientNotes
    SET 
      ordering=ISNULL@ordering,ordering), 
      title=isnull(@title,title), 
      content=isnull(@content,content)
    WHERE id=@id

I think I remember seeing before that if you are updating to the same value SQL Server will actually recognize this and won't do an unnecessary write.

Using PUT method in HTML form

To set methods PUT and DELETE I perform as following:

<form
  method="PUT"
  action="domain/route/param?query=value"
>
  <input type="hidden" name="delete_id" value="1" />
  <input type="hidden" name="put_id" value="1" />
  <input type="text" name="put_name" value="content_or_not" />
  <div>
    <button name="update_data">Save changes</button>
    <button name="remove_data">Remove</button>
  </div>
</form>
<hr>
<form
  method="DELETE"
  action="domain/route/param?query=value"
>
  <input type="hidden" name="delete_id" value="1" />
  <input type="text" name="delete_name" value="content_or_not" />
  <button name="delete_data">Remove item</button>
</form>

Then JS acts to perform the desired methods:

<script>
   var putMethod = ( event ) => {
     // Prevent redirection of Form Click
     event.preventDefault();
     var target = event.target;
     while ( target.tagName != "FORM" ) {
       target = target.parentElement;
     } // While the target is not te FORM tag, it looks for the parent element
     // The action attribute provides the request URL
     var url = target.getAttribute( "action" );

     // Collect Form Data by prefix "put_" on name attribute
     var bodyForm = target.querySelectorAll( "[name^=put_]");
     var body = {};
     bodyForm.forEach( element => {
       // I used split to separate prefix from worth name attribute
       var nameArray = element.getAttribute( "name" ).split( "_" );
       var name = nameArray[ nameArray.length - 1 ];
       if ( element.tagName != "TEXTAREA" ) {
         var value = element.getAttribute( "value" );
       } else {
       // if element is textarea, value attribute may return null or undefined
         var value = element.innerHTML;
       }
       // all elements with name="put_*" has value registered in body object
       body[ name ] = value;
     } );
     var xhr = new XMLHttpRequest();
     xhr.open( "PUT", url );
     xhr.setRequestHeader( "Content-Type", "application/json" );
     xhr.onload = () => {
       if ( xhr.status === 200 ) {
       // reload() uses cache, reload( true ) force no-cache. I reload the page to make "redirects normal effect" of HTML form when submit. You can manipulate DOM instead.
         location.reload( true );
       } else {
         console.log( xhr.status, xhr.responseText );
       }
     }
     xhr.send( body );
   }

   var deleteMethod = ( event ) => {
     event.preventDefault();
     var confirm = window.confirm( "Certeza em deletar este conteúdo?" );
     if ( confirm ) {
       var target = event.target;
       while ( target.tagName != "FORM" ) {
         target = target.parentElement;
       }
       var url = target.getAttribute( "action" );
       var xhr = new XMLHttpRequest();
       xhr.open( "DELETE", url );
       xhr.setRequestHeader( "Content-Type", "application/json" );
       xhr.onload = () => {
         if ( xhr.status === 200 ) {
           location.reload( true );
           console.log( xhr.responseText );
         } else {
           console.log( xhr.status, xhr.responseText );
         }
       }
       xhr.send();
     }
   }
</script>

With these functions defined, I add a event listener to the buttons which make the form method request:

<script>
  document.querySelectorAll( "[name=update_data], [name=delete_data]" ).forEach( element => {
    var button = element;
    var form = element;
    while ( form.tagName != "FORM" ) {
      form = form.parentElement;
    }
    var method = form.getAttribute( "method" );
    if ( method == "PUT" ) {
      button.addEventListener( "click", putMethod );
    }
    if ( method == "DELETE" ) {
      button.addEventListener( "click", deleteMethod );
    }
  } );
</script>

And for the remove button on the PUT form:

<script>
  document.querySelectorAll( "[name=remove_data]" ).forEach( element => {
    var button = element;
    button.addEventListener( "click", deleteMethod );
</script>

_ - - - - - - - - - - -

This article https://blog.garstasio.com/you-dont-need-jquery/ajax/ helps me a lot!

Beyond this, you can set postMethod function and getMethod to handle POST and GET submit methods as you like instead browser default behavior. You can do whatever you want instead use location.reload(), like show message of successful changes or successful deletion.

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

JSFiddle: https://jsfiddle.net/enriquerene/d6jvw52t/53/

How do I rename the android package name?

This modification needs three steps :

  1. Change the package name in the manifest
  2. Refactor the name of your package with right click -> refactor -> rename in the tree view, then Android studio will display a window, select "rename package"
  3. Change manually the application Id in the build.gradle file : android / defaultconfig / application ID

Then clean / rebuild the project

How to escape single quotes within single quoted strings

I just use shell codes.. e.g. \x27 or \\x22 as applicable. No hassle, ever really.

Simple JavaScript Checkbox Validation

You can do something like this:

<form action="../" onsubmit="return checkCheckBoxes(this);">
    <p><input type="CHECKBOX" name="MyCheckbox" value="This..."> This...</p>
    <p><input type="SUBMIT" value="Submit!"></p>
</form>

<script type="text/javascript" language="JavaScript">
<!--
function checkCheckBoxes(theForm) {
    if (
    theForm.MyCheckbox.checked == false) 
    {
        alert ('You didn\'t choose any of the checkboxes!');
        return false;
    } else {    
        return true;
    }
}
//-->
</script> 

http://lab.artlung.com/validate-checkbox/

Although less legible imho, this can be done without a separate function definition like this:

<form action="../" onsubmit="if (this.MyCheckbox.checked == false) { alert ('You didn\'t choose any of the checkboxes!'); return false; } else { return true; }">
    <p><input type="CHECKBOX" name="MyCheckbox" value="This..."> This...</p>
    <p><input type="SUBMIT" value="Submit!"></p>
</form>

jQuery .each() index?

jQuery takes care of this for you. The first argument to your .each() callback function is the index of the current iteration of the loop. The second being the current matched DOM element So:

$('#list option').each(function(index, element){
  alert("Iteration: " + index)
});

Any implementation of Ordered Set in Java?

You might also get some utility out of a Bidirectional Map like the BiMap from Google Guava

With a BiMap, you can pretty efficiently map an Integer (for random index access) to any other object type. BiMaps are one-to-one, so any given integer has, at most, one element associated with it, and any element has one associated integer. It's cleverly underpinned by two HashTable instances, so it uses almost double the memory, but it's a lot more efficient than a custom List as far as processing because contains() (which gets called when an item is added to check if it already exists) is a constant-time and parallel-friendly operation like HashSet's, while List's implementation is a LOT slower.

Best way to list files in Java, sorted by Date Modified?

A slightly more modernized version of the answer of @jason-orendorf.

Note: this implementation keeps the original array untouched, and returns a new array. This might or might not be desirable.

files = Arrays.stream(files)
        .map(FileWithLastModified::ofFile)
        .sorted(comparingLong(FileWithLastModified::lastModified))
        .map(FileWithLastModified::file)
        .toArray(File[]::new);

private static class FileWithLastModified {
    private final File file;
    private final long lastModified;

    private FileWithLastModified(File file, long lastModified) {
        this.file = file;
        this.lastModified = lastModified;
    }

    public static FileWithLastModified ofFile(File file) {
        return new FileWithLastModified(file, file.lastModified());
    }

    public File file() {
        return file;
    }

    public long lastModified() {
        return lastModified;
    }
}

But again, all credits to @jason-orendorf for the idea!

How do I overload the [] operator in C#

The [] operator is called an indexer. You can provide indexers that take an integer, a string, or any other type you want to use as a key. The syntax is straightforward, following the same principles as property accessors.

For example, in your case where an int is the key or index:

public int this[int index]
{
    get => GetValue(index);
}

You can also add a set accessor so that the indexer becomes read and write rather than just read-only.

public int this[int index]
{
    get => GetValue(index);
    set => SetValue(index, value);
}

If you want to index using a different type, you just change the signature of the indexer.

public int this[string index]
...

Kill some processes by .exe file name

Quick Answer:

foreach (var process in Process.GetProcessesByName("whatever"))
{
    process.Kill();
}

(leave off .exe from process name)

Call a child class method from a parent class object

Many of the answers here are suggesting implementing variant types using "Classical Object-Oriented Decomposition". That is, anything which might be needed on one of the variants has to be declared at the base of the hierarchy. I submit that this is a type-safe, but often very bad, approach. You either end up exposing all internal properties of all the different variants (most of which are "invalid" for each particular variant) or you end up cluttering the API of the hierarchy with tons of procedural methods (which means you have to recompile every time a new procedure is dreamed up).

I hesitate to do this, but here is a shameless plug for a blog post I wrote that outlines about 8 ways to do variant types in Java. They all suck, because Java sucks at variant types. So far the only JVM language that gets it right is Scala.

http://jazzjuice.blogspot.com/2010/10/6-things-i-hate-about-java-or-scala-is.html

The Scala creators actually wrote a paper about three of the eight ways. If I can track it down, I'll update this answer with a link.

UPDATE: found it here.

AppendChild() is not a function javascript

 function createQuestionPanel() {

        var element = document.createElement("Input");
        element.setAttribute("type", "button");
        element.setAttribute("value", "button");
        element.setAttribute("name", "button");


        var div = document.createElement("div"); <------- Create DIv Node
        div.appendChild(element);<--------------------
        document.body.appendChild(div) <------------- Then append it to body

    }

    function formvalidate() {

    }

CSS Styling for a Button: Using <input type="button> instead of <button>

In your .button CSS, try display:inline-block. See this JSFiddle

PHP - remove <img> tag from string

Try dropping the \ in front of the >.

Edit: I just tested your regex and it works fine. This is what I used:

<?
    $content = "this is something with an <img src=\"test.png\"/> in it.";
    $content = preg_replace("/<img[^>]+\>/i", "(image) ", $content); 
    echo $content;
?>

The result is:

this is something with an (image)  in it.

How to move the layout up when the soft keyboard is shown android

This is all that is needed:

<activity android:windowSoftInputMode="adjustResize"> </activity>

Set max-height on inner div so scroll bars appear, but not on parent div

set this :

#inner-right {
    height: 100%;
    max-height: 96%;//change here
    overflow: auto;
    background: ivory;
}

this will solve your problem.

CSS flexbox vertically/horizontally center image WITHOUT explicitely defining parent height

Without explicitly defining the height I determined I need to apply the flex value to the parent and grandparent div elements...

<div style="display: flex;">
<div style="display: flex;">
 <img alt="No, he'll be an engineer." src="theknack.png" style="margin: auto;" />
</div>
</div>

If you're using a single element (e.g. dead-centered text in a single flex element) use the following:

align-items: center;
display: flex;
justify-content: center;

C# - Fill a combo box with a DataTable

string strConn = "Data Source=SEZSW08;Initial Catalog=Nidhi;Integrated Security=True";
SqlConnection Con = new SqlConnection(strConn);
Con.Open();
string strCmd = "select companyName from companyinfo where CompanyName='" + cmbCompName.SelectedValue + "';";
SqlDataAdapter da = new SqlDataAdapter(strCmd, Con);
DataSet ds = new DataSet();
Con.Close();
da.Fill(ds);
cmbCompName.DataSource = ds;
cmbCompName.DisplayMember = "CompanyName";
cmbCompName.ValueMember = "CompanyName";
//cmbCompName.DataBind();
cmbCompName.Enabled = true;

HTML span align center not working?

A div is a block element, and will span the width of the container unless a width is set. A span is an inline element, and will have the width of the text inside it. Currently, you are trying to set align as a CSS property. Align is an attribute.

<span align="center" style="border:1px solid red;">
    This is some text in a div element!
</span>

However, the align attribute is deprecated. You should use the CSS text-align property on the container.

<div style="text-align: center;">
    <span style="border:1px solid red;">
        This is some text in a div element!
    </span>
</div>

The container 'Maven Dependencies' references non existing library - STS

I finally found my maven repo mirror is down. I changed to another one, problem solved.

Abstraction vs Encapsulation in Java

Abstraction is about identifying commonalities and reducing features that you have to work with at different levels of your code.

e.g. I may have a Vehicle class. A Car would derive from a Vehicle, as would a Motorbike. I can ask each Vehicle for the number of wheels, passengers etc. and that info has been abstracted and identified as common from Cars and Motorbikes.

In my code I can often just deal with Vehicles via common methods go(), stop() etc. When I add a new Vehicle type later (e.g. Scooter) the majority of my code would remain oblivious to this fact, and the implementation of Scooter alone worries about Scooter particularities.

Where can I get Google developer key

First activate Google+ API, then you will get "Simple API access" box, from there you can get developer key as API key https://code.google.com/apis/console/?api=plus or read this: http://code.google.com/p/google-api-php-client/wiki/OAuth2

How to extract multiple JSON objects from one file?

Use a json array, in the format:

[
{"ID":"12345","Timestamp":"20140101", "Usefulness":"Yes",
  "Code":[{"event1":"A","result":"1"},…]},
{"ID":"1A35B","Timestamp":"20140102", "Usefulness":"No",
  "Code":[{"event1":"B","result":"1"},…]},
{"ID":"AA356","Timestamp":"20140103", "Usefulness":"No",
  "Code":[{"event1":"B","result":"0"},…]},
...
]

Then import it into your python code

import json

with open('file.json') as json_file:

    data = json.load(json_file)

Now the content of data is an array with dictionaries representing each of the elements.

You can access it easily, i.e:

data[0]["ID"]

How to get client IP address in Laravel 5+

I used the Sebastien Horin function getIp and request()->ip() (at global request), because to localhost the getIp function return null:

$this->getIp() ?? request()->ip();

The getIp function:

public function getIp(){
foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key){
    if (array_key_exists($key, $_SERVER) === true){
        foreach (explode(',', $_SERVER[$key]) as $ip){
            $ip = trim($ip); // just to be safe
            if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false){
                return $ip;
            }
        }
    }
}

}

Extract subset of key-value pairs from Python dictionary object?

solution

from operator import itemgetter
from typing import List, Dict, Union


def subdict(d: Union[Dict, List], columns: List[str]) -> Union[Dict, List[Dict]]:
    """Return a dict or list of dicts with subset of 
    columns from the d argument.
    """
    getter = itemgetter(*columns)

    if isinstance(d, list):
        result = []
        for subset in map(getter, d):
            record = dict(zip(columns, subset))
            result.append(record)
        return result
    elif isinstance(d, dict):
        return dict(zip(columns, getter(d)))

    raise ValueError('Unsupported type for `d`')

examples of use

# pure dict

d = dict(a=1, b=2, c=3)
print(subdict(d, ['a', 'c']))

>>> In [5]: {'a': 1, 'c': 3}
# list of dicts

d = [
    dict(a=1, b=2, c=3),
    dict(a=2, b=4, c=6),
    dict(a=4, b=8, c=12),
]

print(subdict(d, ['a', 'c']))

>>> In [5]: [{'a': 1, 'c': 3}, {'a': 2, 'c': 6}, {'a': 4, 'c': 12}]

Why does npm install say I have unmet dependencies?

I believe it is because the dependency resolution is a bit broken, see https://github.com/npm/npm/issues/1341#issuecomment-20634338

Following are the possible solution :

  1. Manually need to install the top-level modules, containing unmet dependencies: npm install [email protected]

  2. Re-structure your package.json. Place all the high-level modules (serves as a dependency for others modules) at the bottom.

  3. Re-run the npm install command.

The problem could be caused by npm's failure to download all the package due to timed-out or something else.

Note: You can also install the failed packages manually as well using npm install [email protected].

Before running npm install, performing the following steps may help:

  • remove node_modules using rm -rf node_modules/
  • run npm cache clean

Why 'removing node_modules' sometimes is necessary? When a nested module fails to install during npm install, subsequent npm install won't detect those missing nested dependencies.

If that's the case, sometimes it's sufficient to remove the top-level dependency of those missing nested modules, and running npm install again. See

How to solve "Fatal error: Class 'MySQLi' not found"?

on ubuntu:

sudo apt-get install php-mysql
sudo service apache2 restart

How to call a REST web service API from JavaScript?

I'm surprised nobody has mentioned the new Fetch API, supported by all browsers except IE11 at the time of writing. It simplifies the XMLHttpRequest syntax you see in many of the other examples.

The API includes a lot more, but start with the fetch() method. It takes two arguments:

  1. A URL or an object representing the request.
  2. Optional init object containing the method, headers, body etc.

Simple GET:

const userAction = async () => {
  const response = await fetch('http://example.com/movies.json');
  const myJson = await response.json(); //extract JSON from the http response
  // do something with myJson
}

Recreating the previous top answer, a POST:

const userAction = async () => {
  const response = await fetch('http://example.com/movies.json', {
    method: 'POST',
    body: myBody, // string or object
    headers: {
      'Content-Type': 'application/json'
    }
  });
  const myJson = await response.json(); //extract JSON from the http response
  // do something with myJson
}

diff to output only the file names

From the diff man page:

-q   Report only whether the files differ, not the details of the differences.
-r   When comparing directories, recursively compare any subdirectories found.

Example command:

diff -qr dir1 dir2

Example output (depends on locale):

$ ls dir1 dir2
dir1:
same-file  different  only-1

dir2:
same-file  different  only-2
$ diff -qr dir1 dir2
Files dir1/different and dir2/different differ
Only in dir1: only-1
Only in dir2: only-2

Run script with rc.local: script works, but not at boot

In this example of a rc.local script I use io redirection at the very first line of execution to my own log file:

#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.

exec 2> /tmp/rc.local.log  # send stderr from rc.local to a log file
exec 1>&2                      # send stdout to the same log file
set -x                         # tell sh to display commands before execution

/opt/stuff/somefancy.error.script.sh

exit 0

Is it possible to use std::string in a constexpr?

As of C++20, yes.

As of C++17, you can use string_view:

constexpr std::string_view sv = "hello, world";

A string_view is a string-like object that acts as an immutable, non-owning reference to any sequence of char objects.

How do I use T-SQL's Case/When?

If logical test is against a single column then you could use something like

USE AdventureWorks2012;  
GO  
SELECT   ProductNumber, Category =  
      CASE ProductLine  
         WHEN 'R' THEN 'Road'  
         WHEN 'M' THEN 'Mountain'  
         WHEN 'T' THEN 'Touring'  
         WHEN 'S' THEN 'Other sale items'  
         ELSE 'Not for sale'  
      END,  
   Name  
FROM Production.Product  
ORDER BY ProductNumber;  
GO  

More information - https://docs.microsoft.com/en-us/sql/t-sql/language-elements/case-transact-sql?view=sql-server-2017

How do I fix a NoSuchMethodError?

I've encountered this error too.

My problem was that I've changed a method's signature, something like

void invest(Currency money){...}

into

void invest(Euro money){...}

This method was invoked from a context similar to

public static void main(String args[]) {
    Bank myBank = new Bank();

    Euro capital = new Euro();
    myBank.invest(capital);
}

The compiler was silent with regard to warnings/ errors, as capital is both Currency as well as Euro.

The problem appeared due to the fact that I only compiled the class in which the method was defined - Bank, but not the class from which the method is being called from, which contains the main() method.

This issue is not something you might encounter too often, as most frequently the project is rebuilt mannually or a Build action is triggered automatically, instead of just compiling the one modified class.

My usecase was that I generated a .jar file which was to be used as a hotfix, that did not contain the App.class as this was not modified. It made sense to me not to include it as I kept the initial argument's base class trough inheritance.

The thing is, when you compile a class, the resulting bytecode is kind of static, in other words, it's a hard-reference.

The original disassembled bytecode (generated with the javap tool) looks like this:

 #7 = Methodref          #2.#22         // Bank.invest:(LCurrency;)V

After the ClassLoader loads the new compiled Bank.class, it will not find such a method, it appears as if it was removed and not changed, thus the named error.

Hope this helps.

Disabled form inputs do not appear in the request

Semantically this feels like the correct behaviour

I'd be asking myself "Why do I need to submit this value?"

If you have a disabled input on a form, then presumably you do not want the user changing the value directly

Any value that is displayed in a disabled input should either be

  1. output from a value on the server that produced the form, or
  2. if the form is dynamic, be calculable from the other inputs on the form

Assuming that the server processing the form is the same as the server serving it, all the information to reproduce the values of the disabled inputs should be available at processing

In fact, to preserve data integrity - even if the value of the disabled input was sent to the processing server, you should really be validating it. This validation would require the same level of information as you would need to reproduce the values anyway!

I'd almost argue that read-only inputs shouldn't be sent in the request either

Happy to be corrected, but all the use cases I can think of where read-only/disabled inputs need to be submitted are really just styling issues in disguise

VBA Count cells in column containing specified value

Not what you asked but may be useful nevertheless.

Of course you can do the same thing with matrix formulas. Just read the result of the cell that contains:

Cell A1="Text to search"
Cells A2:C20=Range to search for

=COUNT(SEARCH(A1;A2:C20;1))

Remember that entering matrix formulas needs CTRL+SHIFT+ENTER, not just ENTER. After, it should look like :

{=COUNT(SEARCH(A1;A2:C20;1))}

How to solve java.lang.OutOfMemoryError trouble in Android

You should implement an LRU cache manager when dealing with bitmap

http://developer.android.com/reference/android/util/LruCache.html http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html When should I recycle a bitmap using LRUCache?

OR

Use a tier library like Universal Image Loader :

https://github.com/nostra13/Android-Universal-Image-Loader

EDIT :

Now when dealing with images and most of the time with bitmap I use Glide which let you configure a Glide Module and a LRUCache

https://github.com/bumptech/glide

How do I run a Java program from the command line on Windows?

enter image description here STEP 1: FIRST OPEN THE COMMAND PROMPT WHERE YOUR FILE IS LOCATED. (right click while pressing shift)
STEP 2: THEN USE THE FOLLOWING COMMANDS TO EXECUTE. (lets say the file and class name to be executed is named as Student.java)The example program is in the picture background.

     javac Student.java
     java Student

enter image description here

What is the best Java email address validation method?

Although there are many alternatives to Apache commons, their implementations are rudimentary at best (like Apache commons' implementation itself) and even dead wrong in other cases.

I'd also stay away from so called simple 'non-restrictive' regex; there's no such thing. For example @ is allowed multiple times depending on context, how do you know the required one is there? Simple regex won't understand it, even though the email should be valid. Anything more complex becomes error-prone or even contain hidden performance killers. How are you going to maintain something like this?

The only comprehensive RFC compliant regex based validator I'm aware of is email-rfc2822-validator with its 'refined' regex appropriately named Dragons.java. It supports only the older RFC-2822 spec though, although appropriate enough for modern needs (RFC-5322 updates it in areas already out of scope for daily use cases).

But really what you want is a lexer that properly parses a string and breaks it up into the component structure according to the RFC grammar. EmailValidator4J seems promising in that regard, but is still young and limited.

Another option you have is using a webservice such as Mailgun's battle-tested validation webservice or Mailboxlayer API (just took the first Google results). It is not strictly RFC compliant, but works well enough for modern needs.

EPPlus - Read Excel Table

This is my working version. Note that the resolvers code is not shown but are a spin on my implementation which allows columns to be resolved even though they are named slightly differently in each worksheet.

public static IEnumerable<T> ToArray<T>(this ExcelWorksheet worksheet, List<PropertyNameResolver> resolvers) where T : new()
{

  // List of all the column names
  var header = worksheet.Cells.GroupBy(cell => cell.Start.Row).First();

  // Get the properties from the type your are populating
  var properties = typeof(T).GetProperties().ToList();


  var start = worksheet.Dimension.Start;
  var end = worksheet.Dimension.End;

  // Resulting list
  var list = new List<T>();

  // Iterate the rows starting at row 2 (ie start.Row + 1)
  for (int row = start.Row + 1; row <= end.Row; row++)
  {
    var instance = new T();
    for (int col = start.Column; col <= end.Column; col++)
    {
      object value = worksheet.Cells[row, col].Text;

      // Get the column name zero based (ie col -1)
      var column = (string)header.Skip(col - 1).First().Value;

      // Gets the corresponding property to set
      var property = properties.Property(resolvers, column);

      try
      {
        var propertyName = property.PropertyType.IsGenericType
          ? property.PropertyType.GetGenericArguments().First().FullName
          : property.PropertyType.FullName;


        // Implement setter code as needed. 
        switch (propertyName)
        {
          case "System.String":
            property.SetValue(instance, Convert.ToString(value));
            break;
          case "System.Int32":
            property.SetValue(instance, Convert.ToInt32(value));
            break;
          case "System.DateTime":
            if (DateTime.TryParse((string) value, out var date))
            {
              property.SetValue(instance, date);
            }
            property.SetValue(instance, FromExcelSerialDate(Convert.ToInt32(value)));
            break;
          case "System.Boolean":
            property.SetValue(instance, (int)value == 1);
            break;
        }
      }
      catch (Exception e)
      {
        // instance property is empty because there was a problem.
      }

    } 
    list.Add(instance);
  }
  return list;
}

// Utility function taken from the above post's inline function.
public static DateTime FromExcelSerialDate(int excelDate)
{
  if (excelDate < 1)
    throw new ArgumentException("Excel dates cannot be smaller than 0.");

  var dateOfReference = new DateTime(1900, 1, 1);

  if (excelDate > 60d)
    excelDate = excelDate - 2;
  else
    excelDate = excelDate - 1;
  return dateOfReference.AddDays(excelDate);
}

Check/Uncheck all the checkboxes in a table

All CheckBox Checked

$("input[type=checkbox]").prop('checked', true);

How to fix an UnsatisfiedLinkError (Can't find dependent libraries) in a JNI project

If you load a 32 bit version of your dll with a 64 bit JRE you could have this issue. This was my case.

When to use HashMap over LinkedList or ArrayList and vice-versa

The downfall of ArrayList and LinkedList is that when iterating through them, depending on the search algorithm, the time it takes to find an item grows with the size of the list.

The beauty of hashing is that although you sacrifice some extra time searching for the element, the time taken does not grow with the size of the map. This is because the HashMap finds information by converting the element you are searching for, directly into the index, so it can make the jump.

Long story short... LinkedList: Consumes a little more memory than ArrayList, low cost for insertions(add & remove) ArrayList: Consumes low memory, but similar to LinkedList, and takes extra time to search when large. HashMap: Can perform a jump to the value, making the search time constant for large maps. Consumes more memory and takes longer to find the value than small lists.

Java collections convert a string to a list of characters

IntStream can be used to access each character and add them to the list.

String str = "abc";
List<Character> charList = new ArrayList<>();
IntStream.range(0,str.length()).forEach(i -> charList.add(str.charAt(i)));

Append integer to beginning of list in Python

None of these worked for me. I converted the first element to be part of a series (a single element series), and converted the second element also to be a series, and used append function.

l = ((pd.Series(<first element>)).append(pd.Series(<list of other elements>))).tolist()

JavaFX How to set scene background image

In addition to @Elltz answer, we can use both fill and image for background:

someNode.setBackground(
            new Background(
                    Collections.singletonList(new BackgroundFill(
                            Color.WHITE, 
                            new CornerRadii(500), 
                            new Insets(10))),
                    Collections.singletonList(new BackgroundImage(
                            new Image("image/logo.png", 100, 100, false, true),
                            BackgroundRepeat.NO_REPEAT,
                            BackgroundRepeat.NO_REPEAT,
                            BackgroundPosition.CENTER,
                            BackgroundSize.DEFAULT))));

Use

setBackground(
                new Background(
                        Collections.singletonList(new BackgroundFill(
                                Color.WHITE,
                                new CornerRadii(0),
                                new Insets(0))),
                        Collections.singletonList(new BackgroundImage(
                                new Image("file:clouds.jpg", 100, 100, false, true),
                                BackgroundRepeat.NO_REPEAT,
                                BackgroundRepeat.NO_REPEAT,
                                BackgroundPosition.DEFAULT,
                                new BackgroundSize(1.0, 1.0, true, true, false, false)
                        ))));

(different last argument) to make the image full-window size.

How to grep a string in a directory and all its subdirectories?

If your grep supports -R, do:

grep -R 'string' dir/

If not, then use find:

find dir/ -type f -exec grep -H 'string' {} +

fatal error LNK1104: cannot open file 'kernel32.lib'

Check the VC++ directories, in VS 2010 these can be found in your project properties. Check whether $(WindowsSdkDir)\lib is included in the directories list, if not, manually add it. If you're building for X64 platform, you should select X64 from the “Platform” ComboBox, and make sure that $(WindowsSdkDir)\lib\x64 is included in the directories list.

Extract parameter value from url using regular expressions

I use seperate custom functions which gets all URL Parameters and URL parts . For URL parameters, (which is the final part of an URI String, http://domain.tld/urlpart/?x=a&y=b

    function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
        vars[key] = value;
    });
    return vars;
    }

The above function will return an array consisting of url variables.

For URL Parts or functions, (which is http://domain.tld/urlpart/?x=a&y=b I use a simple uri split,

function getUrlParams() { 
    var vars = {};
    var parts = window.location.href.split('/' );
    return parts;
}

You can even combine them both to be able to use with a single call in a page or in javascript.

setBackground vs setBackgroundDrawable (Android)

Now you can use either of those options. And it is going to work in any case. Your color can be a HEX code, like this:

myView.setBackgroundResource(ContextCompat.getColor(context, Color.parseColor("#FFFFFF")));

A color resource, like this:

myView.setBackgroundResource(ContextCompat.getColor(context,R.color.blue_background));

Or a custom xml resource, like so:

myView.setBackgroundResource(R.drawable.my_custom_background);

Hope it helps!

The response content cannot be parsed because the Internet Explorer engine is not available, or

In your invoke web request just use the parameter -UseBasicParsing

e.g. in your script (line 2) you should use:

$rss = Invoke-WebRequest -UseBasicParsing

According to the documentation, this parameter is necessary on systems where IE isn't installed or configured.

Uses the response object for HTML content without Document Object Model (DOM) parsing. This parameter is required when Internet Explorer is not installed on the computers, such as on a Server Core installation of a Windows Server operating system.

How to install OpenJDK 11 on Windows?

  1. Extract the zip file into a folder, e.g. C:\Program Files\Java\ and it will create a jdk-11 folder (where the bin folder is a direct sub-folder). You may need Administrator privileges to extract the zip file to this location.

  2. Set a PATH:

    • Select Control Panel and then System.
    • Click Advanced and then Environment Variables.
    • Add the location of the bin folder of the JDK installation to the PATH variable in System Variables.
    • The following is a typical value for the PATH variable: C:\WINDOWS\system32;C:\WINDOWS;"C:\Program Files\Java\jdk-11\bin"
  3. Set JAVA_HOME:

    • Under System Variables, click New.
    • Enter the variable name as JAVA_HOME.
    • Enter the variable value as the installation path of the JDK (without the bin sub-folder).
    • Click OK.
    • Click Apply Changes.
  4. Configure the JDK in your IDE (e.g. IntelliJ or Eclipse).

You are set.

To see if it worked, open up the Command Prompt and type java -version and see if it prints your newly installed JDK.

If you want to uninstall - just undo the above steps.

Note: You can also point JAVA_HOME to the folder of your JDK installations and then set the PATH variable to %JAVA_HOME%\bin. So when you want to change the JDK you change only the JAVA_HOME variable and leave PATH as it is.

Get final URL after curl is redirected

This would work:

 curl -I somesite.com | perl -n -e '/^Location: (.*)$/ && print "$1\n"'

Creating a jQuery object from a big HTML-string

Update:

From jQuery 1.8, we can use $.parseHTML, which will parse the HTML string to an array of DOM nodes. eg:

var dom_nodes = $($.parseHTML('<div><input type="text" value="val" /></div>'));

alert( dom_nodes.find('input').val() );

DEMO


var string = '<div><input type="text" value="val" /></div>';

$('<div/>').html(string).contents();

DEMO

What's happening in this code:

  • $('<div/>') is a fake <div> that does not exist in the DOM
  • $('<div/>').html(string) appends string within that fake <div> as children
  • .contents() retrieves the children of that fake <div> as a jQuery object

If you want to make .find() work then try this:

var string = '<div><input type="text" value="val" /></div>',
    object = $('<div/>').html(string).contents();

alert( object.find('input').val() );

DEMO

Import error No module named skimage

For Python 3, try the following:

import sys
!conda install --yes --prefix {sys.prefix} scikit-image

When using .net MVC RadioButtonFor(), how do you group so only one selection can be made?

In cases where the name attribute is different it is easiest to control the radio group via JQuery. When an option is selected use JQuery to un-select the other options.

Is there any way to debug chrome in any IOS device

If you don't need full debugging support, you can now view JavaScript console logs directly within Chrome for iOS at chrome://inspect.

https://blog.chromium.org/2019/03/debugging-websites-in-chrome-for-ios.html

Chrome for iOS Console

How to rename a file using Python

os.rename(old, new)

This is found in the Python docs: http://docs.python.org/library/os.html

How to get a Fragment to remove itself, i.e. its equivalent of finish()?

While it might not be the best approach the closest equivalent I can think of that works is this with the support/compatibility library

getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();

or

getActivity().getFragmentManager().beginTransaction().remove(this).commit();

otherwise.

In addition you can use the backstack and pop it. However keep in mind that the fragment might not be on the backstack (depending on the fragmenttransaction that got it there..) or it might not be the last one that got onto the stack so popping the stack could remove the wrong one...

What exactly does an #if 0 ..... #endif block do?

It is a cheap way to comment out, but I suspect that it could have debugging potential. For example, let's suppose you have a build that output values to a file. You might not want that in a final version so you can use the #if 0... #endif.

Also, I suspect a better way of doing it for debug purpose would be to do:

#ifdef DEBUG
// output to file
#endif

You can do something like that and it might make more sense and all you have to do is define DEBUG to see the results.

Entity Framework : How do you refresh the model when the db changes?

Are you looking at the designer or code view? You can force the designer to open by right clicking on your EDMX file and selecting Open With -> ADO.NET Entity Data Model Designer

Right click on the designer surface of the EDMX designer and click Update Model From Database...

All entities are refreshed by default, new entities are only added if you select them.


EDIT: If it is not refreshing well.

  • Select all the tables and view-s in the EDMX designer.
  • Delete them.
  • Then, update model from database

Run certain code every n seconds

You can start a separate thread whose sole duty is to count for 5 seconds, update the file, repeat. You wouldn't want this separate thread to interfere with your main thread.

initialize a const array in a class initializer in C++

Where I've a constant array, it's always been done as static. If you can accept that, this code should compile and run.

#include <stdio.h>
#include <stdlib.h>

class a {
        static const int b[2];
public:
        a(void) {
                for(int i = 0; i < 2; i++) {
                        printf("b[%d] = [%d]\n", i, b[i]);
                }
        }
};

const int a::b[2] = { 4, 2 };

int main(int argc, char **argv)
{
        a foo;
        return 0;
}

gpg: no valid OpenPGP data found

gpg: no valid OpenPGP data found.

In this scenario, the message is a cryptic way of telling you that the download failed. Piping these two steps together is nice when it works, but it kind of breaks the error reporting -- especially when you use wget -q (or curl -s), because these suppress error messages from the download step.

There could be any number of reasons for the download failure. My case, which wasn't exactly listed so far, was that the proxy settings were lost when I called the enclosing script with sudo.

Shortest distance between a point and a line segment

The above function is not working on vertical lines. Here is a function that is working fine! Line with points p1, p2. and CheckPoint is p;

public float DistanceOfPointToLine2(PointF p1, PointF p2, PointF p)
{
  //          (y1-y2)x + (x2-x1)y + (x1y2-x2y1)
  //d(P,L) = --------------------------------
  //         sqrt( (x2-x1)pow2 + (y2-y1)pow2 )

  double ch = (p1.Y - p2.Y) * p.X + (p2.X - p1.X) * p.Y + (p1.X * p2.Y - p2.X * p1.Y);
  double del = Math.Sqrt(Math.Pow(p2.X - p1.X, 2) + Math.Pow(p2.Y - p1.Y, 2));
  double d = ch / del;
  return (float)d;
}

NoClassDefFoundError for code in an Java library on Android

Solutions:

  1. List item
  2. Check Exports Order
  3. Enable Multi Dex
  4. Check api level of views in layout. I faced same problem with searchView. I have check api level while adding searchview but added implements SearchView.OnQueryTextListener to class file.

How do ACID and database transactions work?

Transaction can be defined as a collection of task that are considered as minimum processing unit. Each minimum processing unit can not be divided further.

All transaction must contain four properties that commonly known as ACID properties. i.e ACID are the group of properties of any transaction.

  • Atomicity :
  • Consistency
  • Isolation
  • Durability

How do I get the path and name of the file that is currently executing?

To keep the migration consistency across platforms (macOS/Windows/Linux), try:

path = r'%s' % os.getcwd().replace('\\','/')

C program to check little vs. big endian

Thought I knew I had read about that in the standard; but can't find it. Keeps looking. Old; answering heading; not Q-tex ;P:


The following program would determine that:

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

int is_big_endian(void)
{
    union {
        uint32_t i;
        char c[4];
    } e = { 0x01000000 };

    return e.c[0];
}

int main(void)
{
    printf("System is %s-endian.\n",
        is_big_endian() ? "big" : "little");

    return 0;
}

You also have this approach; from Quake II:

byte    swaptest[2] = {1,0};
if ( *(short *)swaptest == 1) {
    bigendien = false;

And !is_big_endian() is not 100% to be little as it can be mixed/middle.

Believe this can be checked using same approach only change value from 0x01000000 to i.e. 0x01020304 giving:

switch(e.c[0]) {
case 0x01: BIG
case 0x02: MIX
default: LITTLE

But not entirely sure about that one ...

How to write a stored procedure using phpmyadmin and how to use it through php?

Since a stored procedure is created, altered and dropped using queries you actually CAN manage them using phpMyAdmin.

To create a stored procedure, you can use the following (change as necessary) :

CREATE PROCEDURE sp_test()
BEGIN
  SELECT 'Number of records: ', count(*) from test;
END//

And make sure you set the "Delimiter" field on the SQL tab to //.

Once you created the stored procedure it will appear in the Routines fieldset below your tables (in the Structure tab), and you can easily change/drop it.

To use the stored procedure from PHP you have to execute a CALL query, just like you would do in plain SQL.

How to unmerge a Git merge?

If you haven't committed the merge, then use:

git merge --abort

How to set a default value for an existing column

in case a restriction already exists with its default name:

-- Drop existing default constraint on Employee.CityBorn
DECLARE @default_name varchar(256);
SELECT @default_name = [name] FROM sys.default_constraints WHERE parent_object_id=OBJECT_ID('Employee') AND COL_NAME(parent_object_id, parent_column_id)='CityBorn';
EXEC('ALTER TABLE Employee DROP CONSTRAINT ' + @default_name);

-- Add default constraint on Employee.CityBorn
ALTER TABLE Employee ADD CONSTRAINT df_employee_1 DEFAULT 'SANDNES' FOR CityBorn;

Binding ng-model inside ng-repeat loop in AngularJS

<h4>Order List</h4>
<ul>
    <li ng-repeat="val in filter_option.order">
        <span>
            <input title="{{filter_option.order_name[$index]}}" type="radio" ng-model="filter_param.order_option" ng-value="'{{val}}'" />
            &nbsp;{{filter_option.order_name[$index]}}
        </span>
        <select title="" ng-model="filter_param[val]">
            <option value="asc">Asc</option>
            <option value="desc">Desc</option>
        </select>
    </li>
</ul>

Difference between session affinity and sticky session?

I've seen those terms used interchangeably, but there are different ways of implementing it:

  1. Send a cookie on the first response and then look for it on subsequent ones. The cookie says which real server to send to.
    Bad if you have to support cookie-less browsers
  2. Partition based on the requester's IP address.
    Bad if it isn't static or if many come in through the same proxy.
  3. If you authenticate users, partition based on user name (it has to be an HTTP supported authentication mode to do this).
  4. Don't require state.
    Let clients hit any server (send state to the client and have them send it back)
    This is not a sticky session, it's a way to avoid having to do it.

I would suspect that sticky might refer to the cookie way, and that affinity might refer to #2 and #3 in some contexts, but that's not how I have seen it used (or use it myself)

What is the difference between atomic / volatile / synchronized?

A volatile + synchronization is a fool proof solution for an operation(statement) to be fully atomic which includes multiple instructions to the CPU.

Say for eg:volatile int i = 2; i++, which is nothing but i = i + 1; which makes i as the value 3 in the memory after the execution of this statement. This includes reading the existing value from memory for i(which is 2), load into the CPU accumulator register and do with the calculation by increment the existing value with one(2 + 1 = 3 in accumulator) and then write back that incremented value back to the memory. These operations are not atomic enough though the value is of i is volatile. i being volatile guarantees only that a SINGLE read/write from memory is atomic and not with MULTIPLE. Hence, we need to have synchronized also around i++ to keep it to be fool proof atomic statement. Remember the fact that a statement includes multiple statements.

Hope the explanation is clear enough.

val() doesn't trigger change() in jQuery

From https://api.jquery.com/change/:

The change event is sent to an element when its value changes. This event is limited to <input> elements, <textarea> boxes and <select> elements. For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus.

What's NSLocalizedString equivalent in Swift?

Created a small helper method for cases, where "comment" is always ignored. Less code is easier to read:

public func NSLocalizedString(key: String) -> String {
    return NSLocalizedString(key, comment: "")
}

Just put it anywhere (outside a class) and Xcode will find this global method.

Copy files from one directory into an existing directory

cp dir1/* dir2

Or if you have directories inside dir1 that you'd want to copy as well

cp -r dir1/* dir2

iPhone SDK on Windows (alternative solutions)

This really comes down to how much you value your time. As the other posters have mentioned, there are a couple of ways you can build iPhone apps without a Mac. However, you are jumping through serious hoops, and it'll be much more difficult and take longer than it would with the proper development chain.

You can buy a second-hand Mac Mini for a couple of hundred bucks on eBay. If you're serious about doing iPhone development you'll make this back in saved time very quickly.

How to export JavaScript array info to csv (on client side)?

//It work in Chrome and IE ... I reviewed and readed a lot of answer. then i used it and tested in both ... 

var link = document.createElement("a");

if (link.download !== undefined) { // feature detection
    // Browsers that support HTML5 download attribute
    var blob = new Blob([CSV], { type: 'text/csv;charset=utf-8;' });
    var url = URL.createObjectURL(blob);            
    link.setAttribute("href", url);
    link.setAttribute("download", fileName);
    link.style = "visibility:hidden";
}

if (navigator.msSaveBlob) { // IE 10+
   link.addEventListener("click", function (event) {
     var blob = new Blob([CSV], {
       "type": "text/csv;charset=utf-8;"
     });
   navigator.msSaveBlob(blob, fileName);
  }, false);
}

document.body.appendChild(link);
link.click();
document.body.removeChild(link);

//Regards

Access Session attribute on jstl

You don't need the jsp:useBean to set the model if you already have a controller which prepared the model.

Just access it plain by EL:

<p>${Questions.questionPaperID}</p>
<p>${Questions.question}</p>

or by JSTL <c:out> tag if you'd like to HTML-escape the values or when you're still working on legacy Servlet 2.3 containers or older when EL wasn't supported in template text yet:

<p><c:out value="${Questions.questionPaperID}" /></p>
<p><c:out value="${Questions.question}" /></p>

See also:


Unrelated to the problem, the normal practice is by the way to start attribute name with a lowercase, like you do with normal variable names.

session.setAttribute("questions", questions);

and alter EL accordingly to use ${questions}.

Also note that you don't have any JSTL tag in your code. It's all plain JSP.

Why does CreateProcess give error 193 (%1 is not a valid Win32 app)

Your Button2Click and Button3Click functions pass klad.xls and smimime.txt. These files most likely aren't actual executables indeed.

In order to open arbitrary files using the application associated with them, use ShellExecute

SQL: Combine Select count(*) from multiple tables

you could name all fields and add an outer select on those fields:

SELECT A, B, C FROM ( your initial query here ) TableAlias

That should do the trick.

How to force Hibernate to return dates as java.util.Date instead of Timestamp?

Approaches 1 and 2 obviously don't work, because you get java.sql.Date objects, per JPA/Hibernate spec, and not java.util.Date. From approaches 3 and 4, I would rather choose the latter one, because it's more declarative, and will work with both field and getter annotations.

You have already laid out the solution 4 in your referenced blog post, as @tscho was kind to point out. Maybe defaultForType (see below) should give you the centralized solution you were looking for. Of course will will still need to differentiate between date (without time) and timestamp fields.

For future reference I will leave the summary of using your own Hibernate UserType here:

To make Hibernate give you java.util.Date instances, you can use the @Type and @TypeDef annotations to define a different mapping of your java.util.Date java types to and from the database.

See the examples in the core reference manual here.

  1. Implement a UserType to do the actual plumbing (conversion to/from java.util.Date), named e.g. TimestampAsJavaUtilDateType
  2. Add a @TypeDef annotation on one entity or in a package-info.java - both will be available globally for the session factory (see manual link above). You can use defaultForType to apply the type conversion on all mapped fields of type java.util.Date.

    @TypeDef
      name = "timestampAsJavaUtilDate",
      defaultForType = java.util.Date.class, /* applied globally */
      typeClass = TimestampAsJavaUtilDateType.class
    )
    
  3. Optionally, instead of defaultForType, you can annotate your fields/getters with @Type individually:

    @Entity
    public class MyEntity {
       [...]
       @Type(type="timestampAsJavaUtilDate")
       private java.util.Date myDate;
       [...]
    }
    

P.S. To suggest a totally different approach: we usually just don't compare Date objects using equals() anyway. Instead we use a utility class with methods to compare e.g. only the calendar date of two Date instances (or another resolution such as seconds), regardless of the exact implementation type. That as worked well for us.

Ternary operators in JavaScript without an "else"

You could write

x = condition ? true : x;

So that x is unmodified when the condition is false.

This then is equivalent to

if (condition) x = true

EDIT:

!defaults.slideshowWidth 
      ? defaults.slideshowWidth = obj.find('img').width()+'px' 
      : null 

There are a couple of alternatives - I'm not saying these are better/worse - merely alternatives

Passing in null as the third parameter works because the existing value is null. If you refactor and change the condition, then there is a danger that this is no longer true. Passing in the exising value as the 2nd choice in the ternary guards against this:

!defaults.slideshowWidth = 
      ? defaults.slideshowWidth = obj.find('img').width()+'px' 
      : defaults.slideshowwidth 

Safer, but perhaps not as nice to look at, and more typing. In practice, I'd probably write

defaults.slideshowWidth = defaults.slideshowWidth 
               || obj.find('img').width()+'px'

Submitting a form by pressing enter without a submit button

HTML5 solution

<input type="submit" hidden />

When or Why to use a "SET DEFINE OFF" in Oracle Database

By default, SQL Plus treats '&' as a special character that begins a substitution string. This can cause problems when running scripts that happen to include '&' for other reasons:

SQL> insert into customers (customer_name) values ('Marks & Spencers Ltd');
Enter value for spencers: 
old   1: insert into customers (customer_name) values ('Marks & Spencers Ltd')
new   1: insert into customers (customer_name) values ('Marks  Ltd')

1 row created.

SQL> select customer_name from customers;

CUSTOMER_NAME
------------------------------
Marks  Ltd

If you know your script includes (or may include) data containing '&' characters, and you do not want the substitution behaviour as above, then use set define off to switch off the behaviour while running the script:

SQL> set define off
SQL> insert into customers (customer_name) values ('Marks & Spencers Ltd');

1 row created.

SQL> select customer_name from customers;

CUSTOMER_NAME
------------------------------
Marks & Spencers Ltd

You might want to add set define on at the end of the script to restore the default behaviour.

How to select a CRAN mirror in R

Here is what I do, which is basically straight from the example(Startup) page:

## Default repo
local({r <- getOption("repos")
       r["CRAN"] <- "http://cran.r-project.org" 
       options(repos=r)
})

which is in ~/.Rprofile.

Edit: As it is now 2018, we can add that for the last few years the URL "https://cloud.r-project.org" has been preferable as it reflects a) https access and b) an "always-near-you" CDN.

urllib2.HTTPError: HTTP Error 403: Forbidden

import urllib.request

bank_pdf_list = ["https://www.hdfcbank.com/content/bbp/repositories/723fb80a-2dde-42a3-9793-7ae1be57c87f/?path=/Personal/Home/content/rates.pdf",
"https://www.yesbank.in/pdf/forexcardratesenglish_pdf",
"https://www.sbi.co.in/documents/16012/1400784/FOREX_CARD_RATES.pdf"]


def get_pdf(url):
    user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'
    
    #url = "https://www.yesbank.in/pdf/forexcardratesenglish_pdf"
    headers={'User-Agent':user_agent,} 
    
    request=urllib.request.Request(url,None,headers) #The assembled request
    response = urllib.request.urlopen(request)
    #print(response.text)
    data = response.read()
#    print(type(data))
    
    name = url.split("www.")[-1].split("//")[-1].split(".")[0]+"_FOREX_CARD_RATES.pdf"
    f = open(name, 'wb')
    f.write(data)
    f.close()
    

for bank_url in bank_pdf_list:
    try: 
        get_pdf(bank_url)
    except:
        pass

Determine if string is in list in JavaScript

EcmaScript 6 and up

If you're using ES6 or higher, the cleanest way is to construct an array of the items and use Array.includes:

['a', 'b', 'c'].includes('b')

This has some inherent benefits over indexOf because it can properly test for the presence of NaN in the list, and can match missing array elements such as the middle one in [1, , 2] to undefined. includes also works on JavaScript typed arrays such as Uint8Array.

If you're concerned about browser support (such as for IE or Edge), you can check Array.includes at CanIUse.Com, and if you want to target a browser or browser version that's missing includes, I recommend polyfill.io for polyfilling.

Without An Array

You could add a new isInList property to strings as follows:

if (!String.prototype.isInList) {
  Object.defineProperty(String.prototype, 'isInList', {
    get: () => function(...args) {
      let value = this.valueOf();
      for (let i = 0, l = args.length; i < l; i += 1) {
        if (arguments[i] === value) return true;
      }
      return false;
    }
  });
}

Then use it like so:

'fox'.isInList('weasel', 'fox', 'stoat') // true
'fox'.isInList('weasel', 'stoat') // false

You can do the same thing for Number.prototype.

Note that Object.defineProperty cannot be used in IE8 and earlier, or very old versions of other browsers. However, it is a far superior solution to String.prototype.isInList = function() { ... } because using simple assignment like that will create an enumerable property on String.prototype, which is more likely to break code.

Array.indexOf

If you are using a modern browser, indexOf always works. However, for IE8 and earlier you'll need a polyfill.

If indexOf returns -1, the item is not in the list. Be mindful though, that this method will not properly check for NaN, and while it can match an explicit undefined, it can’t match a missing element to undefined as in the array [1, , 2].

Polyfill for indexOf or includes in IE, or any other browser/version lacking support

If you don't want to use a service like polyfill.io as mentioned above, you can always include in your own source code standards-compliant custom polyfills. For example, Mozilla Developer Network has one for indexOf.

In this situation where I had to make a solution for Internet Explorer 7, I "rolled my own" simpler version of the indexOf() function that is not standards-compliant:

if (!Array.prototype.indexOf) {
   Array.prototype.indexOf = function(item) {
      var i = this.length;
      while (i--) {
         if (this[i] === item) return i;
      }
      return -1;
   }
}

However, I don't think modifying Array.prototype is the best answer in the long term. Modifying Object and Array prototypes in JavaScript can lead to serious bugs. You need to decide whether doing so is safe in your own environment. Of primary note is that iterating an array (when Array.prototype has added properties) with for ... in will return the new function name as one of the keys:

Array.prototype.blah = function() { console.log('blah'); };
let arr = [1, 2, 3];
for (let x in arr) { console.log(x); }
// Result:
0
1
2
blah // Extra member iterated over!

Your code may work now, but the moment someone in the future adds a third-party JavaScript library or plugin that isn't zealously guarding against inherited keys, everything can break.

The old way to avoid that breakage is, during enumeration, to check each value to see if the object actually has it as a non-inherited property with if (arr.hasOwnProperty(x)) and only then work with that x.

The new ES6 ways to avoid this extra-key problem are:

  1. Use of instead of in, for (let x of arr). However, unless you can guarantee that all of your code and third-party libraries strictly stick to this method, then for the purposes of this question you'll probably just want to use includes as stated above.

  2. Define your new properties on the prototype using Object.defineProperty(), as this will make the property (by default) non-enumerable. This only truly solves the problem if all the JavaScript libraries or modules you use also do this.

How to respond with HTTP 400 error in a Spring MVC @ResponseBody method returning String?

Easiest way is to throw a ResponseStatusException

    @RequestMapping(value = "/matches/{matchId}", produces = "application/json")
    @ResponseBody
    public String match(@PathVariable String matchId, @RequestBody String body) {
        String json = matchService.getMatchJson(matchId);
        if (json == null) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND);
        }
        return json;
    }

How can I extract a number from a string in JavaScript?

Tried all the combinations cited above with this Code and got it working, was the only one that worked on that string -> (12) 3456-7890

var str="(12) 3456-7890";
str.replace( /\D+/g, '');

Result: "1234567890"

Obs: i know that a string like that will not be on the attr but whatever, the solution is better, because its more complete.

How to use the CancellationToken property?

You can create a Task with cancellation token, when you app goto background you can cancel this token.

You can do this in PCL https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/app-lifecycle

var cancelToken = new CancellationTokenSource();
Task.Factory.StartNew(async () => {
    await Task.Delay(10000);
    // call web API
}, cancelToken.Token);

//this stops the Task:
cancelToken.Cancel(false);

Anther solution is user Timer in Xamarin.Forms, stop timer when app goto background https://xamarinhelp.com/xamarin-forms-timer/

Convert a String to a byte array and then back to the original String

Use [String.getBytes()][1] to convert to bytes and use [String(byte[] data)][2] constructor to convert back to string.

Converting String to Int with Swift

You can use NSNumberFormatter().numberFromString(yourNumberString). It's great because it returns an an optional that you can then test with if let to determine if the conversion was successful. eg.

var myString = "\(10)"
if let myNumber = NSNumberFormatter().numberFromString(myString) {
    var myInt = myNumber.integerValue
    // do what you need to do with myInt
} else {
    // what ever error code you need to write
}

Swift 5

var myString = "\(10)"
if let myNumber = NumberFormatter().number(from: myString) {
    var myInt = myNumber.intValue
    // do what you need to do with myInt
  } else {
    // what ever error code you need to write
  }

Intellij idea subversion checkout error: `Cannot run program "svn"`

IntelliJ needs the subversion command(svn) added into Subversion settings. Here are the steps: 1. Download and Install subversion. 2. check on the command line prompt on windows(cmd) for the same command - svn.

enter image description here

  1. Validate svn command added to File --> settings --> Version Control --> subversion enter image description here

  2. Exit IntelliJ studio and relaunch

How can I disable mod_security in .htaccess file?

With some web hosts including NameCheap, it's not possible to disable ModSecurity using .htaccess. The only option is to contact tech support and ask them to alter the configuration for you.

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

IQueryable is faster than IEnumerable if we are dealing with huge amounts of data from database because,IQueryable gets only required data from database where as IEnumerable gets all the data regardless of the necessity from the database

Subdomain on different host

UPDATE - I do not have Total DNS enabled at GoDaddy because the domain is hosted at DiscountASP. As such, I could not add an A Record and that is why GoDaddy was only offering to forward my subdomain to a different site. I finally realized that I had to go to DiscountASP to add the A Record to point to DreamHost. Now waiting to see if it all works!

Of course, use the stinkin' IP! I'm not sure why that wasn't registering for me. I guess their helper text example of pointing to another url was throwing me off.

Thanks for both of the replies. I 'got it' as soon as I read Bryant's response which was first but Saif kicked it up a notch and added a little more detail.

Thanks!

Get bytes from std::string in C++

I dont think you want to use the c# code you have there. They provide System.Text.Encoding.ASCII(also UTF-*)

string str = "some text;
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(str);

your problems stem from ignoring the encoding in c# not your c++ code

Align inline-block DIVs to top of container element

You need to add a vertical-align property to your two child div's.

If .small is always shorter, you need only apply the property to .small. However, if either could be tallest then you should apply the property to both .small and .big.

.container{ 
    border: 1px black solid;
    width: 320px;
    height: 120px;    
}

.small{
    display: inline-block;
    width: 40%;
    height: 30%;
    border: 1px black solid;
    background: aliceblue; 
    vertical-align: top;   
}

.big {
    display: inline-block;
    border: 1px black solid;
    width: 40%;
    height: 50%;
    background: beige; 
    vertical-align: top;   
}

Vertical align affects inline or table-cell box's, and there are a large nubmer of different values for this property. Please see https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align for more details.

Reload child component when variables on parent component changes. Angular2

On Angular to update a component including its template, there is a straight forward solution to this, having an @Input property on your ChildComponent and add to your @Component decorator changeDetection: ChangeDetectionStrategy.OnPush as follows:

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

@Component({
    selector: 'master',
    templateUrl: templateUrl,
    styleUrls:[styleUrl1],
    changeDetection: ChangeDetectionStrategy.OnPush    
})

export class ChildComponent{
  @Input() data: MyData;
}

This will do all the work of check if Input data have changed and re-render the component

No Network Security Config specified, using platform default - Android Log

This occurs to the api 28 and above, because doesn't accept http anymore, you need to change if you want to accept http or localhost requests.

  1. Create an XML file Create XML file

  2. Add the following code on the new XML file you created Add base-config

  3. Add this on AndroidManifest.xml Add this code line

Undefined index with $_POST

Your code assumes the existence of something:

$user = $_POST["username"];

PHP is letting you know that there is no "username" in the $_POST array. In this instance, you would be safer checking to see if the value isset() before attempting to access it:

if ( isset( $_POST["username"] ) ) {
    /* ... proceed ... */
}

Alternatively, you could hi-jack the || operator to assign a default:

$user = $_POST["username"] || "visitor" ;

As long as the user's name isn't a falsy value, you can consider this method pretty reliable. A much safer route to default-assignment would be to use the ternary operator:

$user = isset( $_POST["username"] ) ? $_POST["username"] : "visitor" ;

use jQuery to get values of selected checkboxes

Jquery 3.3.1 , getting values for all checked check boxes on button click

_x000D_
_x000D_
$(document).ready(function(){_x000D_
 $(".btn-submit").click(function(){_x000D_
  $('.cbCheck:checkbox:checked').each(function(){_x000D_
 alert($(this).val())_x000D_
  });_x000D_
 });   _x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input type="checkbox" id="vehicle1" name="vehicle1"  class="cbCheck" value="Bike">_x000D_
  <label for="vehicle1"> I have a bike</label><br>_x000D_
  <input type="checkbox" id="vehicle2" name="vehicle2"  class="cbCheck" value="Car">_x000D_
  <label for="vehicle2"> I have a car</label><br>_x000D_
  <input type="checkbox" id="vehicle3" name="vehicle3"  class="cbCheck" value="Boat">_x000D_
  <label for="vehicle3"> I have a boat</label><br><br>_x000D_
  <input type="submit" value="Submit" class="btn-submit">
_x000D_
_x000D_
_x000D_

Wpf DataGrid Add new row

Just simply use this Style of DataGridRow:

<DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Setter Property="IsEnabled" Value="{Binding RelativeSource={RelativeSource Self},Path=IsNewItem,Mode=OneWay}" />
        </Style>
</DataGrid.RowStyle>

Android java.exe finished with non-zero exit value 1

In my case, the solution was to close Android Studio and kill the java processs, which was very big (1.2 GB). After this, my project runs normally (OS X Mount Lion, Android Studio 1.2.2, iMac Mid 2011 4GB Ram).

Cookie blocked/not saved in IFRAME in Internet Explorer

If you own the domain that needs to be embedded, then you could, before calling the page that includes the IFrame, redirect to that domain, which will create the cookie and redirect back, as explained here: http://www.mendoweb.be/blog/internet-explorer-safari-third-party-cookie-problem/

This will work for Internet Explorer but for Safari as well (because Safari also blocks the third-party cookies).

How to properly use unit-testing's assertRaises() with NoneType objects?

The usual way to use assertRaises is to call a function:

self.assertRaises(TypeError, test_function, args)

to test that the function call test_function(args) raises a TypeError.

The problem with self.testListNone[:1] is that Python evaluates the expression immediately, before the assertRaises method is called. The whole reason why test_function and args is passed as separate arguments to self.assertRaises is to allow assertRaises to call test_function(args) from within a try...except block, allowing assertRaises to catch the exception.

Since you've defined self.testListNone = None, and you need a function to call, you might use operator.itemgetter like this:

import operator
self.assertRaises(TypeError, operator.itemgetter, (self.testListNone,slice(None,1)))

since

operator.itemgetter(self.testListNone,slice(None,1))

is a long-winded way of saying self.testListNone[:1], but which separates the function (operator.itemgetter) from the arguments.

How do you get a query string on Flask?

Every form of the query string retrievable from flask request object as described in O'Reilly Flask Web Devleopment:

From O'Reilly Flask Web Development, and as stated by Manan Gouhari earlier, first you need to import request:

from flask import request

request is an object exposed by Flask as a context variable named (you guessed it) request. As its name suggests, it contains all the information that the client included in the HTTP request. This object has many attributes and methods that you can retrieve and call, respectively.

You have quite a few request attributes which contain the query string from which to choose. Here I will list every attribute that contains in any way the query string, as well as a description from the O'Reilly book of that attribute.

First there is args which is "a dictionary with all the arguments passed in the query string of the URL." So if you want the query string parsed into a dictionary, you'd do something like this:

from flask import request

@app.route('/'):
    queryStringDict = request.args

(As others have pointed out, you can also use .get('<arg_name>') to get a specific value from the dictionary)

Then, there is the form attribute, which does not contain the query string, but which is included in part of another attribute that does include the query string which I will list momentarily. First, though, form is "A dictionary with all the form fields submitted with the request." I say that to say this: there is another dictionary attribute available in the flask request object called values. values is "A dictionary that combines the values in form and args." Retrieving that would look something like this:

from flask import request

@app.route('/'):
    formFieldsAndQueryStringDict = request.values

(Again, use .get('<arg_name>') to get a specific item out of the dictionary)

Another option is query_string which is "The query string portion of the URL, as a raw binary value." Example of that:

from flask import request

@app.route('/'):
    queryStringRaw = request.query_string

Then as an added bonus there is full_path which is "The path and query string portions of the URL." Por ejemplo:

from flask import request

@app.route('/'):
    pathWithQueryString = request.full_path

And finally, url, "The complete URL requested by the client" (which includes the query string):

from flask import request

@app.route('/'):
    pathWithQueryString = request.url

Happy hacking :)

Is it possible to get an Excel document's row count without loading the entire document into memory?

The solution suggested in this answer has been deprecated, and might no longer work.


Taking a look at the source code of OpenPyXL (IterableWorksheet) I've figured out how to get the column and row count from an iterator worksheet:

wb = load_workbook(path, use_iterators=True)
sheet = wb.worksheets[0]

row_count = sheet.get_highest_row() - 1
column_count = letter_to_index(sheet.get_highest_column()) + 1

IterableWorksheet.get_highest_column returns a string with the column letter that you can see in Excel, e.g. "A", "B", "C" etc. Therefore I've also written a function to translate the column letter to a zero based index:

def letter_to_index(letter):
    """Converts a column letter, e.g. "A", "B", "AA", "BC" etc. to a zero based
    column index.

    A becomes 0, B becomes 1, Z becomes 25, AA becomes 26 etc.

    Args:
        letter (str): The column index letter.
    Returns:
        The column index as an integer.
    """
    letter = letter.upper()
    result = 0

    for index, char in enumerate(reversed(letter)):
        # Get the ASCII number of the letter and subtract 64 so that A
        # corresponds to 1.
        num = ord(char) - 64

        # Multiply the number with 26 to the power of `index` to get the correct
        # value of the letter based on it's index in the string.
        final_num = (26 ** index) * num

        result += final_num

    # Subtract 1 from the result to make it zero-based before returning.
    return result - 1

I still haven't figured out how to get the column sizes though, so I've decided to use a fixed-width font and automatically scaled columns in my application.

How to turn on line numbers in IDLE?

As mentioned above (a quick way to do this) :

pip install IDLEX

Then I create a shortcut on Desktop (Win10) like this:

C:\Python\Python37\pythonw.exe "C:\Python\Python37\Scripts\idlex.pyw"

The paths may be different and need to be changed:

C:\Python\Python37

(Thanks for the great answers above)

Illegal access: this web application instance has been stopped already

Problem solved after restarting the tomcat and apache, the tomcat was caching older version of the app.