Programs & Examples On #Stub

A replacement implementation for objects, methods, or functions in order to remove external dependencies.

Access restriction on class due to restriction on required library rt.jar?

There's another solution that also works.

  1. Go to the Build Path settings in the project properties.
  2. Remove the JRE System Library
  3. Add it back; Select "Add Library" and select the JRE System Library. The default worked for me.

This works because you have multiple classes in different jar files. Removing and re-adding the JRE lib will make the right classes be first. If you want a fundamental solution make sure you exclude the jar files with the same classes.

For me I have: javax.xml.soap.SOAPPart in three different jars: axis-saaj-1.4.jar, saaj-api-1.3.jar and the rt.jar

java.net.ConnectException :connection timed out: connect?

Number (1): The IP was incorrect - is the correct answer. The /etc/hosts file (a.k.a. C:\Windows\system32\drivers\etc\hosts ) had an incorrect entry for the local machine name. Corrected the 'hosts' file and Camel runs very well. Thanks for the pointer.

What does "to stub" mean in programming?

"Stubbing-out a function means you'll write only enough to show that the function was called, leaving the details for later when you have more time."

From: SAMS Teach yourself C++, Jesse Liberty and Bradley Jones

What's the difference between a mock & stub?

I like the explanantion put out by Roy Osherove [video link].

Every class or object created is a Fake. It is a Mock if you verify calls against it. Otherwise its a stub.

How can I get (query string) parameters from the URL in Next.js?

url prop is deprecated as of Next.js version 6: https://github.com/zeit/next.js/blob/master/errors/url-deprecated.md

To get the query parameters, use getInitialProps:

For stateless components

import Link from 'next/link'
const About = ({query}) => (
  <div>Click <Link href={{ pathname: 'about', query: { name: 'leangchhean' }}}><a>here</a></Link> to read more</div>
)

About.getInitialProps = ({query}) => {
  return {query}
}

export default About;

For regular components

class About extends React.Component {

  static getInitialProps({query}) {
    return {query}
  }

  render() {
    console.log(this.props.query) // The query is available in the props object
    return <div>Click <Link href={{ pathname: 'about', query: { name: 'leangchhean' }}}><a>here</a></Link> to read more</div>

  }
}

The query object will be like: url.com?a=1&b=2&c=3 becomes: {a:1, b:2, c:3}

Return 0 if field is null in MySQL

None of the above answers were complete for me. If your field is named field, so the selector should be the following one:

IFNULL(`field`,0) AS field

For example in a SELECT query:

SELECT IFNULL(`field`,0) AS field, `otherfield` FROM `mytable`

Hope this can help someone to not waste time.

add created_at and updated_at fields to mongoose schemas

const mongoose = require('mongoose');
const config = require('config');
const util = require('util');

const Schema = mongoose.Schema;
const BaseSchema = function(obj, options) {
  if (typeof(options) == 'undefined') {
    options = {};
  }
  if (typeof(options['timestamps']) == 'undefined') {
    options['timestamps'] = true;
  }

  Schema.apply(this, [obj, options]);
};
util.inherits(BaseSchema, Schema);

var testSchema = new BaseSchema({
  jsonObject: { type: Object }
  , stringVar : { type: String }
});

Now you can use this, so that there is no need to include this option in every table

Undefined reference to main - collect2: ld returned 1 exit status

You can just add a main function to resolve this problem. Just like:

int main()
{
    return 0;
}

Checking to see if one array's elements are in another array in PHP

You could also use in_array as follows:

<?php
$found = null;
$people = array(3,20,2);
$criminals = array( 2, 4, 8, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20);
foreach($people as $num) {
    if (in_array($num,$criminals)) {
        $found[$num] = true;
    } 
}
var_dump($found);
// array(2) { [20]=> bool(true)   [2]=> bool(true) }

While array_intersect is certainly more convenient to use, it turns out that its not really superior in terms of performance. I created this script too:

<?php
$found = null;
$people = array(3,20,2);
$criminals = array( 2, 4, 8, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20);
$fastfind = array_intersect($people,$criminals);
var_dump($fastfind);
// array(2) { [1]=> int(20)   [2]=> int(2) }

Then, I ran both snippets respectively at: http://3v4l.org/WGhO7/perf#tabs and http://3v4l.org/g1Hnu/perf#tabs and checked the performance of each. The interesting thing is that the total CPU time, i.e. user time + system time is the same for PHP5.6 and the memory also is the same. The total CPU time under PHP5.4 is less for in_array than array_intersect, albeit marginally so.

what is Segmentation fault (core dumped)?

"Segmentation fault" means that you tried to access memory that you do not have access to.

The first problem is with your arguments of main. The main function should be int main(int argc, char *argv[]), and you should check that argc is at least 2 before accessing argv[1].

Also, since you're passing in a float to printf (which, by the way, gets converted to a double when passing to printf), you should use the %f format specifier. The %s format specifier is for strings ('\0'-terminated character arrays).

Better way to find last used row

I use this routine to find the count of data rows. There is a minimum of overhead required, but by counting using a decreasing scale, even a very large result requires few iterations. For example, a result of 28,395 would only require 2 + 8 + 3 + 9 + 5, or 27 times through the loop, instead of a time-expensive 28,395 times.

Even were we to multiply that by 10 (283,950), the iteration count is the same 27 times.

Dim lWorksheetRecordCountScaler as Long
Dim lWorksheetRecordCount as Long

Const sDataColumn = "A"   '<----Set to column that has data in all rows (Code, ID, etc.)

    'Count the data records
    lWorksheetRecordCountScaler = 100000  'Begin by counting in 100,000-record bites
    lWorksheetRecordCount = lWorksheetRecordCountScaler

    While lWorksheetRecordCountScaler >= 1

        While Sheets("Sheet2").Range(sDataColumn & lWorksheetRecordCount + 2).Formula > " "
            lWorksheetRecordCount = lWorksheetRecordCount + lWorksheetRecordCountScaler
        Wend

        'To the beginning of the previous bite, count 1/10th of the scale from there
        lWorksheetRecordCount = lWorksheetRecordCount - lWorksheetRecordCountScaler
        lWorksheetRecordCountScaler = lWorksheetRecordCountScaler / 10

    Wend

    lWorksheetRecordCount = lWorksheetRecordCount + 1   'Final answer

When is a language considered a scripting language?

My friend and I just had this argument: What is the difference between a programming language and a scripting language.

A popular argument is that programming languages are compiled and scripting languages are interpreted - However I believe this argument to be completely false...why?

  1. Chakra & V8 (Microsoft's and Google's JavaScript engines) compile code before execution
  2. QBasic is interpreted - does this make Qbasic a "scripting" language?

On that basis, this is my argument for the difference between a programming language and a scripting language:

A programming language runs at the machine level and has access to the machine itself (memory, graphics, sound etc).

A scripting language is sand boxed and only has access to objects exposed to the sand box. It has no direct access to the underlying machine.

Set an environment variable in git bash

If you want to set environment variables permanently in Git-Bash, you have two options:

  1. Set a regular Windows environment variable. Git-bash gets all existing Windows environment variables at startupp.

  2. Set up env variables in .bash_profile file.

.bash_profile is by default located in a user home folder, like C:\users\userName\git-home\.bash_profile. You can change the path to the bash home folder by setting HOME Windows environment variable.

.bash_profile file uses the regular Bash syntax and commands

# Export a variable in .bash_profile
export DIR=c:\dir
# Nix path style works too
export DIR=/c/dir

# And don't forget to add quotes if a variable contains whitespaces
export ANOTHER_DIR="c:\some dir"

Read more information about Bash configurations files.

Calling JavaScript Function From CodeBehind

You can't call a Javascript function from the CodeBehind, because the CodeBehind file contains the code that executes server side on the web server. Javascript code executes in the web browser on the client side.

Can I have an onclick effect in CSS?

Answer as of 2020:

The best way (actually the only way*) to simulate an actual click event using only CSS (rather than just hovering on an element or making an element active, where you don't have mouseUp) is to use the checkbox hack. It works by attaching a label to an <input type="checkbox"> element via the label's for="" attribute.

This feature has broad browser support (the :checked pseudo-class is IE9+).

Apply the same value to an <input>'s ID attribute and an accompanying <label>'s for="" attribute, and you can tell the browser to re-style the label on click with the :checked pseudo-class, thanks to the fact that clicking a label will check and uncheck the "associated" <input type="checkbox">.

* You can simulate a "selected" event via the :active or :focus pseudo-class in IE7+ (e.g. for a button that's normally 50px wide, you can change its width while active: #btnControl:active { width: 75px; }), but those are not true "click" events. They are "live" the entire time the element is selected (such as by Tabbing with your keyboard), which is a little different from a true click event, which fires an action on - typically - mouseUp.


Basic demo of the checkbox hack (the basic code structure for what you're asking):

_x000D_
_x000D_
label {
    display: block;
    background: lightgrey;
    width: 100px;
    height: 100px;
}

#demo:checked + label {
    background: blue;
    color: white;
}
_x000D_
<input type="checkbox" id="demo"/>
<label for="demo">I'm a square. Click me.</label>
_x000D_
_x000D_
_x000D_

Here I've positioned the label right after the input in my markup. This is so that I can use the adjacent sibling selector (the + key) to select only the label that immediately follows my #demo checkbox. Since the :checked pseudo-class applies to the checkbox, #demo:checked + label will only apply when the checkbox is checked.

Demo for re-sizing an image on click, which is what you're asking:

_x000D_
_x000D_
#btnControl {
    display: none;
}

#btnControl:checked + label > img {
    width: 70px;
    height: 74px;
}
_x000D_
<input type="checkbox" id="btnControl"/>
<label class="btn" for="btnControl"><img src="https://placekitten.com/200/140" id="btnLeft" /></label>
_x000D_
_x000D_
_x000D_

With that being said, there is some bad news. Because a label can only be associated with one form control at a time, that means you can't just drop a button inside the <label></label> tags and call it a day. However, we can use some CSS to make the label look and behave fairly close to how an HTML button looks and behaves.

Demo for imitating a button click effect, above and beyond what you're asking:

_x000D_
_x000D_
#btnControl {
    display: none;
}

.btn {
    width: 60px;
    height: 20px;
    background: silver;
    border-radius: 5px;
    padding: 1px 3px;
    box-shadow: 1px 1px 1px #000;
    display: block;
    text-align: center;
    background-image: linear-gradient(to bottom, #f4f5f5, #dfdddd);
    font-family: arial;
    font-size: 12px;
    line-height:20px;
}

.btn:hover {
    background-image: linear-gradient(to bottom, #c3e3fa, #a5defb);
}


.btn:active {
    margin-left: 1px 1px 0;
    box-shadow: -1px -1px 1px #000;
    outline: 1px solid black;
    -moz-outline-radius: 5px;
    background-image: linear-gradient(to top, #f4f5f5, #dfdddd);
}

#btnControl:checked + label {
    width: 70px;
    height: 74px;
    line-height: 74px;
}
_x000D_
<input type="checkbox" id="btnControl"/>
<label class="btn" for="btnControl">Click me!</label>
_x000D_
_x000D_
_x000D_

Most of the CSS in this demo is just for styling the label element. If you don't actually need a button, and any old element will suffice, then you can remove almost all of the styles in this demo, similar to my second demo above.

You'll also notice I have one prefixed property in there, -moz-outline-radius. A while back, Mozilla added this awesome non-spec property to Firefox, but the folks at WebKit decided they aren't going to add it, unfortunately. So consider that line of CSS just a progressive enhancement for people who use Firefox.

Reading/Writing a MS Word file in PHP

Reading binary Word documents would involve creating a parser according to the published file format specifications for the DOC format. I think this is no real feasible solution.

You could use the Microsoft Office XML formats for reading and writing Word files - this is compatible with the 2003 and 2007 version of Word. For reading you have to ensure that the Word documents are saved in the correct format (it's called Word 2003 XML-Document in Word 2007). For writing you just have to follow the openly available XML schema. I've never used this format for writing out Office documents from PHP, but I'm using it for reading in an Excel worksheet (naturally saved as XML-Spreadsheet 2003) and displaying its data on a web page. As the files are plainly XML data it's no problem to navigate within and figure out how to extract the data you need.

The other option - a Word 2007 only option (if the OpenXML file formats are not installed in your Word 2003) - would be to ressort to OpenXML. As databyss pointed out here the DOCX file format is just a ZIP archive with XML files included. There are a lot of resources on MSDN regarding the OpenXML file format, so you should be able to figure out how to read the data you want. Writing will be much more complicated I think - it just depends on how much time you'll invest.

Perhaps you can have a look at PHPExcel which is a library able to write to Excel 2007 files and read from Excel 2007 files using the OpenXML standard. You could get an idea of the work involved when trying to read and write OpenXML Word documents.

How can I combine flexbox and vertical scroll in a full-height app?

Thanks to https://stackoverflow.com/users/1652962/cimmanon that gave me the answer.

The solution is setting a height to the vertical scrollable element. For example:

#container article {
    flex: 1 1 auto;
    overflow-y: auto;
    height: 0px;
}

The element will have height because flexbox recalculates it unless you want a min-height so you can use height: 100px; that it is exactly the same as: min-height: 100px;

#container article {
    flex: 1 1 auto;
    overflow-y: auto;
    height: 100px; /* == min-height: 100px*/
}

So the best solution if you want a min-height in the vertical scroll:

#container article {
    flex: 1 1 auto;
    overflow-y: auto;
    min-height: 100px;
}

If you just want full vertical scroll in case there is no enough space to see the article:

#container article {
    flex: 1 1 auto;
    overflow-y: auto;
    min-height: 0px;
}

The final code: http://jsfiddle.net/ch7n6/867/

How can I use querySelector on to pick an input element by name?

1- you need to close the block of the function with '}', which is missing.

2- the argument of querySelector may not be an empty string '' or ' '... Use '*' for all.

3- those arguments will return the needed value:

querySelector('*')

querySelector('input')

querySelector('input[name="pwd"]')

querySelector('[name="pwd"]')

Can someone explain how to implement the jQuery File Upload plugin?

This is good Angular plugin for uploading files, and its free!

angular file upload

CSS: how to get scrollbars for div inside container of fixed height

setting the overflow should take care of it, but you need to set the height of Content also. If the height attribute is not set, the div will grow vertically as tall as it needs to, and scrollbars wont be needed.

See Example: http://jsfiddle.net/ftkbL/1/

Force encode from US-ASCII to UTF-8 (iconv)

I accidentally encoded a file in UTF-7 and had a similar issue. When I typed file -i name.file I would get charset=us-ascii.

iconv -f us-ascii -t utf-9//translit name.file would not work since I've gathered UTF-7 is a subset of US ASCII, as is UTF-8.

To solve this, I entered

iconv -f UTF-7 -t UTF-8//TRANSLIT name.file -o output.file

I'm not sure how to determine the encoding other than what others have suggested here.

Change image source in code behind - Wpf

You just need one line:

ImageViewer1.Source = new BitmapImage(new Uri(@"\myserver\folder1\Customer Data\sample.png"));

No module named MySQLdb

For Python 3.6+ sudo apt-get install libmysqlclient-dev and pip3 install mysqlclient does the trick

What is the difference between Builder Design pattern and Factory Design pattern?

Builder and Abstract Factory have meant for different purposes. Depending on right use case, you have to select suitable design pattern.

Builder salient features:

  1. Builder pattern builds a complex object using simple objects and using a step by step approach
  2. A Builder class builds the final object step by step. This builder is independent of other objects
  3. Replacement to Factory method/Abstract Factory in this scenario : Too Many arguments to pass from client program to the Factory class that can be error prone
  4. Some of the parameters might be optional unlike in Factory which forces to send all parameters

Factory (simple Factory) salient features:

  1. Creational pattern
  2. Based on inheritance
  3. Factory returns a Factory Method (interface) which in turn returns Concrete Object
  4. You can substitute new Concrete Objects for interface and client (caller) should not be aware of all concrete implementations
  5. Client always access interface only and you can hide object creation details in Factory method.

Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Prototype, or Builder (more flexible, more complex)

Have a look at related posts:

Keeping builder in separate class (fluent interface)

Design Patterns: Factory vs Factory method vs Abstract Factory

You can refer to below articles for more details:

sourcemaking

journaldev

How to access to the parent object in c#

Store a reference to the meter instance as a member in Production:

public class Production {
  //The other members, properties etc...
  private Meter m;

  Production(Meter m) {
    this.m = m;
  }
}

And then in the Meter-class:

public class Meter
{
   private int _powerRating = 0; 
   private Production _production;

   public Meter()
   {
      _production = new Production(this);
   }
}

Also note that you need to implement an accessor method/property so that the Production class can actually access the powerRating member of the Meter class.

Check if a string contains an element from a list (of strings)

when you construct yours strings it should be like this

bool inact = new string[] { "SUSPENDARE", "DIZOLVARE" }.Any(s=>stare.Contains(s));

How to plot a subset of a data frame in R?

with(dfr[dfr$var3 < 155,], plot(var1, var2)) should do the trick.

Edit regarding multiple conditions:

with(dfr[(dfr$var3 < 155) & (dfr$var4 > 27),], plot(var1, var2))

How to grant "grant create session" privilege?

You would use the WITH ADMIN OPTION option in the GRANT statement

GRANT CREATE SESSION TO <<username>> WITH ADMIN OPTION

Android ListView not refreshing after notifyDataSetChanged

You are assigning reloaded items to global variable items in onResume(), but this will not reflect in ItemAdapter class, because it has its own instance variable called 'items'.

For refreshing ListView, add a refresh() in ItemAdapter class which accepts list data i.e items

class ItemAdapter
{
    .....

    public void refresh(List<Item> items)
    {
        this.items = items;
        notifyDataSetChanged();
    } 
}

update onResume() with following code

@Override
public void onResume()
{
    super.onResume();
    items.clear();
    items = dbHelper.getItems(); //reload the items from database
    **adapter.refresh(items);**
}

How can I render a list select box (dropdown) with bootstrap?

Another way without using the .form-control is this:

  $(".dropdown-menu li a").click(function(){
        $(this).parents(".btn-group").find('.btn').html($(this).text() + ' <span class="caret"></span>');
        $(this).parents(".btn-group").find('.btn').val($(this).data('value'));
      });

_x000D_
_x000D_
$(".dropdown-menu li a").click(function(){_x000D_
  $(this).parents(".btn-group").find('.btn').html($(this).text() + ' <span class="caret"></span>');_x000D_
  $(this).parents(".btn-group").find('.btn').val($(this).data('value'));_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
<div class="btn-group">_x000D_
  <button  type="button" class="btn btn-info dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">_x000D_
                  Test <span class="caret"> </span>_x000D_
  </button>_x000D_
  <ul class="dropdown-menu">_x000D_
    <li><a href='#'>test 1</a></li>_x000D_
    <li><a href='#'>test 2</a></li>_x000D_
    <li><a href='#'>test 3</a></li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

what is the use of fflush(stdin) in c programming

It's not in standard C, so the behavior is undefined.

Some implementation uses it to clear stdin buffer.

From C11 7.21.5.2 The fflush function, fflush works only with output/update stream, not input stream.

If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.

Exception in thread "main" java.util.NoSuchElementException

simply don't close in

remove in.close() from your code.

Add Marker function with Google Maps API

THis is other method
You can also use setCenter method with add new marker

check below code

$('#my_map').gmap3({
      action: 'setCenter',
      map:{
         options:{
          zoom: 10
         }
      },
      marker:{
         values:
          [
            {latLng:[position.coords.latitude, position.coords.longitude], data:"Netherlands !"}
          ]
      }
   });

sh: 0: getcwd() failed: No such file or directory on cited drive

This can happen with symlinks sometimes. If you experience this issue and you know you are in an existing directory, but your symlink may have changed, you can use this command:

cd $(pwd)

MassAssignmentException in Laravel

This is not a good way when you want to seeding database.
Use faker instead of hard coding, and before all this maybe it's better to truncate tables.

Consider this example :

    // Truncate table.  
    DB::table('users')->truncate();

    // Create an instance of faker.
    $faker = Faker::create();

    // define an array for fake data.
    $users = [];

    // Make an array of 500 users with faker.
    foreach (range(1, 500) as $index)
    {
        $users[] = [
            'group_id' => rand(1, 3),
            'name' => $faker->name,
            'company' => $faker->company,
            'email' => $faker->email,
            'phone' => $faker->phoneNumber,
            'address' => "{$faker->streetName} {$faker->postCode} {$faker->city}",
            'about' => $faker->sentence($nbWords = 20, $variableNbWords = true),
            'created_at' => new DateTime,
            'updated_at' => new DateTime,
        ];
    }

    // Insert into database.
    DB::table('users')->insert($users);

Sending JSON object to Web API

var model = JSON.stringify({ 
    'ID': 0, 
    'ProductID': $('#ID').val(), 
    'PartNumber': $('#part-number').val(),
    'VendorID': $('#Vendors').val()
})

$.ajax({
    type: "POST",
    dataType: "json",
    contentType: "application/json",
    url: "/api/PartSourceAPI/",
    data: model,
    success: function (data) {
        alert('success');
    },
    error: function (error) {
        jsonValue = jQuery.parseJSON(error.responseText);
        jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
    }
});

var model = JSON.stringify({      'ID': 0,     ...': 5,      'PartNumber': 6,     'VendorID': 7 }) // output is "{"ID":0,"ProductID":5,"PartNumber":6,"VendorID":7}"

your data is something like this "{"model": "ID":0,"ProductID":6,"PartNumber":7,"VendorID":8}}" web api controller cannot bind it to Your model

MySql server startup error 'The server quit without updating PID file '

Could be related to old MySQL process. You need to kill it and restart. Sometimes it can be due to a conflict in MySQL config file. Try to move it and restart MySQL. Check the following url for more details.

http://linuxadministrator.pro/blog/?p=225

Thanks.

Is it possible to center text in select box?

_x000D_
_x000D_
select {_x000D_
  text-align: center;_x000D_
  text-align-last: center;_x000D_
}_x000D_
option {_x000D_
  text-align: left;_x000D_
}
_x000D_
<select>_x000D_
   <option value="">(please select a state)</option>_x000D_
   <option class="lt" value="--">none</option>_x000D_
   <option class="lt" value="AL">Alabama</option>_x000D_
   <option class="lt" value="AK">Alaska</option>_x000D_
   <option class="lt" value="AZ">Arizona</option>_x000D_
   <option class="lt" value="AR">Arkansas</option>_x000D_
   <option class="lt" value="CA">California</option>_x000D_
   <option class="lt" value="CO">Colorado</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

PostgreSQL Error: Relation already exists

I finally discover the error. The problem is that the primary key constraint name is equal the table name. I don know how postgres represents constraints, but I think the error "Relation already exists" was being triggered during the creation of the primary key constraint because the table was already declared. But because of this error, the table wasnt created at the end.

Where is the kibana error log? Is there a kibana error log?

In kibana 4.0.2 there is no --log-file option. If I start kibana as a service with systemctl start kibana I find log in /var/log/messages

Show/hide widgets in Flutter programmatically

UPDATE: Since this answer was written, Visibility was introduced and provides the best solution to this problem.


You can use Opacity with an opacity: of 0.0 to draw make an element hidden but still occupy space.

To make it not occupy space, replace it with an empty Container().

EDIT: To wrap it in an Opacity object, do the following:

            new Opacity(opacity: 0.0, child: new Padding(
              padding: const EdgeInsets.only(
                left: 16.0,
              ),
              child: new Icon(pencil, color: CupertinoColors.activeBlue),
            ))

Google Developers quick tutorial on Opacity: https://youtu.be/9hltevOHQBw

Initialization of all elements of an array to one default value in C++?

C++11 has another (imperfect) option:

std::array<int, 100> a;
a.fill(-1);

Better way to convert file sizes in Python

UNITS = {1000: ['KB', 'MB', 'GB'],
            1024: ['KiB', 'MiB', 'GiB']}

def approximate_size(size, flag_1024_or_1000=True):
    mult = 1024 if flag_1024_or_1000 else 1000
    for unit in UNITS[mult]:
        size = size / mult
        if size < mult:
            return '{0:.3f} {1}'.format(size, unit)

approximate_size(2123, False)

How to connect to MySQL Database?

you can use Package Manager to add it as package and it is the easiest way to do. You don't need anything else to work with mysql database.

Or you can run below command in Package Manager Console

PM> Install-Package MySql.Data

NUGET Mysql.Data

Getting last month's date in php

$lastMonth = date('M Y', strtotime("-1 month"));
var_dump($lastMonth);
$lastMonth = date('M Y', mktime(0, 0, 0, date('m') - 1, 1, date('Y')));
var_dump($lastMonth);

How do you set the startup page for debugging in an ASP.NET MVC application?

Go to your project's properties and set the start page property.

  1. Go to the project's Properties
  2. Go to the Web tab
  3. Select the Specific Page radio button
  4. Type in the desired url in the Specific Page text box

String.Format alternative in C++

In addition to options suggested by others I can recommend the fmt library which implements string formatting similar to str.format in Python and String.Format in C#. Here's an example:

std::string a = "test";
std::string b = "text.txt";
std::string c = "text1.txt";
std::string result = fmt::format("{0} {1} > {2}", a, b, c);

Disclaimer: I'm the author of this library.

jQuery - Getting form values for ajax POST

try as this code.

$.ajax({
        type: "POST",
        url: "http://rt.ja.com/includes/register.php?submit=1",
        data: "username="+username+"&email="+email+"&password="+password+"&passconf="+passconf,

        success: function(html)
        {   
            //alert(html);
            $('#userError').html(html);
            $("#userError").html(userChar);
            $("#userError").html(userTaken);
        }
    });

i think this will work definitely..

you can also use .serialize() function for sending data via jquery Ajax..

i.e: data : $("#registerSubmit").serialize()

Thanks.

CAST DECIMAL to INT

There's also ROUND() if your numbers don't necessarily always end with .00. ROUND(20.6) will give 21, and ROUND(20.4) will give 20.

Difference between size and length methods?

I bet (no language specified) size() method returns length property.

However valid for loop should looks like:

for (int i = 0; i < values.length; i++) {}

How do I stretch a background image to cover the entire HTML element?

If you need to stretch your background image while resizing the screen and you don't need compatibility with older browser versions this will do the work:

body {
    background-image: url('../images/image.jpg');
    background-repeat: no-repeat;
    background-size: cover;
}

How to disable postback on an asp Button (System.Web.UI.WebControls.Button)

ASP.NET always generate asp:Button as an input type=submit.
If you want a button which doesn't do a post, but need some control for the element on the server side, create a simple HTML input with attributes type=button and runat=server.

If you disable click actions doing OnClientClick=return false, it won't do anything on click, unless you create a function like:

function btnClick() {
    // do stuff
    return false;
}

"NODE_ENV" is not recognized as an internal or external command, operable command or batch file

for windows use & in between command also. Like,

  "scripts": {
    "start": "SET NODE_ENV=development & nodemon app/app.js",
  }

How to suppress "unused parameter" warnings in C?

You can use gcc/clang's unused attribute, however I use these macros in a header to avoid having gcc specific attributes all over the source, also having __attribute__ everywhere is a bit verbose/ugly.

#ifdef __GNUC__
#  define UNUSED(x) UNUSED_ ## x __attribute__((__unused__))
#else
#  define UNUSED(x) UNUSED_ ## x
#endif

#ifdef __GNUC__
#  define UNUSED_FUNCTION(x) __attribute__((__unused__)) UNUSED_ ## x
#else
#  define UNUSED_FUNCTION(x) UNUSED_ ## x
#endif

Then you can do...

void foo(int UNUSED(bar)) { ... }

I prefer this because you get an error if you try use bar in the code anywhere so you can't leave the attribute in by mistake.

and for functions...

static void UNUSED_FUNCTION(foo)(int bar) { ... }

Note 1):
As far as I know, MSVC doesn't have an equivalent to __attribute__((__unused__)).

Note 2):
The UNUSED macro won't work for arguments which contain parenthesis,
so if you have an argument like float (*coords)[3] you can't do,
float UNUSED((*coords)[3]) or float (*UNUSED(coords))[3], This is the only downside to the UNUSED macro I found so far, in these cases I fall back to (void)coords;

Where to install Android SDK on Mac OS X?

You can install android-sdk in different ways

  1. homebrew
    Install brew using command from brew.sh

    /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"  
    

    Install android-sdk using

    brew install android-sdk
    

    Now android-sdk will be installed in /usr/local/opt/android-sdk

    export ANDROID_HOME=/usr/local/opt/android-sdk
    
  2. If you installed android studio following the website,
    android-sdk will be installed in ~/Library/Android/sdk

    export ANDROID_HOME=~/Library/Android/sdk
    

I think these defaults make sense and its better to stick to it

How to add a color overlay to a background image?

Try this, it's simple and clear. I have found it from here : https://css-tricks.com/tinted-images-multiple-backgrounds/

.tinted-image {

  width: 300px;
  height: 200px;

  background: 
    /* top, transparent red */ 
    linear-gradient(
      rgba(255, 0, 0, 0.45), 
      rgba(255, 0, 0, 0.45)
    ),
    /* bottom, image */
    url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/owl1.jpg);
}

Hibernate, @SequenceGenerator and allocationSize

allocationSize=1 It is a micro optimization before getting query Hibernate tries to assign value in the range of allocationSize and so try to avoid querying database for sequence. But this query will be executed every time if you set it to 1. This hardly makes any difference since if your data base is accessed by some other application then it will create issues if same id is used by another application meantime .

Next generation of Sequence Id is based on allocationSize.

By defualt it is kept as 50 which is too much. It will also only help if your going to have near about 50 records in one session which are not persisted and which will be persisted using this particular session and transation.

So you should always use allocationSize=1 while using SequenceGenerator. As for most of underlying databases sequence is always incremented by 1.

offsetTop vs. jQuery.offset().top

Try this: parseInt(jQuery.offset().top, 10)

"cannot resolve symbol R" in Android Studio

I am facing an error 'Unable to resolve symbol R' the R appears in java file in red. I've solved it.

  1. Do not save any image with Capital letters like ABC.png. First delete the image or rename it.
  2. Clean project
  3. Rebuild Project

Call JavaScript function on DropDownList SelectedIndexChanged Event:

First Method: (Tested)

Code in .aspx.cs:

 protected void Page_Load(object sender, EventArgs e)
    {
        ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);
        if (!Page.IsPostBack)
        {
            ddl.Attributes.Add("onchange", "CalcTotalAmt();");
        }
    }

    protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
    {
       //Your Code
    }

JavaScript function: return true from your JS function

   function CalcTotalAmt() 
 {
//Your Code
 }

.aspx code:

<asp:DropDownList ID="ddl" runat="server"  AutoPostBack="true">
        <asp:ListItem Text="a" Value="a"></asp:ListItem>
         <asp:ListItem Text="b" Value="b"></asp:ListItem>
        </asp:DropDownList>

Second Method: (Tested)

Code in .aspx.cs:

protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Params["__EVENTARGUMENT"] != null && Request.Params["__EVENTARGUMENT"].Equals("ddlchange"))
                ddl_SelectedIndexChanged(sender, e);
            if (!Page.IsPostBack)
            {
                ddl.Attributes.Add("onchange", "CalcTotalAmt();");
            }
        }

        protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Your Code
        }

JavaScript function: return true from your JS function

function CalcTotalAmt() {
         //Your Code
     __doPostBack("ctl00$MainContent$ddl","ddlchange");
 }

.aspx code:

<asp:DropDownList ID="ddl" runat="server"  AutoPostBack="true">
        <asp:ListItem Text="a" Value="a"></asp:ListItem>
         <asp:ListItem Text="b" Value="b"></asp:ListItem>
        </asp:DropDownList>

how to change listen port from default 7001 to something different?

You can change the listen port as per your requirement. This task can be accomplished in two diffrent ways. By changing config.xml file By changing in admin console Change the listen port in config.xml as per your requirement and bounce the domain. Admin Console Login to AdminConsole->Server->Configuration->ListenPort (Change it) Note: It is a bad practice to edit config.xml and try to edit in admin console(It's a good practise as well)

jquery ui Dialog: cannot call methods on dialog prior to initialization

I simply had to add the ScriptManager to the page. Issue resolved.

How to find the socket buffer size of linux

If you want see your buffer size in terminal, you can take a look at:

  • /proc/sys/net/ipv4/tcp_rmem (for read)
  • /proc/sys/net/ipv4/tcp_wmem (for write)

They contain three numbers, which are minimum, default and maximum memory size values (in byte), respectively.

How do I launch the Android emulator from the command line?

list of avd name available on

.android/avd

/SDK_PATH/tools/emulator -netdelay none -netspeed full -avd "AVD_NAME"

How can I move a tag on a git branch to a different commit?

I try to avoid a few things when using Git.

  1. Using knowledge of the internals, e.g. refs/tags. I try to use solely the documented Git commands and avoid using things which require knowledge of the internal contents of the .git directory. (That is to say, I treat Git as a Git user and not a Git developer.)

  2. The use of force when not required.

  3. Overdoing things. (Pushing a branch and/or lots of tags, to get one tag where I want it.)

So here is my non-violent solution for changing a tag, both locally and remotely, without knowledge of the Git internals.

I use it when a software fix ultimately has a problem and needs to be updated/re-released.

git tag -d fix123                # delete the old local tag
git push github :fix123          # delete the old remote tag (use for each affected remote)
git tag fix123 790a621265        # create a new local tag
git push github fix123           # push new tag to remote    (use for each affected remote)

github is a sample remote name, fix123 is a sample tag name, and 790a621265 a sample commit.

How to see the proxy settings on windows?

An update to @rleelr:
It's possible to view proxy settings in Google Chrome:

chrome://net-internals/#http2

Then select

View live HTTP/2 sessions

Then select one of the live sessions (you need to have some tabs open). There you find:

[...]
t=504112 [st= 0] +HTTP2_SESSION  [dt=?]
                  --> host = "play.google.com:443"
                  --> proxy = "PROXY www.xxx.yyy.zzz:8080"
[...]
                              ============================

Is there any way to change input type="date" format?

It's important to distinguish two different formats:

  • The RFC 3339/ISO 8601 "wire format": YYYY-MM-DD. According to the HTML5 specification, this is the format that must be used for the input's value upon form submission or when requested via the DOM API. It is locale and region independent.
  • The format displayed by the user interface control and accepted as user input. Browser vendors are encouraged to follow the user's preferences selection. For example, on Mac OS with the region "United States" selected in the Language & Text preferences pane, Chrome 20 uses the format "m/d/yy".

The HTML5 specification does not include any means of overriding or manually specifying either format.

Most efficient way to see if an ArrayList contains an object in Java

There are three basic options:

1) If retrieval performance is paramount and it is practical to do so, use a form of hash table built once (and altered as/if the List changes).

2) If the List is conveniently sorted or it is practical to sort it and O(log n) retrieval is sufficient, sort and search.

3) If O(n) retrieval is fast enough or if it is impractical to manipulate/maintain the data structure or an alternate, iterate over the List.

Before writing code more complex than a simple iteration over the List, it is worth thinking through some questions.

  • Why is something different needed? (Time) performance? Elegance? Maintainability? Reuse? All of these are okay reasons, apart or together, but they influence the solution.

  • How much control do you have over the data structure in question? Can you influence how it is built? Managed later?

  • What is the life cycle of the data structure (and underlying objects)? Is it built up all at once and never changed, or highly dynamic? Can your code monitor (or even alter) its life cycle?

  • Are there other important constraints, such as memory footprint? Does information about duplicates matter? Etc.

How to make an embedded video not autoplay

fenomas's answer was really good...it got me off of looking into the HTML code. I know that jb was looking for something that works in Captivate, but the question is broad enough to include people working out of Flash (I'm using CS5), so I thought I'd throw in the specific answer to my situation here.

If you're using the stock Adobe FLVPlayback component in Flash (you probably are if you used File > Import > Import Video...), there's an option in the Properties panel, under Component Parameters. Look for 'autoPlay' and uncheck it. That'll stop autoplay when the page loads!

C# - How to add an Excel Worksheet programmatically - Office XP / 2003

This is what i used to add addtional worksheet

Workbook workbook = null;
Worksheet worksheet = null;

workbook = app.Workbooks.Add(1);
workbook.Sheets.Add();

Worksheet additionalWorksheet = workbook.ActiveSheet;

CMD (command prompt) can't go to the desktop

You need to use the change directory command 'cd' to change directory

cd C:\Users\MyName\Desktop

you can use cd \d to change the drive as well.

link for additional resources http://ss64.com/nt/cd.html

Unclosed Character Literal error

String y = "hello";

would work (note the double quotes).

char y = 'h'; this will work for chars (note the single quotes)

but the type is the key: '' (single quotes) for one char, "" (double quotes) for string.

Cannot connect to repo with TortoiseSVN

As stated by David W. "First of all, check your URL" - Our dns entry changed breaking all svn repo connections. Connecting on ip instead of url as Wes stated worked - (now we have to fix our dns)

How to protect Excel workbook using VBA?

  1. in your sample code you must remove the brackets, because it's not a functional assignment; also for documentary reasons I would suggest you use the := notation (see code sample below)

    1. Application.Thisworkbook refers to the book containing the VBA code, not necessarily the book containing the data, so be cautious.

Express the sheet you're working on as a sheet object and pass it, together with a logical variable to the following sub:

Sub SetProtectionMode(MySheet As Worksheet, ProtectionMode As Boolean)

    If ProtectionMode Then
        MySheet.Protect DrawingObjects:=True, Contents:=True, _
                        AllowSorting:=True, AllowFiltering:=True
    Else
        MySheet.Unprotect
    End If
End Sub

Within the .Protect method you can define what you want to allow/disallow. This code block will switch protection on/off - without password in this example, you can add it as a parameter or hardcoded within the Sub. Anyway somewhere the PW will be hardcoded. If you don't want this, just call the Protection Dialog window and let the user decide what to do:

Application.Dialogs(xlDialogProtectDocument).Show

Hope that helps

Good luck - MikeD

Have Excel formulas that return 0, make the result blank

None of the above worked for me today, so I tried putting the 0 in quotes, as shown in the example below.

Example: =IF(INDEX(a,b,c)="0","", INDEX(a,b,c))

Mythical man month 10 lines per developer day - how close on large projects?

One suspects this perennial bit of manager-candy was coined when everything was a sys app written in C because if nothing else the magic number would vary by orders of magnitude depending on the language, scale and nature of the application. And then you have to discount comments and attributes. And ultimately who cares about the number of lines of code written? Are you supposed to be finished when you've reach 10K lines? 100K? So arbitrary.

It's useless.

How to copy a dictionary and only edit the copy

dict2 = dict1 does not copy the dictionary. It simply gives you the programmer a second way (dict2) to refer to the same dictionary.

WPF TemplateBinding vs RelativeSource TemplatedParent

I thought TemplateBinding does not support Freezable types (which includes brush objects). To get around the problem. One can make use of TemplatedParent

Renew Provisioning Profile

Unfortunately renewing does not seem to work in my case. My Ad Hoc Distribution Profile is about to expire in 5 days. I got warnings about that on the iPhone and the Xcode Organizer shows a warning sign next to it as well.

In Apple's provisioning portal it was marked as inactive and there was a button to reactivate it. But still with the same expiry date, 5 days from now. Next, I added two more iPhones to it, yet, the changed profile still expires 5 days from now.

Finally, I deleted the profile in the provisioning portal and created a new one from scratch, using a different name, yet this new one still expires on April 13th, 5 days from now!

That is really frustrating! So I guess I have to wait until after it expires and create a new one then.

In case you are wondering if my developer subscription runs out, it is not. I just renewed it in February.

Loading cross-domain endpoint with AJAX

Your URL doesn't work these days, but your code can be updated with this working solution:

_x000D_
_x000D_
var url = "http://saskatchewan.univ-ubs.fr:8080/SASStoredProcess/do?_username=DARTIES3-2012&_password=P@ssw0rd&_program=%2FUtilisateurs%2FDARTIES3-2012%2FMon+dossier%2Fanalyse_dc&annee=2012&ind=V&_action=execute";_x000D_
_x000D_
url = 'https://google.com'; // TEST URL_x000D_
_x000D_
$.get("https://images"+~~(Math.random()*33)+"-focus-opensocial.googleusercontent.com/gadgets/proxy?container=none&url=" + encodeURI(url), function(data) {_x000D_
    $('div.ajax-field').html(data);_x000D_
});
_x000D_
<div class="ajax-field"></div>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Want to download a Git repository, what do I need (windows machine)?

Install mysysgit. (Same as Greg Hewgill's answer.)

Install Tortoisegit. (Tortoisegit requires mysysgit or something similiar like Cygwin.)

After TortoiseGit is installed, right-click on a folder, select Git Clone..., then enter the Url of the repository, then click Ok.

This answer is not any better than just installing mysysgit, but you can avoid the dreaded command line. :)

How to clear an EditText on click?

Be careful when setting text with an onClick listener on the field you are setting the text. I was doing this and setting the text to an empty string. This was causing the pointer to come up to indicate where my cursor was, which will normally go away after a few seconds. When I did not wait for it to go away before leaving my page causing finish() to be called, it would cause a memory leak and crash my app. Took me a while to figure out what was causing the crash on this one..

Anyway, I would recommend using selectAll() in your on click listener rather than setText() if you can. This way, once the text is selected, the user can start typing and all of the previous text will be cleared.

pic of the suspect pointer: http://i.stack.imgur.com/juJnt.png

iOS9 getting error “an SSL error has occurred and a secure connection to the server cannot be made”

iOS 9 forces connections that are using HTTPS to be TLS 1.2 to avoid recent vulnerabilities. In iOS 8 even unencrypted HTTP connections were supported, so that older versions of TLS didn't make any problems either. As a workaround, you can add this code snippet to your Info.plist:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

*referenced to App Transport Security (ATS)

enter image description here

How to build a DataTable from a DataGridView?

Well, you can do

DataTable data = (DataTable)(dgvMyMembers.DataSource);

and then use

data.Columns.Remove(...);

I think it's the fastest way. This will modify data source table, if you don't want it, then copy of table is reqired. Also be aware that DataGridView.DataSource is not necessarily of DataTable type.

error TS2339: Property 'x' does not exist on type 'Y'

Starting with TypeScript 2.2 using dot notation to access indexed properties is allowed. You won't get error TS2339 on your example.

See Dotted property for types with string index signatures in TypeScript 2.2 release note.

Best way to compare dates in Android

String date = "03/26/2012 11:00:00";
    String dateafter = "03/26/2012 11:59:00";
    SimpleDateFormat dateFormat = new SimpleDateFormat(
            "MM/dd/yyyy hh:mm:ss");
    Date convertedDate = new Date();
    Date convertedDate2 = new Date();
    try {
        convertedDate = dateFormat.parse(date);
        convertedDate2 = dateFormat.parse(dateafter);
        if (convertedDate2.after(convertedDate)) {
            txtView.setText("true");
        } else {
            txtView.setText("false");
        }
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

it return true.. and you can also check before and equal with help of date.before and date.equal..

Replace all occurrences of a String using StringBuilder?

Yes. It is very simple to use String.replaceAll() method:

package com.test;

public class Replace {

    public static void main(String[] args) {
        String input = "Hello World";
        input = input.replaceAll("o", "0");
        System.out.println(input);
    }
}

Output:

Hell0 W0rld

If you really want to use StringBuilder.replace(int start, int end, String str) instead then here you go:

public static void main(String args[]) {
    StringBuilder sb = new StringBuilder("This is a new StringBuilder");

    System.out.println("Before: " + sb);

    String from = "new";
    String to = "replaced";
    sb = sb.replace(sb.indexOf(from), sb.indexOf(from) + from.length(), to);

    System.out.println("After: " + sb);
}

Output:

Before: This is a new StringBuilder
After: This is a replaced StringBuilder

Display HTML snippets in HTML

 //To show xml tags in table columns you will have to encode the tags first

function htmlEncode(value) {
    //create a in-memory div, set it's inner text(which jQuery automatically encodes)
    //then grab the encoded contents back out.  The div never exists on the page.
    return $('<div/>').text(value).html();
}

html = htmlEncode(html)

Found shared references to a collection org.hibernate.HibernateException

I have experienced a great example of reproducing such a problem. Maybe my experience will help someone one day.

Short version

Check that your @Embedded Id of container has no possible collisions.

Long version

When Hibernate instantiates collection wrapper, it searches for already instantiated collection by CollectionKey in internal Map.

For Entity with @Embedded id, CollectionKey wraps EmbeddedComponentType and uses @Embedded Id properties for equality checks and hashCode calculation.

So if you have two entities with equal @Embedded Ids, Hibernate will instantiate and put new collection by the first key and will find same collection for the second key. So two entities with same @Embedded Id will be populated with same collection.

Example

Suppose you have Account entity which has lazy set of loans. And Account has @Embedded Id consists of several parts(columns).

@Entity
@Table(schema = "SOME", name = "ACCOUNT")
public class Account {
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "account")
    private Set<Loan> loans;

    @Embedded
    private AccountId accountId;

    ...
}

@Embeddable
public class AccountId {
    @Column(name = "X")
    private Long x;
    
    @Column(name = "BRANCH")
    private String branchId;
    
    @Column(name = "Z")
    private String z;

    ...
}

Then suppose that Account has additional property mapped by @Embedded Id but has relation to other entity Branch.

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "BRANCH")
@MapsId("accountId.branchId")
@NotFound(action = NotFoundAction.IGNORE)//Look at this!
private Branch branch;

It could happen that you have no FK for Account to Brunch relation id DB so Account.BRANCH column can have any value not presented in Branch table.

According to @NotFound(action = NotFoundAction.IGNORE) if value is not present in related table, Hibernate will load null value for the property.

If X and Y columns of two Accounts are same(which is fine), but BRANCH is different and not presented in Branch table, hibernate will load null for both and Embedded Ids will be equal.

So two CollectionKey objects will be equal and will have same hashCode for different Accounts.

result = {CollectionKey@34809} "CollectionKey[Account.loans#Account@43deab74]"
 role = "Account.loans"
 key = {Account@26451} 
 keyType = {EmbeddedComponentType@21355} 
 factory = {SessionFactoryImpl@21356} 
 hashCode = 1187125168
 entityMode = {EntityMode@17415} "pojo"

result = {CollectionKey@35653} "CollectionKey[Account.loans#Account@33470aa]"
 role = "Account.loans"
 key = {Account@35225} 
 keyType = {EmbeddedComponentType@21355} 
 factory = {SessionFactoryImpl@21356} 
 hashCode = 1187125168
 entityMode = {EntityMode@17415} "pojo"

Because of this, Hibernate will load same PesistentSet for two entities.

How to get current screen width in CSS?

Use the CSS3 Viewport-percentage feature.

Viewport-Percentage Explanation

Assuming you want the body width size to be a ratio of the browser's view port. I added a border so you can see the body resize as you change your browser width or height. I used a ratio of 90% of the view-port size.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
    <title>Styles</title>_x000D_
_x000D_
    <style>_x000D_
        @media screen and (min-width: 480px) {_x000D_
            body {_x000D_
                background-color: skyblue;_x000D_
                width: 90vw;_x000D_
                height: 90vh;_x000D_
                border: groove black;_x000D_
            }_x000D_
_x000D_
            div#main {_x000D_
                font-size: 3vw;_x000D_
            }_x000D_
        }_x000D_
    </style>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
    <div id="main">_x000D_
        Viewport-Percentage Test_x000D_
    </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Capture key press (or keydown) event on DIV element

(1) Set the tabindex attribute:

<div id="mydiv" tabindex="0" />

(2) Bind to keydown:

 $('#mydiv').on('keydown', function(event) {
    //console.log(event.keyCode);
    switch(event.keyCode){
       //....your actions for the keys .....
    }
 });

To set the focus on start:

$(function() {
   $('#mydiv').focus();
});

To remove - if you don't like it - the div focus border, set outline: none in the CSS.

See the table of keycodes for more keyCode possibilities.

All of the code assuming you use jQuery.

#

CSS - how to make image container width fixed and height auto stretched

Try width:inherit to make the image take the width of it's container <div>. It will stretch/shrink it's height to maintain proportion. Don't set the height in the <div>, it will size to fit the image height.

img {
    width:inherit;
}

.item {
    border:1px solid pink;
    width: 120px;
    float: left;
    margin: 3px;
    padding: 3px;
}

JSFiddle example

How to inject Javascript in WebBrowser control?

As a follow-up to the accepted answer, this is a minimal definition of the IHTMLScriptElement interface which does not require to include additional type libraries:

[ComImport, ComVisible(true), Guid(@"3050f28b-98b5-11cf-bb82-00aa00bdce0b")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)]
[TypeLibType(TypeLibTypeFlags.FDispatchable)]
public interface IHTMLScriptElement
{
    [DispId(1006)]
    string text { set; [return: MarshalAs(UnmanagedType.BStr)] get; }
}

So a full code inside a WebBrowser control derived class would look like:

protected override void OnDocumentCompleted(
    WebBrowserDocumentCompletedEventArgs e)
{
    base.OnDocumentCompleted(e);

    // Disable text selection.
    var doc = Document;
    if (doc != null)
    {
        var heads = doc.GetElementsByTagName(@"head");
        if (heads.Count > 0)
        {
            var scriptEl = doc.CreateElement(@"script");
            if (scriptEl != null)
            {
                var element = (IHTMLScriptElement)scriptEl.DomElement;
                element.text =
                    @"function disableSelection()
                    { 
                        document.body.onselectstart=function(){ return false; }; 
                        document.body.ondragstart=function() { return false; };
                    }";
                heads[0].AppendChild(scriptEl);
                doc.InvokeScript(@"disableSelection");
            }
        }
    }
}

Convert js Array() to JSon object for use with JQuery .ajax

You can iterate the key/value pairs of the saveData object to build an array of the pairs, then use join("&") on the resulting array:

var a = [];
for (key in saveData) {
    a.push(key+"="+saveData[key]);
}
var serialized = a.join("&") // a=2&c=1

Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which?

Since the name is likely to change in future versions of Android (currently the latest is AppCompatActivity but it will probably change at some point), I believe a good thing to have is a class Activity that extends AppCompatActivity and then all your activities extend from that one. If tomorrow, they change the name to AppCompatActivity2 for instance you will have to change it just in one place.

How to load my app from Eclipse to my Android phone instead of AVD

Step by step:

  1. Connect your phone to computer via USB
  2. Enable USB debugging on your phone: Settings -> Applications -> Development -> USB debugging
  3. Change Run configuration in your Eclipse project: right click -> Run As -> Run Configurations. In the Target tab choose Always prompt to pick device (or Manual). Then Apply, Run.

In the new window you should see your connected phone.

Create auto-numbering on images/figures in MS Word

I assume you are using the caption feature of Word, that is, captions were not typed in as normal text, but were inserted using Insert > Caption (Word versions before 2007), or References > Insert Caption (in the ribbon of Word 2007 and up). If done correctly, the captions are really 'fields'. You'll know if it is a field if the caption's background turns grey when you put your cursor on them (or is permanently displayed grey).

Captions are fields - Unfortunately fields (like caption fields) are only updated on specific actions, like opening of the document, printing, switching from print view to normal view, etc. The easiest way to force updating of all (caption) fields when you want it is by doing the following:

  1. Select all text in your document (easiest way is to press ctrl-a)
  2. Press F9, this command tells Word to update all fields in the selection.

Captions are normal text - If the caption number is not a field, I am afraid you'll have to edit the text manually.

For loop example in MySQL

drop table if exists foo;
create table foo
(
id int unsigned not null auto_increment primary key,
val smallint unsigned not null default 0
)
engine=innodb;

drop procedure if exists load_foo_test_data;

delimiter #
create procedure load_foo_test_data()
begin

declare v_max int unsigned default 1000;
declare v_counter int unsigned default 0;

  truncate table foo;
  start transaction;
  while v_counter < v_max do
    insert into foo (val) values ( floor(0 + (rand() * 65535)) );
    set v_counter=v_counter+1;
  end while;
  commit;
end #

delimiter ;

call load_foo_test_data();

select * from foo order by id;

PHP Parse error: syntax error, unexpected end of file in a CodeIgniter View

Unexpected end of file means that something else was expected before the PHP parser reached the end of the script.

Judging from your HUGE file, it's probably that you're missing a closing brace (}) from an if statement.

Please at least attempt the following things:

  1. Separate your code from your view logic.
  2. Be consistent, you're using an end ; in some of your embedded PHP statements, and not in others, ie. <?php echo base_url(); ?> vs <?php echo $this->layouts->print_includes() ?>. It's not required, so don't use it (or do, just do one or the other).
  3. Repeated because it's important, separate your concerns. There's no need for all of this code.
  4. Use an IDE, it will help you with errors such as this going forward.

Restart container within pod

There are cases when you want to restart a specific container instead of deleting the pod and letting Kubernetes recreate it.

Doing a kubectl exec POD_NAME -c CONTAINER_NAME /sbin/killall5 worked for me.

(I changed the command from reboot to /sbin/killall5 based on the below recommendations.)

create table in postgreSQL

First the bigint(20) not null auto_increment will not work, simply use bigserial primary key. Then datetime is timestamp in PostgreSQL. All in all:

CREATE TABLE article (
    article_id bigserial primary key,
    article_name varchar(20) NOT NULL,
    article_desc text NOT NULL,
    date_added timestamp default NULL
);

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

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

So this should work:

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

List files with certain extensions with ls and grep

it is easy try to use this command :

ls | grep \.txt$ && ls | grep \.exe

Set background colour of cell to RGB value of data in cell

Sub AddColor()
    For Each cell In Selection
        R = Round(cell.Value)
        G = Round(cell.Offset(0, 1).Value)
        B = Round(cell.Offset(0, 2).Value)
        Cells(cell.Row, 1).Resize(1, 4).Interior.Color = RGB(R, G, B)
    Next cell
End Sub

Assuming that there are 3 columns R, G and B (in this order). Select first column ie R. press alt+F11 and run the above code. We have to select the first column (containing R or red values) and run the code every time we change the values to reflect the changes.

I hope this simpler code helps !

Sending POST data without form

have a look at the php documentation for theese functions you can send post reqeust using them.

fsockopen()
fputs()

or simply use a class like Zend_Http_Client which is also based on socket-conenctions.

also found a neat example using google...

Adding days to a date in Java

Simple, without any other API:

To add 8 days:

Date today=new Date();
long ltime=today.getTime()+8*24*60*60*1000;
Date today8=new Date(ltime);

Take multiple lists into dataframe

I think you're almost there, try removing the extra square brackets around the lst's (Also you don't need to specify the column names when you're creating a dataframe from a dict like this):

import pandas as pd
lst1 = range(100)
lst2 = range(100)
lst3 = range(100)
percentile_list = pd.DataFrame(
    {'lst1Title': lst1,
     'lst2Title': lst2,
     'lst3Title': lst3
    })

percentile_list
    lst1Title  lst2Title  lst3Title
0          0         0         0
1          1         1         1
2          2         2         2
3          3         3         3
4          4         4         4
5          5         5         5
6          6         6         6
...

If you need a more performant solution you can use np.column_stack rather than zip as in your first attempt, this has around a 2x speedup on the example here, however comes at bit of a cost of readability in my opinion:

import numpy as np
percentile_list = pd.DataFrame(np.column_stack([lst1, lst2, lst3]), 
                               columns=['lst1Title', 'lst2Title', 'lst3Title'])

Split list into smaller lists (split in half)

Another take on this problem in 2020 ... Here's a generalization of the problem. I interpret the 'divide a list in half' to be .. (i.e. two lists only and there shall be no spillover to a third array in case of an odd one out etc). For instance, if the array length is 19 and a division by two using // operator gives 9, and we will end up having two arrays of length 9 and one array (third) of length 1 (so in total three arrays). If we'd want a general solution to give two arrays all the time, I will assume that we are happy with resulting duo arrays that are not equal in length (one will be longer than the other). And that its assumed to be ok to have the order mixed (alternating in this case).

"""
arrayinput --> is an array of length N that you wish to split 2 times
"""
ctr = 1 # lets initialize a counter

holder_1 = []
holder_2 = []

for i in range(len(arrayinput)): 

    if ctr == 1 :
        holder_1.append(arrayinput[i])
    elif ctr == 2: 
        holder_2.append(arrayinput[i])

    ctr += 1 

    if ctr > 2 : # if it exceeds 2 then we reset 
        ctr = 1 

This concept works for any amount of list partition as you'd like (you'd have to tweak the code depending on how many list parts you want). And is rather straightforward to interpret. To speed things up , you can even write this loop in cython / C / C++ to speed things up. Then again, I've tried this code on relatively small lists ~ 10,000 rows and it finishes in a fraction of second.

Just my two cents.

Thanks!

Convert array of strings to List<string>

Just use this constructor of List<T>. It accepts any IEnumerable<T> as an argument.

string[] arr = ...
List<string> list = new List<string>(arr);

Do you need to dispose of objects and set them to null?

You never need to set objects to null in C#. The compiler and runtime will take care of figuring out when they are no longer in scope.

Yes, you should dispose of objects that implement IDisposable.

Missing MVC template in Visual Studio 2015

I don't think the accepted answer works anymore. According to Microsoft here, here, and here, has been re-branded to ASP.Net Core. It looks like they've taken down the templates from the general ASP.Net Web Application project type. But now there's a new project type of ASP.Net Core Web Application. enter image description hereI don't see an MVC template for this project type, but I don't think the Core framework has been completely released yet.

onclick event function in JavaScript

<script>
//$(document).ready(function () {
function showcontent() {
        document.getElementById("demo22").innerHTML = "Hello World";
}
//});// end of ready function
</script>

I had the same problem where onclick function calls would not work. I had included the function inside the usual "$(document).ready(function(){});" block used to wrap jquery scripts. Commenting this block out solved the problem.

Java Try Catch Finally blocks without Catch

The finally block is always run after the try block ends, whether try ends normally or abnormally due to an exception, er, throwable.

If an exception is thrown by any of the code within the try block, then the current method simply re-throws (or continues to throw) the same exception (after running the finally block).

If the finally block throws an exception / error / throwable, and there is already a pending throwable, it gets ugly. Quite frankly, I forget exactly what happens (so much for my certification years ago). I think both throwables get linked together, but there is some special voodoo you have to do (i.e. - a method call I would have to look up) to get the original problem before the "finally" barfed, er, threw up.

Incidentally, try/finally is a pretty common thing to do for resource management, since java has no destructors.

E.g. -

r = new LeakyThing();
try { useResource( r); }
finally { r.release(); }  // close, destroy, etc

"Finally", one more tip: if you do bother to put in a catch, either catch specific (expected) throwable subclasses, or just catch "Throwable", not "Exception", for a general catch-all error trap. Too many problems, such as reflection goofs, throw "Errors", rather than "Exceptions", and those will slip right by any "catch all" coded as:

catch ( Exception e) ...  // doesn't really catch *all*, eh?

do this instead:

catch ( Throwable t) ...

How to get everything after a certain character?

Here is the method by using explode:

$text = explode('_', '233718_This_is_a_string', 2)[1]; // Returns This_is_a_string

or:

$text = @end((explode('_', '233718_This_is_a_string', 2)));

By specifying 2 for the limit parameter in explode(), it returns array with 2 maximum elements separated by the string delimiter. Returning 2nd element ([1]), will give the rest of string.


Here is another one-liner by using strpos (as suggested by @flu):

$needle = '233718_This_is_a_string';
$text = substr($needle, (strpos($needle, '_') ?: -1) + 1); // Returns This_is_a_string

Android Studio Gradle: Error:Execution failed for task ':app:processDebugGoogleServices'. > No matching client found for package

I meet the problem when using Firebase, i think different package cause the problem.

I solved by adding packeage of new app within Firebase Console, and download google-services.json again. enter image description here enter image description here enter image description here enter image description here

Embed YouTube video - Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

If embed no longer works for you, try with /v instead:

<iframe width="420" height="315" src="https://www.youtube.com/v/A6XUVjK9W4o" frameborder="0" allowfullscreen></iframe>

Spring MVC: Error 400 The request sent by the client was syntactically incorrect

I was facing a similar issue and found that a few fields like Date were not getting a concrete value, once given the values things worked fine. Please make sure you do not have date or any other field present on the form which needs a concrete value.

Regular expression for extracting tag attributes

If you want to be general, you have to look at the precise specification of the a tag, like here. But even with that, if you do your perfect regexp, what if you have malformed html?

I would suggest to go for a library to parse html, depending on the language you work with: e.g. like python's Beautiful Soup.

How/When does Execute Shell mark a build as failure in Jenkins?

In Jenkins ver. 1.635, it is impossible to show a native environment variable like this:

$BUILD_NUMBER or ${BUILD_NUMBER}

In this case, you have to set it in an other variable.

set BUILDNO = $BUILD_NUMBER
$BUILDNO

PHP Email sending BCC

You were setting BCC but then overwriting the variable with the FROM

$to = "[email protected]";
     $subject .= "".$emailSubject."";
 $headers .= "Bcc: ".$emailList."\r\n";
 $headers .= "From: [email protected]\r\n" .
     "X-Mailer: php";
     $headers .= "MIME-Version: 1.0\r\n";
     $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
 $message = '<html><body>';
 $message .= 'THE MESSAGE FROM THE FORM';

     if (mail($to, $subject, $message, $headers)) {
     $sent = "Your email was sent!";
     } else {
      $sent = ("Error sending email.");
     }

What is makeinfo, and how do I get it?

If you build packages from scratch:

Specifically, if you build bash from source, install docs, including man pages, will fail (silently) without makeinfo available.

Referencing a string in a string array resource with xml

The better option would be to just use the resource returned array as an array, meaning :

getResources().getStringArray(R.array.your_array)[position]

This is a shortcut approach of above mentioned approaches but does the work in the fashion you want. Otherwise android doesnt provides direct XML indexing for xml based arrays.

How to get substring of NSString?

Here's a slightly less complicated answer:

NSString *myString = @"abcdefg";
NSString *mySmallerString = [myString substringToIndex:4];

See also substringWithRange and substringFromIndex

how to open an URL in Swift3

All you need is:

guard let url = URL(string: "http://www.google.com") else {
  return //be safe
}

if #available(iOS 10.0, *) {
    UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
    UIApplication.shared.openURL(url)
}

How do I make a Windows batch script completely silent?

To suppress output, use redirection to NUL.

There are two kinds of output that console commands use:

  • standard output, or stdout,

  • standard error, or stderr.

Of the two, stdout is used more often, both by internal commands, like copy, and by console utilities, or external commands, like find and others, as well as by third-party console programs.

>NUL suppresses the standard output and works fine e.g. for suppressing the 1 file(s) copied. message of the copy command. An alternative syntax is 1>NUL. So,

COPY file1 file2 >NUL

or

COPY file1 file2 1>NUL

or

>NUL COPY file1 file2

or

1>NUL COPY file1 file2

suppresses all of COPY's standard output.

To suppress error messages, which are typically printed to stderr, use 2>NUL instead. So, to suppress a File Not Found message that DEL prints when, well, the specified file is not found, just add 2>NUL either at the beginning or at the end of the command line:

DEL file 2>NUL

or

2>NUL DEL file

Although sometimes it may be a better idea to actually verify whether the file exists before trying to delete it, like you are doing in your own solution. Note, however, that you don't need to delete the files one by one, using a loop. You can use a single command to delete the lot:

IF EXIST "%scriptDirectory%*.noext" DEL "%scriptDirectory%*.noext"

How npm start runs a server on port 8000

You can change the port in the console by running the following on Windows:

SET PORT=8000

For Mac, Linux or Windows WSL use the following:

export PORT=8000

The export sets the environment variable for the current shell and all child processes like npm that might use it.

If you want the environment variable to be set just for the npm process, precede the command with the environment variable like this (on Mac and Linux and Windows WSL):

PORT=8000 npm run start

Make <body> fill entire screen?

If you have a border or padding, then the solution

_x000D_
_x000D_
html, body {_x000D_
    margin: 0;_x000D_
    height: 100%;_x000D_
}_x000D_
body {_x000D_
    border: solid red 5px;_x000D_
    border-radius: 2em;_x000D_
}
_x000D_
_x000D_
_x000D_

produces the imperfect rendering

not good

To get it right in the presence of a border or padding

good

use instead

_x000D_
_x000D_
html, body {_x000D_
    margin: 0;_x000D_
    height: 100%;_x000D_
}_x000D_
body {_x000D_
    box-sizing: border-box;_x000D_
    border: solid red 5px;_x000D_
    border-radius: 2em;_x000D_
}
_x000D_
_x000D_
_x000D_

as Martin pointed out, although overflow: hidden is not needed.

(2018 - tested with Chrome 69 and IE 11)

How to use the priority queue STL for objects?

You need to provide a valid strict weak ordering comparison for the type stored in the queue, Person in this case. The default is to use std::less<T>, which resolves to something equivalent to operator<. This relies on it's own stored type having one. So if you were to implement

bool operator<(const Person& lhs, const Person& rhs); 

it should work without any further changes. The implementation could be

bool operator<(const Person& lhs, const Person& rhs)
{
  return lhs.age < rhs.age;
}

If the the type does not have a natural "less than" comparison, it would make more sense to provide your own predicate, instead of the default std::less<Person>. For example,

struct LessThanByAge
{
  bool operator()(const Person& lhs, const Person& rhs) const
  {
    return lhs.age < rhs.age;
  }
};

then instantiate the queue like this:

std::priority_queue<Person, std::vector<Person>, LessThanByAge> pq;

Concerning the use of std::greater<Person> as comparator, this would use the equivalent of operator> and have the effect of creating a queue with the priority inverted WRT the default case. It would require the presence of an operator> that can operate on two Person instances.

How to convert a char to a String?

Use the Character.toString() method like so:

char mChar = 'l';
String s = Character.toString(mChar);

How to format Joda-Time DateTime to only mm/dd/yyyy?

This works

String x = "22/06/2012";
String y = "25/10/2014";

String datestart = x;
String datestop = y;

//DateTimeFormatter format = DateTimeFormat.forPattern("dd/mm/yyyy");
SimpleDateFormat  format = new SimpleDateFormat("dd/mm/yyyy");

Date d1 = null;
Date d2 = null;

try {
    d1 =  format.parse(datestart);
    d2 = format.parse(datestop);

    DateTime dt1 = new DateTime(d1);
    DateTime dt2 = new DateTime(d2);

    //Period
    period = new Period (dt1,dt2);

    //calculate days
    int days = Days.daysBetween(dt1, dt2).getDays();


} catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

jQuery val is undefined?

you may forgot to wrap your object with $()

  var tableChild = children[i];
  tableChild.val("my Value");// this is wrong 

and the ccorrect one is

$(tableChild).val("my Value");// this is correct

SEVERE: ContainerBase.addChild: start:org.apache.catalina.LifecycleException: Failed to start error

This issue arises because of different reasons. It might encountered if you are using Spring boot built war file. As Spring boot web and rest starter projects jars do have embedded Tomcat in it, hence fails with "SEVERE: ContainerBase.addChild: start: org.apache.catalina.LifecycleException".

You can fix this by exclusion of the embedded tomcat at the time of packaging by using exclusions in case of maven.

Maven dependency of "spring-boot-starter-web" will look like

   <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

jQuery dialog popup

This HTML is fine:

<a href="#" id="contactUs">Contact Us</a>                   
<div id="dialog" title="Contact form">
  <p>appear now</p>
</div>

You need to initialize the Dialog (not sure if you are doing this):

$(function() {
  // this initializes the dialog (and uses some common options that I do)
  $("#dialog").dialog({
    autoOpen : false, modal : true, show : "blind", hide : "blind"
  });

  // next add the onclick handler
  $("#contactUs").click(function() {
    $("#dialog").dialog("open");
    return false;
  });
});

How to initialize struct?

Structure types should, whenever practical, either have all of their state encapsulated in public fields which may independently be set to any values which are valid for their respective type, or else behave as a single unified value which can only bet set via constructor, factory, method, or else by passing an instance of the struct as an explicit ref parameter to one of its public methods. Contrary to what some people claim, that there's nothing wrong with a struct having public fields, if it is supposed to represent a set of values which may sensibly be either manipulated individually or passed around as a group (e.g. the coordinates of a point). Historically, there have been problems with structures that had public property setters, and a desire to avoid public fields (implying that setters should be used instead) has led some people to suggest that mutable structures should be avoided altogether, but fields do not have the problems that properties had. Indeed, an exposed-field struct is the ideal representation for a loose collection of independent variables, since it is just a loose collection of variables.

In your particular example, however, it appears that the two fields of your struct are probably not supposed to be independent. There are three ways your struct could sensibly be designed:

  • You could have the only public field be the string, and then have a read-only "helper" property called length which would report its length if the string is non-null, or return zero if the string is null.

  • You could have the struct not expose any public fields, property setters, or mutating methods, and have the contents of the only field--a private string--be specified in the object's constructor. As above, length would be a property that would report the length of the stored string.

  • You could have the struct not expose any public fields, property setters, or mutating methods, and have two private fields: one for the string and one for the length, both of which would be set in a constructor that takes a string, stores it, measures its length, and stores that. Determining the length of a string is sufficiently fast that it probably wouldn't be worthwhile to compute and cache it, but it might be useful to have a structure that combined a string and its GetHashCode value.

It's important to be aware of a detail with regard to the third design, however: if non-threadsafe code causes one instance of the structure to be read while another thread is writing to it, that may cause the accidental creation of a struct instance whose field values are inconsistent. The resulting behaviors may be a little different from those that occur when classes are used in non-threadsafe fashion. Any code having anything to do with security must be careful not to assume that structure fields will be in a consistent state, since malicious code--even in a "full trust" enviroment--can easily generate structs whose state is inconsistent if that's what it wants to do.

PS -- If you wish to allow your structure to be initialized using an assignment from a string, I would suggest using an implicit conversion operator and making Length be a read-only property that returns the length of the underlying string if non-null, or zero if the string is null.

Visual Studio "Could not copy" .... during build

I think I solved it removing the check mark to Break all processes when one process breaks in Debug options (op's first screenshot->second option).
It's been building/running well for a while since I unchecked it.
I'm using MySql NET Connector and DevExpress controls in my project. May be one of them was not disposing connections, bindings, etc. well because of this flag beeing activated.

EDITED: definitely it works! No more 'Unable to copy file' and no more Form designer errors.

VS2010 How to include files in project, to copy them to build output directory automatically during build or publish

In my case, setting Copy to Output Directory to Copy Always and Build did not do the trick, while Rebuild did.

Hope this helps someone!

How to get id from URL in codeigniter?

$product_id = $this->input->get('id', TRUE);
echo $product_id;

How to increase Maximum Upload size in cPanel?

I have found the answer and solution to this problem. Before, I did not know that php.ini resides where in wordpress files. Now I have found that file in wp-admin directory where I placed the code

post_max_size 33M
upload_max_filesize 32M

then it worked. It increases the upload file size for my worpdress website. But, it is the same 2M as was before on cPanel.

How to tar certain file types in all subdirectories?

If you're using bash version > 4.0, you can exploit shopt -s globstar to make short work of this:

shopt -s globstar; tar -czvf deploy.tar.gz **/Alice*.yml **/Bob*.json

this will add all .yml files that starts with Alice from any sub-directory and add all .json files that starts with Bob from any sub-directory.

Convert a string to int using sql query

Try this one, it worked for me in Athena:

cast(MyVarcharCol as integer)

How to convert these strange characters? (ë, Ã, ì, ù, Ã)

These are utf-8 encoded characters. Use utf8_decode() to convert them to normal ISO-8859-1 characters.

Get screen width and height in Android

Just use the function below that returns width and height of the screen size as an array of integers

private int[] getScreenSIze(){
        DisplayMetrics displaymetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        int h = displaymetrics.heightPixels;
        int w = displaymetrics.widthPixels;

        int[] size={w,h};
        return size;

    }

On your onCreate function or button click add the following code to output the screen sizes as shown below

 int[] screenSize= getScreenSIze();
        int width=screenSize[0];
        int height=screenSize[1];
        screenSizes.setText("Phone Screen sizes \n\n  width = "+width+" \n Height = "+height);

Finding longest string in array

In case you expect more than one maximum this will work:

_.maxBy(Object.entries(_.groupBy(x, y => y.length)), y => parseInt(y[0]))[1]

It uses lodash and returns an array.

How to use executables from a package installed locally in node_modules?

Use npm run[-script] <script name>

After using npm to install the bin package to your local ./node_modules directory, modify package.json to add <script name> like this:

$ npm install --save learnyounode
$ edit packages.json
>>> in packages.json
...
"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "learnyounode": "learnyounode"
},
...
$ npm run learnyounode

It would be nice if npm install had a --add-script option or something or if npm run would work without adding to the scripts block.

Oracle: If Table Exists

I prefer to specify the table and the schema owner.

Watch out for case sensitivity as well. (see "upper" clause below).

I threw a couple of different objects in to show that is can be used in places besides TABLEs.

.............

declare
   v_counter int;
begin
 select count(*) into v_counter from dba_users where upper(username)=upper('UserSchema01');
   if v_counter > 0 then
      execute immediate 'DROP USER UserSchema01 CASCADE';
   end if; 
end;
/



CREATE USER UserSchema01 IDENTIFIED BY pa$$word
  DEFAULT TABLESPACE users
  TEMPORARY TABLESPACE temp
  QUOTA UNLIMITED ON users;

grant create session to UserSchema01;  

And a TABLE example:

declare
   v_counter int;
begin
 select count(*) into v_counter from all_tables where upper(TABLE_NAME)=upper('ORDERS') and upper(OWNER)=upper('UserSchema01');
   if v_counter > 0 then
      execute immediate 'DROP TABLE UserSchema01.ORDERS';
   end if; 
end;
/   

Compare two date formats in javascript/jquery

This is already in :

Age from Date of Birth using JQuery

or alternatively u can use Date.parse() as in

var date1 = new Date("10/25/2011");
var date2 = new Date("09/03/2010");
var date3 = new Date(Date.parse(date1) - Date.parse(date2));

How to simulate a touch event in Android?

Here is a monkeyrunner script that sends touch and drags to an application. I have been using this to test that my application can handle rapid repetitive swipe gestures.

# This is a monkeyrunner jython script that opens a connection to an Android
# device and continually sends a stream of swipe and touch gestures.
#
# See http://developer.android.com/guide/developing/tools/monkeyrunner_concepts.html
#
# usage: monkeyrunner swipe_monkey.py
#

# Imports the monkeyrunner modules used by this program
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice

# Connects to the current device
device = MonkeyRunner.waitForConnection()

# A swipe left from (x1, y) to (x2, y) in 2 steps
y = 400
x1 = 100
x2 = 300
start = (x1, y)
end = (x2, y)
duration = 0.2
steps = 2
pause = 0.2

for i in range(1, 250):
    # Every so often inject a touch to spice things up!
    if i % 9 == 0:
        device.touch(x2, y, 'DOWN_AND_UP')
        MonkeyRunner.sleep(pause)
    # Swipe right
    device.drag(start, end, duration, steps)
    MonkeyRunner.sleep(pause)
    # Swipe left
    device.drag(end, start, duration, steps)
    MonkeyRunner.sleep(pause)

Passing functions with arguments to another function in Python?

This is what lambda is for:

def perform(f):
    f()

perform(lambda: action1())
perform(lambda: action2(p))
perform(lambda: action3(p, r))

Changing SQL Server collation to case insensitive from case sensitive?

You can do that but the changes will affect for new data that is inserted on the database. On the long run follow as suggested above.

Also there are certain tricks you can override the collation, such as parameters for stored procedures or functions, alias data types, and variables are assigned the default collation of the database. To change the collation of an alias type, you must drop the alias and re-create it.

You can override the default collation of a literal string by using the COLLATE clause. If you do not specify a collation, the literal is assigned the database default collation. You can use DATABASEPROPERTYEX to find the current collation of the database.

You can override the server, database, or column collation by specifying a collation in the ORDER BY clause of a SELECT statement.

Foreign key referring to primary keys across multiple tables?

You can probably add two foreign key constraints (honestly: I've never tried it), but it'd then insist the parent row exist in both tables.

Instead you probably want to create a supertype for your two employee subtypes, and then point the foreign key there instead. (Assuming you have a good reason to split the two types of employees, of course).

                 employee       
employees_ce     ————————       employees_sn
————————————     type           ————————————
empid —————————> empid <——————— empid
name               /|\          name
                    |  
                    |  
      deductions    |  
      ——————————    |  
      empid ————————+  
      name

type in the employee table would be ce or sn.

How to download videos from youtube on java?

I know i am answering late. But this code may useful for some one. So i am attaching it here.

Use the following java code to download the videos from YouTube.

package com.mycompany.ytd;

import java.io.File;
import java.net.URL;
import com.github.axet.vget.VGet;

/**
 *
 * @author Manindar
 */
public class YTD {

    public static void main(String[] args) {
        try {
            String url = "https://www.youtube.com/watch?v=s10ARdfQUOY";
            String path = "D:\\Manindar\\YTD\\";
            VGet v = new VGet(new URL(url), new File(path));
            v.download();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

Add the below Dependency in your POM.XML file

        <dependency>
            <groupId>com.github.axet</groupId>
            <artifactId>vget</artifactId>
            <version>1.1.33</version>
        </dependency>

Hope this will be useful.

How to unzip files programmatically in Android?

Based on Vasily Sochinsky's answer a bit tweaked & with a small fix:

public static void unzip(File zipFile, File targetDirectory) throws IOException {
    ZipInputStream zis = new ZipInputStream(
            new BufferedInputStream(new FileInputStream(zipFile)));
    try {
        ZipEntry ze;
        int count;
        byte[] buffer = new byte[8192];
        while ((ze = zis.getNextEntry()) != null) {
            File file = new File(targetDirectory, ze.getName());
            File dir = ze.isDirectory() ? file : file.getParentFile();
            if (!dir.isDirectory() && !dir.mkdirs())
                throw new FileNotFoundException("Failed to ensure directory: " +
                        dir.getAbsolutePath());
            if (ze.isDirectory())
                continue;
            FileOutputStream fout = new FileOutputStream(file);
            try {
                while ((count = zis.read(buffer)) != -1)
                    fout.write(buffer, 0, count);
            } finally {
                fout.close();
            }
            /* if time should be restored as well
            long time = ze.getTime();
            if (time > 0)
                file.setLastModified(time);
            */
        }
    } finally {
        zis.close();
    }
}

Notable differences

  • public static - this is a static utility method that can be anywhere.
  • 2 File parameters because String are :/ for files and one could not specify where the zip file is to be extracted before. Also path + filename concatenation > https://stackoverflow.com/a/412495/995891
  • throws - because catch late - add a try catch if really not interested in them.
  • actually makes sure that the required directories exist in all cases. Not every zip contains all the required directory entries in advance of file entries. This had 2 potential bugs:
    • if the zip contains an empty directory and instead of the resulting directory there is an existing file, this was ignored. The return value of mkdirs() is important.
    • could crash on zip files that don't contain directories.
  • increased write buffer size, this should improve performance a bit. Storage is usually in 4k blocks and writing in smaller chunks is usually slower than necessary.
  • uses the magic of finally to prevent resource leaks.

So

unzip(new File("/sdcard/pictures.zip"), new File("/sdcard"));

should do the equivalent of the original

unpackZip("/sdcard/", "pictures.zip")

How do I get Fiddler to stop ignoring traffic to localhost?

For Fiddler to capture traffic from localhost on local IIS, there are 3 steps (It worked on my computer):

  1. Click Tools > Fiddler Options. Ensure Allow remote clients to connect is checked. Close Fiddler.

enter image description here

  1. Create a new DWORD named ReverseProxyForPort inside KEY_CURRENT_USER\SOFTWARE\Microsoft\Fiddler2. Set the DWORD to port 80 (choose decimal here). Restart Fiddler.

enter image description here

  1. Add port 8888 to the addresses defined in your client. For example localhost:8888/MyService/WebAPI/v1/

How to make external HTTP requests with Node.js

node-http-proxy is a great solution as was suggested by @hross above. If you're not deadset on using node, we use NGINX to do the same thing. It works really well with node. We use it for example to process SSL requests before forwarding them to node. It can also handle cacheing and forwarding routes. Yay!

Append text using StreamWriter

using(StreamWriter writer = new StreamWriter("debug.txt", true))
{
  writer.WriteLine("whatever you text is");
}

The second "true" parameter tells it to append.

http://msdn.microsoft.com/en-us/library/36b035cb.aspx

Maximum length of HTTP GET request

Technically, I have seen HTTP GET will have issues if the URL length goes beyond 2000 characters. In that case, it's better to use HTTP POST or split the URL.

How to assign the output of a command to a Makefile variable

Use the Make shell builtin like in MY_VAR=$(shell echo whatever)

me@Zack:~$make
MY_VAR IS whatever

me@Zack:~$ cat Makefile 
MY_VAR := $(shell echo whatever)

all:
    @echo MY_VAR IS $(MY_VAR)

How to pass optional parameters while omitting some other optional parameters?

you can use optional variable by ? or if you have multiple optional variable by ..., example:

function details(name: string, country="CA", address?: string, ...hobbies: string) {
    // ...
}

In the above:

  • name is required
  • country is required and has a default value
  • address is optional
  • hobbies is an array of optional params

Html.Textbox VS Html.TextboxFor

The TextBoxFor is a newer MVC input extension introduced in MVC2.

The main benefit of the newer strongly typed extensions is to show any errors / warnings at compile-time rather than runtime.

See this page.

http://weblogs.asp.net/scottgu/archive/2010/01/10/asp-net-mvc-2-strongly-typed-html-helpers.aspx

Array inside a JavaScript Object?

_x000D_
_x000D_
var defaults = {_x000D_
_x000D_
  "background-color": "#000",_x000D_
  color: "#fff",_x000D_
  weekdays: [_x000D_
    {0: 'sun'},_x000D_
    {1: 'mon'},_x000D_
    {2: 'tue'},_x000D_
    {3: 'wed'},_x000D_
    {4: 'thu'},_x000D_
    {5: 'fri'},_x000D_
    {6: 'sat'}_x000D_
  ]_x000D_
_x000D_
};_x000D_
               _x000D_
console.log(defaults.weekdays[3]);
_x000D_
_x000D_
_x000D_

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

i had same problem i fix this using if developing jsp, put mysql connetor into WEB-INF->lib folder after puting that in eclipse right click and go build-path -> configure build patha in library tab add external jar file give location where lib folder is

Android ACTION_IMAGE_CAPTURE Intent

To follow up on Yenchi's comment above, the OK button will also do nothing if the camera app can't write to the directory in question.

That means that you can't create the file in a place that's only writeable by your application (for instance, something under getCacheDir()) Something under getExternalFilesDir() ought to work, however.

It would be nice if the camera app printed an error message to the logs if it could not write to the specified EXTRA_OUTPUT path, but I didn't find one.

How do I jump to a closing bracket in Visual Studio Code?

You can learn commands from the command palette Ctrl/Cmd + Shift + P). Look for "Go to Bracket". The keybinding is also shown there.

How to Get a Sublist in C#

Would it be as easy as running a LINQ query on your List?

List<string> mylist = new List<string>{ "hello","world","foo","bar"};
List<string> listContainingLetterO = mylist.Where(x=>x.Contains("o")).ToList();

What is the pythonic way to detect the last element in a 'for' loop?

Although that question is pretty old, I came here via google and I found a quite simple way: List slicing. Let's say you want to put an '&' between all list entries.

s = ""
l = [1, 2, 3]
for i in l[:-1]:
    s = s + str(i) + ' & '
s = s + str(l[-1])

This returns '1 & 2 & 3'.

How do I find the date a video (.AVI .MP4) was actually recorded?

Quick Command for Finding Date/Time Metadata in Many Video Files

The following command has served me well in finding date/time metadata on various AVI/MP4 videos:

ffmpeg -i /path/to/video.mp4 -dump

Note: as mentioned in other answers, there is no guarantee that such information is available in all video files or available in a specific format.

Abbreviated Sample Output for Some AVI File

    Metadata:
      Make            : FUJIFILM
      Model           : FinePix AX655
      DateTime        : 2014:08:25 05:19:45
      JPEGInterchangeFormat:     658
      JPEGInterchangeFormatLength:    1521
      Copyright       :     
      DateTimeOriginal: 2014:08:25 05:19:45
      DateTimeDigitized: 2014:08:25 05:19:45

Abbreviated Sample Output for Some MP4 File

  Metadata:
    major_brand     : mp41
    minor_version   : 538120216
    compatible_brands: mp41
    creation_time   : 2018-03-13T15:43:24.000000Z

How to remove certain characters from a string in C++?

Lot of good answers, here is another way to clean up a string of numbers, is not deleting chars but by moving the numbers out.

string str("(555) 555-5555"), clean;
for (char c : str)
    if (c >= 48 and c <= 57)
        clean.push_back(c);

Rails create or update magic?

The sequel gem adds an update_or_create method which seems to do what you're looking for.

Create a sample login page using servlet and JSP?

As I can see, you are comparing the message with the empty string using ==.

Its very hard to write the full code, but I can tell the flow of code - first, create db class & method inide that which will return the connection. second, create a servelet(ex-login.java) & import that db class onto that servlet. third, create instance of imported db class with the help of new operator & call the connection method of that db class. fourth, creaet prepared statement & execute statement & put this code in try catch block for exception handling.Use if-else condition in the try block to navigate your login page based on success or failure.

I hope, it will help you. If any problem, then please revert.

Nikhil Pahariya

What are static factory methods?

Readability can be improved by static factory methods:

Compare

public class Foo{
  public Foo(boolean withBar){
    //...
  }
}

//...

// What exactly does this mean?
Foo foo = new Foo(true);
// You have to lookup the documentation to be sure.
// Even if you remember that the boolean has something to do with a Bar
// you might not remember whether it specified withBar or withoutBar.

to

public class Foo{
  public static Foo createWithBar(){
    //...
  }

  public static Foo createWithoutBar(){
    //...
  }
}

// ...

// This is much easier to read!
Foo foo = Foo.createWithBar();

Best approach to real time http streaming to HTML5 video client

Take a look at JSMPEG project. There is a great idea implemented there — to decode MPEG in the browser using JavaScript. Bytes from encoder (FFMPEG, for example) can be transfered to browser using WebSockets or Flash, for example. If community will catch up, I think, it will be the best HTML5 live video streaming solution for now.

OpenSSL Verify return code: 20 (unable to get local issuer certificate)

put your CA & root certificate in /usr/share/ca-certificate or /usr/local/share/ca-certificate. Then

dpkg-reconfigure ca-certificates

or even reinstall ca-certificate package with apt-get.

After doing this your certificate is collected into system's DB: /etc/ssl/certs/ca-certificates.crt

Then everything should be fine.

Is it bad to have my virtualenv directory inside my git repository?

If you know which operating systems your application will be running on, I would create one virtualenv for each system and include it in my repository. Then I would make my application detect which system it is running on and use the corresponding virtualenv.

The system could e.g. be identified using the platform module.

In fact, this is what I do with an in-house application I have written, and to which I can quickly add a new system's virtualenv in case it is needed. This way, I do not have to rely on that pip will be able to successfully download the software my application requires. I will also not have to worry about compilation of e.g. psycopg2 which I use.

If you do not know which operating system your application may run on, you are probably better off using pip freeze as suggested in other answers here.

Count records for every month in a year

Try This query:

SELECT 
  SUM(CASE datepart(month,ARR_DATE) WHEN 1 THEN 1 ELSE 0 END) AS 'January',
  SUM(CASE datepart(month,ARR_DATE) WHEN 2 THEN 1 ELSE 0 END) AS 'February',
  SUM(CASE datepart(month,ARR_DATE) WHEN 3 THEN 1 ELSE 0 END) AS 'March',
  SUM(CASE datepart(month,ARR_DATE) WHEN 4 THEN 1 ELSE 0 END) AS 'April',
  SUM(CASE datepart(month,ARR_DATE) WHEN 5 THEN 1 ELSE 0 END) AS 'May',
  SUM(CASE datepart(month,ARR_DATE) WHEN 6 THEN 1 ELSE 0 END) AS 'June',
  SUM(CASE datepart(month,ARR_DATE) WHEN 7 THEN 1 ELSE 0 END) AS 'July',
  SUM(CASE datepart(month,ARR_DATE) WHEN 8 THEN 1 ELSE 0 END) AS 'August',
  SUM(CASE datepart(month,ARR_DATE) WHEN 9 THEN 1 ELSE 0 END) AS 'September',
  SUM(CASE datepart(month,ARR_DATE) WHEN 10 THEN 1 ELSE 0 END) AS 'October',
  SUM(CASE datepart(month,ARR_DATE) WHEN 11 THEN 1 ELSE 0 END) AS 'November',
  SUM(CASE datepart(month,ARR_DATE) WHEN 12 THEN 1 ELSE 0 END) AS 'December',
  SUM(CASE datepart(year,ARR_DATE) WHEN 2012 THEN 1 ELSE 0 END) AS 'TOTAL'
FROM
    sometable
WHERE
  ARR_DATE BETWEEN '2012/01/01' AND '2012/12/31' 

SelectedValue vs SelectedItem.Value of DropDownList

Be careful using SelectedItem.Text... If there is no item selected, then SelectedItem will be null and SelectedItem.Text will generate a null-value exception.

.NET should have provided a SelectedText property like the SelectedValue property that returns String.Empty when there is no selected item.

how to clear JTable

I had to get clean table without columns. I have done folowing:

jMyTable.setModel(new DefaultTableModel());

DateTimePicker: pick both date and time

Set the Format to Custom and then specify the format:

dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = "MM/dd/yyyy hh:mm:ss";  

or however you want to lay it out. You could then type in directly the date/time. If you use MMM, you'll need to use the numeric value for the month for entry, unless you write some code yourself for that (e.g., 5 results in May)

Don't know about the picker for date and time together. Sounds like a custom control to me.

Modelling an elevator using Object-Oriented Analysis and Design

Thing's to be Consider While Designing the Elevator System,

Elevator
Floor/Location Identifier
Number of steps
Rotation speed
Daterange
InstallationDate
MaintainenceDate
Department Identifier
AllowedWeight
Detail / Description
Poison Ratio (Statistics)
Start
Stop
SetDirection
SetRotationSpeed
EmergencyStop = Stop + Alert
EmergencyAccidentSenser Handler

Each button press results in an elevator request which has to be served. Each of these requests is tracked at a global place

The number of elevators in the building will be determined by the user. The building will contain a fixed number of floors. The number of passengers that can fit into the elevator will be fixed. The passengers will be counted as they leave the elevator at their destination floor. The destination floor will be determined using a "random" Poisson interval. When all of the passengers in the elevator have reached their destination floors, the elevator will return to the lobby to pickup more passengers

How do I create a view controller file after creating a new view controller?

To add new ViewController once you have have an existing ViewController, follow below step:

  1. Click on background of Main.storyboard.

  2. Search and select ViewController from object library at the utility window.

  3. Drag and drop it in background to create a new ViewController.

How do I configure git to ignore some files locally?

You have several options:

  • Leave a dirty (or uncommitted) .gitignore file in your working dir (or apply it automatically using topgit or some other such patch tool).
  • Put the excludes in your $GIT_DIR/info/exclude file, if this is specific to one tree.
  • Run git config --global core.excludesfile ~/.gitignore and add patterns to your ~/.gitignore. This option applies if you want to ignore certain patterns across all trees. I use this for .pyc and .pyo files, for example.

Also, make sure you are using patterns and not explicitly enumerating files, when applicable.

Is multiplication and division using shift operators in C actually faster?

Short answer: Not likely.

Long answer: Your compiler has an optimizer in it that knows how to multiply as quickly as your target processor architecture is capable. Your best bet is to tell the compiler your intent clearly (i.e. i*2 rather than i << 1) and let it decide what the fastest assembly/machine code sequence is. It's even possible that the processor itself has implemented the multiply instruction as a sequence of shifts & adds in microcode.

Bottom line--don't spend a lot of time worrying about this. If you mean to shift, shift. If you mean to multiply, multiply. Do what is semantically clearest--your coworkers will thank you later. Or, more likely, curse you later if you do otherwise.

LINQ Orderby Descending Query

I think this first failed because you are ordering value which is null. If Delivery is a foreign key associated table then you should include this table first, example below:

var itemList = from t in ctn.Items.Include(x=>x.Delivery)
                    where !t.Items && t.DeliverySelection
                    orderby t.Delivery.SubmissionDate descending
                    select t;

cannot import name patterns

You don't need those imports. The only thing you need in your urls.py (to start) is:

from django.conf.urls.defaults import *

# This two if you want to enable the Django Admin: (recommended)
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls)),
    # ... your url patterns
)

NOTE: This solution was intended for Django <1.6. This was actually the code generated by Django itself. For newer version, see Jacob Hume's answer.

How to set all elements of an array to zero or any same value?

You could use memset, if you sure about the length.

memset(ptr, 0x00, length)

"Insufficient Storage Available" even there is lot of free space in device memory

When it comes to areal device, the behavior of devices seem different to a different group of devices.

Some of the strange collection of the opinion I heard form different people is:

  • Restart your device after unplugging
  • Remove some apps from device and free at-least 100 MB
  • Try to install your app from the command line, ./adb install ~Application_path
  • Move your application to SD card storage or make it default in SD card in the Android manifest file, android:installLocation="preferExternal"
  • You got a lot of memory acquiring stuff in the Raw folder which installs a copy in phone memory while instating an APK file and the device doesn't have enough memory to load them
  • Root your device and install some good ROM which help to letting the device know about its remaining memory.

I hope one of them is relevant to you! ;)

Rest-assured. Is it possible to extract value from request json?

You can also do like this if you're only interested in extracting the "user_id":

String userId = 
given().
        contentType("application/json").
        body(requestBody).
when().
        post("/admin").
then().
        statusCode(200).
extract().
        path("user_id");

In its simplest form it looks like this:

String userId = get("/person").path("person.userId");

Shell script to send email

mail -s "Your Subject" [email protected] < /file/with/mail/content

(/file/with/mail/content should be a plaintext file, not a file attachment or an image, etc)

String Resource new line /n not possible?

use a blackslash not a forwardslash. \n

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="title">Hello\nWorld!</string>
</resources>

Also, if you plan on using the string as HTML, you can use &lt;br /&gt; for a line break(<br />)

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="title">Hello&lt;br /&gt;World!</string>
</resources>

How can I make the cursor turn to the wait cursor?

Use this with WPF:

Cursor = Cursors.Wait;

// Your Heavy work here

Cursor = Cursors.Arrow;

Is it possible to return empty in react render function?

Some answers are slightly incorrect and point to the wrong part of the docs:

If you want a component to render nothing, just return null, as per doc:

In rare cases you might want a component to hide itself even though it was rendered by another component. To do this return null instead of its render output.

If you try to return undefined for example, you'll get the following error:

Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.

As pointed out by other answers, null, true, false and undefined are valid children which is useful for conditional rendering inside your jsx, but it you want your component to hide / render nothing, just return null.

HTML entity for check mark

HTML and XML entities are just a way of referencing a Unicode code-point in a way that reliably works regardless of the encoding of the actual page, making them useful for using esoteric Unicode characters in a page using 7-bit ASCII or some other encoding scheme, ideally on a one-off basis. They're also used to escape the <, >, " and & characters as these are reserved in SGML.

Anyway, Unicode has a number of tick/check characters, as per Wikipedia ( http://en.wikipedia.org/wiki/Tick_(check_mark) ).

Ideally you should save/store your HTML in a Unicode format like UTF-8 or 16, thus obviating the need to use HTML entities to represent a Unicode character. Nonetheless use: &#x2714; ✔.

&#x2714;

Is using hex notation and is the same as

$#10004;

(as 2714 in base 16 is the same as 10004 in base 10)

Could not find com.google.android.gms:play-services:3.1.59 3.2.25 4.0.30 4.1.32 4.2.40 4.2.42 4.3.23 4.4.52 5.0.77 5.0.89 5.2.08 6.1.11 6.1.71 6.5.87

Check if you also installed the "Google Repository". If not, you also have to install the "Google Repository" in your SDK Manager.

Also be aware that there might be 2 SDK installations - one coming from AndroidStudio and one you might have installed. Better consolidate this to one installation - this is a common pitfall - that you have it installed in one installation but it fails when you build with the other installation.

Example of how to access SDK Manager for Google Repository

How do I deal with installing peer dependencies in Angular CLI?

Peer dependency warnings, more often than not, can be ignored. The only time you will want to take action is if the peer dependency is missing entirely, or if the version of a peer dependency is higher than the version you have installed.

Let's take this warning as an example:

npm WARN @angular/[email protected] requires a peer of @angular/[email protected] but none is installed. You must install peer dependencies yourself.

With Angular, you would like the versions you are using to be consistent across all packages. If there are any incompatible versions, change the versions in your package.json, and run npm install so they are all synced up. I tend to keep my versions for Angular at the latest version, but you will need to make sure your versions are consistent for whatever version of Angular you require (which may not be the most recent).

In a situation like this:

npm WARN [email protected] requires a peer of @angular/core@^2.4.0 || ^4.0.0 but none is installed. You must install peer dependencies yourself.

If you are working with a version of Angular that is higher than 4.0.0, then you will likely have no issues. Nothing to do about this one then. If you are using an Angular version under 2.4.0, then you need to bring your version up. Update the package.json, and run npm install, or run npm install for the specific version you need. Like this:

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

You can leave out the --save if you are running npm 5.0.0 or higher, that version saves the package in the dependencies section of the package.json automatically.

In this situation:

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

You are running Windows, and fsevent requires OSX. This warning can be ignored.

Hope this helps, and have fun learning Angular!

QR Code encoding and decoding using zxing

For what it's worth, my groovy spike seems to work with both UTF-8 and ISO-8859-1 character encodings. Not sure what will happen when a non zxing decoder tries to decode the UTF-8 encoded image though... probably varies depending on the device.

// ------------------------------------------------------------------------------------
// Requires: groovy-1.7.6, jdk1.6.0_03, ./lib with zxing core-1.7.jar, javase-1.7.jar 
// Javadocs: http://zxing.org/w/docs/javadoc/overview-summary.html
// Run with: groovy -cp "./lib/*" zxing.groovy
// ------------------------------------------------------------------------------------

import com.google.zxing.*
import com.google.zxing.common.*
import com.google.zxing.client.j2se.*

import java.awt.image.BufferedImage
import javax.imageio.ImageIO

def class zxing {
    def static main(def args) {
        def filename = "./qrcode.png"
        def data = "This is a test to see if I can encode and decode this data..."
        def charset = "UTF-8" //"ISO-8859-1" 
        def hints = new Hashtable<EncodeHintType, String>([(EncodeHintType.CHARACTER_SET): charset])

        writeQrCode(filename, data, charset, hints, 100, 100)

        assert data == readQrCode(filename, charset, hints)
    }

    def static writeQrCode(def filename, def data, def charset, def hints, def width, def height) {
        BitMatrix matrix = new MultiFormatWriter().encode(new String(data.getBytes(charset), charset), BarcodeFormat.QR_CODE, width, height, hints)
        MatrixToImageWriter.writeToFile(matrix, filename.substring(filename.lastIndexOf('.')+1), new File(filename))
    }

    def static readQrCode(def filename, def charset, def hints) {
        BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(ImageIO.read(new FileInputStream(filename)))))
        Result result = new MultiFormatReader().decode(binaryBitmap, hints)

        result.getText()        
    }

}

How to generate and validate a software license key?

You can use a free third party solution to handle this for you such as Quantum-Key.Net It's free and handles payments via paypal through a web sales page it creates for you, key issuing via email and locks key use to a specific computer to prevent piracy.

Your should also take care to obfuscate/encrypt your code or it can easily be reverse engineered using software such as De4dot and .NetReflector. A good free code obfuscator is ConfuserEx wich is fast and simple to use and more effective than expensive alternatives.

You should run your finished software through De4Dot and .NetReflector to reverse-engineer it and see what a cracker would see if they did the same thing and to make sure you have not left any important code exposed or undisguised.

Your software will still be crackable but for the casual cracker it may well be enough to put them off and these simple steps will also prevent your code being extracted and re-used.

https://quantum-key.net

How to use ConfuserEx?

https://github.com/0xd4d/de4dot

https://www.red-gate.com/dynamic/products/dotnet-development/reflector/download

How to prevent scrollbar from repositioning web page?

Extending off of Rapti's answer, this should work just as well, but it adds more margin to the right side of the body and hides it with negative html margin, instead of adding extra padding that could potentially affect the page's layout. This way, nothing is changed on the actual page (in most cases), and the code is still functional.

html {
    margin-right: calc(100% - 100vw);
}
body {
    margin-right: calc(100vw - 100%);
}

D3 transform scale and translate

Scott Murray wrote a great explanation of this[1]. For instance, for the code snippet:

svg.append("g")
    .attr("class", "axis")
    .attr("transform", "translate(0," + h + ")")
    .call(xAxis);

He explains using the following:

Note that we use attr() to apply transform as an attribute of g. SVG transforms are quite powerful, and can accept several different kinds of transform definitions, including scales and rotations. But we are keeping it simple here with only a translation transform, which simply pushes the whole g group over and down by some amount.

Translation transforms are specified with the easy syntax of translate(x,y), where x and y are, obviously, the number of horizontal and vertical pixels by which to translate the element.

[1]: From Chapter 8, "Cleaning it up" of Interactive Data Visualization for the Web, which used to be freely available and is now behind a paywall.

Clearing state es6 React

Problem

The accepted answer:

const initialState = {
    /* etc */
};

class MyComponent extends Component {
    constructor(props) {
        super(props)
        this.state = initialState;
    }
    reset() {
        this.setState(initialState);
    }
    /* etc */
}

unfortunately is not correct.

initialState is passed as a reference to this.state, so whenever you change state you also change initialState (const doesn't really matter here). The result is that you can never go back to initialState.

Solution

You have to deep copy initialState to state, then it will work. Either write a deep copy function yourself or use some existing module like this.

How to check whether a int is not null or empty?

int variables can't be null

If a null is to be converted to int, then it is the converter which decides whether to set 0, throw exception, or set another value (like Integer.MIN_VALUE). Try to plug your own converter.

What to do with branch after merge

After the merge, it's safe to delete the branch:

git branch -d branch1

Additionally, git will warn you (and refuse to delete the branch) if it thinks you didn't fully merge it yet. If you forcefully delete a branch (with git branch -D) which is not completely merged yet, you have to do some tricks to get the unmerged commits back though (see below).

There are some reasons to keep a branch around though. For example, if it's a feature branch, you may want to be able to do bugfixes on that feature still inside that branch.

If you also want to delete the branch on a remote host, you can do:

git push origin :branch1

This will forcefully delete the branch on the remote (this will not affect already checked-out repositiories though and won't prevent anyone with push access to re-push/create it).


git reflog shows the recently checked out revisions. Any branch you've had checked out in the recent repository history will also show up there. Aside from that, git fsck will be the tool of choice at any case of commit-loss in git.

How to get WooCommerce order details

$order = new WC_Order(get_query_var('order-received'));

How to shutdown a Spring Boot Application in a correct way?

I don't expose any endpoints and start (with nohup in background and without out files created through nohup) and stop with shell script(with KILL PID gracefully and force kill if app is still running after 3 mins). I just create executable jar and use PID file writer to write PID file and store Jar and Pid in folder with same name as of application name and shell scripts also have same name with start and stop in the end. I call these stop script and start script via jenkins pipeline also. No issues so far. Perfectly working for 8 applications(Very generic scripts and easy to apply for any app).

Main Class

@SpringBootApplication
public class MyApplication {

    public static final void main(String[] args) {
        SpringApplicationBuilder app = new SpringApplicationBuilder(MyApplication.class);
        app.build().addListeners(new ApplicationPidFileWriter());
        app.run();
    }
}

YML FILE

spring.pid.fail-on-write-error: true
spring.pid.file: /server-path-with-folder-as-app-name-for-ID/appName/appName.pid

Here is the start script(start-appname.sh):

#Active Profile(YAML)
ACTIVE_PROFILE="preprod"
# JVM Parameters and Spring boot initialization parameters
JVM_PARAM="-Xms512m -Xmx1024m -Dspring.profiles.active=${ACTIVE_PROFILE} -Dcom.webmethods.jms.clientIDSharing=true"
# Base Folder Path like "/folder/packages"
CURRENT_DIR=$(readlink -f "$0")
BASE_PACKAGE="${CURRENT_DIR%/bin/*}"
# Shell Script file name after removing path like "start-yaml-validator.sh"
SHELL_SCRIPT_FILE_NAME=$(basename -- "$0")
# Shell Script file name after removing extension like "start-yaml-validator"
SHELL_SCRIPT_FILE_NAME_WITHOUT_EXT="${SHELL_SCRIPT_FILE_NAME%.sh}"
# App name after removing start/stop strings like "yaml-validator"
APP_NAME=${SHELL_SCRIPT_FILE_NAME_WITHOUT_EXT#start-}

PIDS=`ps aux |grep [j]ava.*-Dspring.profiles.active=$ACTIVE_PROFILE.*$APP_NAME.*jar | awk {'print $2'}`
if [ -z "$PIDS" ]; then
  echo "No instances of $APP_NAME with profile:$ACTIVE_PROFILE is running..." 1>&2
else
  for PROCESS_ID in $PIDS; do
        echo "Please stop the process($PROCESS_ID) using the shell script: stop-$APP_NAME.sh"
  done
  exit 1
fi

# Preparing the java home path for execution
JAVA_EXEC='/usr/bin/java'
# Java Executable - Jar Path Obtained from latest file in directory
JAVA_APP=$(ls -t $BASE_PACKAGE/apps/$APP_NAME/$APP_NAME*.jar | head -n1)
# To execute the application.
FINAL_EXEC="$JAVA_EXEC $JVM_PARAM -jar $JAVA_APP"
# Making executable command using tilde symbol and running completely detached from terminal
`nohup $FINAL_EXEC  </dev/null >/dev/null 2>&1 &`
echo "$APP_NAME start script is  completed."

Here is the stop script(stop-appname.sh):

#Active Profile(YAML)
ACTIVE_PROFILE="preprod"
#Base Folder Path like "/folder/packages"
CURRENT_DIR=$(readlink -f "$0")
BASE_PACKAGE="${CURRENT_DIR%/bin/*}"
# Shell Script file name after removing path like "start-yaml-validator.sh"
SHELL_SCRIPT_FILE_NAME=$(basename -- "$0")
# Shell Script file name after removing extension like "start-yaml-validator"
SHELL_SCRIPT_FILE_NAME_WITHOUT_EXT="${SHELL_SCRIPT_FILE_NAME%.*}"
# App name after removing start/stop strings like "yaml-validator"
APP_NAME=${SHELL_SCRIPT_FILE_NAME_WITHOUT_EXT:5}

# Script to stop the application
PID_PATH="$BASE_PACKAGE/config/$APP_NAME/$APP_NAME.pid"

if [ ! -f "$PID_PATH" ]; then
   echo "Process Id FilePath($PID_PATH) Not found"
else
    PROCESS_ID=`cat $PID_PATH`
    if [ ! -e /proc/$PROCESS_ID -a /proc/$PROCESS_ID/exe ]; then
        echo "$APP_NAME was not running with PROCESS_ID:$PROCESS_ID.";
    else
        kill $PROCESS_ID;
        echo "Gracefully stopping $APP_NAME with PROCESS_ID:$PROCESS_ID..."
        sleep 5s
    fi
fi
PIDS=`/bin/ps aux |/bin/grep [j]ava.*-Dspring.profiles.active=$ACTIVE_PROFILE.*$APP_NAME.*jar | /bin/awk {'print $2'}`
if [ -z "$PIDS" ]; then
  echo "All instances of $APP_NAME with profile:$ACTIVE_PROFILE has has been successfully stopped now..." 1>&2
else
  for PROCESS_ID in $PIDS; do
    counter=1
    until [ $counter -gt 150 ]
        do
            if ps -p $PROCESS_ID > /dev/null; then
                echo "Waiting for the process($PROCESS_ID) to finish on it's own for $(( 300 - $(( $counter*5)) ))seconds..."
                sleep 2s
                ((counter++))
            else
                echo "$APP_NAME with PROCESS_ID:$PROCESS_ID is stopped now.."
                exit 0;
            fi
    done
    echo "Forcefully Killing $APP_NAME with PROCESS_ID:$PROCESS_ID."
    kill -9 $PROCESS_ID
  done
fi

In Android, how do I set margins in dp programmatically?

In Kotlin it will look like this:

val layoutParams = (yourView?.layoutParams as? MarginLayoutParams)
layoutParams?.setMargins(40, 40, 40, 40)
yourView?.layoutParams = layoutParams