Programs & Examples On #Mps

JetBrains MPS is a language workbench to create Domain Specific Languages (DSL).

git clone: Authentication failed for <URL>

Rather than escape my password I left it out and was prompted for it, but only when I included the domain name before my username:

git clone https://some-dom-name\[email protected]/tfs/...

Xcode couldn't find any provisioning profiles matching

I opened XCode -> Preferences -> Accounts and clicked on Download certificate. That fixed my problem

You must add a reference to assembly 'netstandard, Version=2.0.0.0

I am facing Same Problem i do following Setup Now Application Work fine

1-

<compilation debug="true" targetFramework="4.7.1">
      <assemblies>
        <add assembly="netstandard, Version=2.0.0.0, Culture=neutral, 
      PublicKeyToken=cc7b13ffcd2ddd51"/>
      </assemblies>
    </compilation>

2- Add Reference

 **C:\Program Files (x86)\Microsoft Visual
Studio\2017\Professional\Common7\IDE\Extensions\Microsoft\ADL
 Tools\2.4.0000.0\ASALocalRun\netstandard.dll**

3-

Copy Above Path Dll to Application Bin Folder on web server

How do I format {{$timestamp}} as MM/DD/YYYY in Postman?

You could use moment.js with Postman to give you that timestamp format.

You can add this to the pre-request script:

const moment = require('moment');
pm.globals.set("today", moment().format("MM/DD/YYYY"));

Then reference {{today}} where ever you need it.

If you add this to the Collection Level Pre-request Script, it will be run for each request in the Collection. Rather than needing to add it to all the requests individually.

For more information about using moment in Postman, I wrote a short blog post: https://dannydainton.com/2018/05/21/hold-on-wait-a-moment/

Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory

You should make sure your test case function is public rather than private to make it accessible by Test Runner.

@Test
private void testmethod(){}

to

@Test
public void testmethod(){}

TypeError: Object of type 'bytes' is not JSON serializable

I guess the answer you need is referenced here Python sets are not json serializable

Not all datatypes can be json serialized . I guess pickle module will serve your purpose.

How to print a Groovy variable in Jenkins?

The following code worked for me:

echo userInput

NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver

My system version: ubuntu 20.04 LTS.

  • I solved this by generate a new MOK and enroll it into shim.

  • Without disable of Secure Boot, although it also really works for me.

  • Simply execute this command and follow what it suggests:

    sudo update-secureboot-policy --enroll-key
    

According to ubuntu's wiki: How can I do non-automated signing of drivers

python JSON object must be str, bytes or bytearray, not 'dict

json.loads take a string as input and returns a dictionary as output.

json.dumps take a dictionary as input and returns a string as output.


With json.loads({"('Hello',)": 6, "('Hi',)": 5}),

You are calling json.loads with a dictionary as input.

You can fix it as follows (though I'm not quite sure what's the point of that):

d1 = {"('Hello',)": 6, "('Hi',)": 5}
s1 = json.dumps(d1)
d2 = json.loads(s1)

Convert python datetime to timestamp in milliseconds

In Python 3 this can be done in 2 steps:

  1. Convert timestring to datetime object
  2. Multiply the timestamp of the datetime object by 1000 to convert it to milliseconds.

For example like this:

from datetime import datetime

dt_obj = datetime.strptime('20.12.2016 09:38:42,76',
                           '%d.%m.%Y %H:%M:%S,%f')
millisec = dt_obj.timestamp() * 1000

print(millisec)

Output:

1482223122760.0

strptime accepts your timestring and a format string as input. The timestring (first argument) specifies what you actually want to convert to a datetime object. The format string (second argument) specifies the actual format of the string that you have passed.

Here is the explanation of the format specifiers from the official documentation:

  • %d - Day of the month as a zero-padded decimal number.
  • %m - Month as a zero-padded decimal number.
  • %Y - Year with century as a decimal number
  • %H - Hour (24-hour clock) as a zero-padded decimal number.
  • %M - Minute as a zero-padded decimal number.
  • %S - Second as a zero-padded decimal number.
  • %f - Microsecond as a decimal number, zero-padded on the left.

Pandas Split Dataframe into two Dataframes at a specific row

iloc

df1 = datasX.iloc[:, :72]
df2 = datasX.iloc[:, 72:]

(iloc docs)

Deserialize Java 8 LocalDateTime with JacksonMapper

There are two problems with your code:

1. Use of wrong type

LocalDateTime does not support timezone. Given below is an overview of java.time types and you can see that the type which matches with your date-time string, 2016-12-01T23:00:00+00:00 is OffsetDateTime because it has a zone offset of +00:00.

enter image description here

Change your declaration as follows:

private OffsetDateTime startDate;

2. Use of wrong format

There are two problems with the format:

  • You need to use y (year-of-era ) instead of Y (week-based-year). Check this discussion to learn more about it. In fact, I recommend you use u (year) instead of y (year-of-era ). Check this answer for more details on it.
  • You need to use XXX or ZZZZZ for the offset part i.e. your format should be uuuu-MM-dd'T'HH:m:ssXXX.

Check the documentation page of DateTimeFormatter for more details about these symbols/formats.

Demo:

import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        String strDateTime = "2019-10-21T13:00:00+02:00";
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:m:ssXXX");
        OffsetDateTime odt = OffsetDateTime.parse(strDateTime, dtf);
        System.out.println(odt);
    }
}

Output:

2019-10-21T13:00+02:00

Learn more about the modern date-time API from Trail: Date Time.

Python/Json:Expecting property name enclosed in double quotes

x = x.replace("'", '"')
j = json.loads(x)

Although this is the correct solution, but it may lead to quite a headache if there a JSON like this -

{'status': 'success', 'data': {'equity': {'enabled': True, 'net': 66706.14510000008, 'available': {'adhoc_margin': 0, 'cash': 1277252.56, 'opening_balance': 1277252.56, 'live_balance': 66706.14510000008, 'collateral': 249823.93, 'intraday_payin': 15000}, 'utilised': {'debits': 1475370.3449, 'exposure': 607729.3129, 'm2m_realised': 0, 'm2m_unrealised': -9033, 'option_premium': 0, 'payout': 0, 'span': 858608.032, 'holding_sales': 0, 'turnover': 0, 'liquid_collateral': 0, 'stock_collateral': 249823.93}}, 'commodity': {'enabled': True, 'net': 0, 'available': {'adhoc_margin': 0, 'cash': 0, 'opening_balance': 0, 'live_balance': 0, 'collateral': 0, 'intraday_payin': 0}, 'utilised': {'debits': 0, 'exposure': 0, 'm2m_realised': 0, 'm2m_unrealised': 0, 'option_premium': 0, 'payout': 0, 'span': 0, 'holding_sales': 0, 'turnover': 0, 'liquid_collateral': 0, 'stock_collateral': 0}}}}

Noticed that "True" value? Use this to make things are double checked for Booleans. This will cover those cases -

x = x.replace("'", '"').replace("True", '"True"').replace("False", '"False"').replace("null", '"null"')
j = json.loads(x)

Also, make sure you do not make

x = json.loads(x)

It has to be another variable.

Add timestamp column with default NOW() for new rows only

You could add the default rule with the alter table,

ALTER TABLE mytable ADD COLUMN created_at TIMESTAMP DEFAULT NOW()

then immediately set to null all the current existing rows:

UPDATE mytable SET created_at = NULL

Then from this point on the DEFAULT will take effect.

The Response content must be a string or object implementing __toString(), "boolean" given after move to psql

I got this issue when I used an ajax call to retrieve data from the database. When the controller returned the array it converted it to a boolean. The problem was that I had "invalid characters" like ú (u with accent).

How to fix error Base table or view not found: 1146 Table laravel relationship table?

The simplest thing to do is, change the default table name assigned for the model. Simply put following code, protected $table = 'category_posts'; instead of protected $table = 'posts'; then it'll do the trick.

However, if you refer Laravel documentation you'll find the answer. Here what it says,

By convention, the "snake case", plural name of the class(model) will be used as the table name unless another name is explicitly specified

Better to you use artisan command to make model and the migration file at the same time, use the following command,

php artisan make:model Test --migration

This will create a model class and a migration class in your Laravel project. Let's say it created following files,

Test.php

2018_06_22_142912_create_tests_table.php

If you look at the code in those two files you'll see,

2018_06_22_142912_create_tests_table.php files' up function,

 public function up()
 {
      Schema::create('tests', function (Blueprint $table) {
      $table->increments('id');
      $table->timestamps();
      });
 }

Here it automatically generated code with the table name of 'tests' which is the plural name of that class which is in Test.php file.

How to copy folders to docker image from Dockerfile?

Replace the * with a /

So instead of

COPY * <destination>

use

COPY / <destination>

Laravel migration default value

Put the default value in single quote and it will work as intended. An example of migration:

$table->increments('id');
            $table->string('name');
            $table->string('url');
            $table->string('country');
            $table->tinyInteger('status')->default('1');
            $table->timestamps();

EDIT : in your case ->default('100.0');

Adb install failure: INSTALL_CANCELED_BY_USER

I tried all the steps described above but failed.

Like, connect to the internet with Data connection, Turning off the MIUI optimization and reboot, Turning on Install via USB from Security settings etc.

Then I found a solution.

Steps:

  • Install PlexVPN.
  • set China-Shanghai server
  • Try turning on Install via USB from Developer option.

That's all.

How can I conditionally import an ES6 module?

No, you can't!

However, having bumped into that issue should make you rethink on how you organize your code.

Before ES6 modules, we had CommonJS modules which used the require() syntax. These modules were "dynamic", meaning that we could import new modules based on conditions in our code. - source: https://bitsofco.de/what-is-tree-shaking/

I guess one of the reasons they dropped that support on ES6 onward is the fact that compiling it would be very difficult or impossible.

What is the difference between json.dump() and json.dumps() in python?

One notable difference in Python 2 is that if you're using ensure_ascii=False, dump will properly write UTF-8 encoded data into the file (unless you used 8-bit strings with extended characters that are not UTF-8):

dumps on the other hand, with ensure_ascii=False can produce a str or unicode just depending on what types you used for strings:

Serialize obj to a JSON formatted str using this conversion table. If ensure_ascii is False, the result may contain non-ASCII characters and the return value may be a unicode instance.

(emphasis mine). Note that it may still be a str instance as well.

Thus you cannot use its return value to save the structure into file without checking which format was returned and possibly playing with unicode.encode.

This of course is not valid concern in Python 3 any more, since there is no more this 8-bit/Unicode confusion.


As for load vs loads, load considers the whole file to be one JSON document, so you cannot use it to read multiple newline limited JSON documents from a single file.

AWS Lambda import module error in python

There are just so many gotchas when creating deployment packages for AWS Lambda (for Python). I have spent hours and hours on debugging sessions until I found a formula that rarely fails.

I have created a script that automates the entire process and therefore makes it less error prone. I have also wrote tutorial that explains how everything works. You may want to check it out:

Hassle-Free Python Lambda Deployment [Tutorial + Script]

Angular 2 @ViewChild annotation returns undefined

This worked for me.

My component named 'my-component', for example, was displayed using *ngIf="showMe" like so:

<my-component [showMe]="showMe" *ngIf="showMe"></my-component>

So, when the component is initialized the component is not yet displayed until "showMe" is true. Thus, my @ViewChild references were all undefined.

This is where I used @ViewChildren and the QueryList that it returns. See angular article on QueryList and a @ViewChildren usage demo.

You can use the QueryList that @ViewChildren returns and subscribe to any changes to the referenced items using rxjs as seen below. @ViewChild does not have this ability.

import { Component, ViewChildren, ElementRef, OnChanges, QueryList, Input } from '@angular/core';
import 'rxjs/Rx';

@Component({
    selector: 'my-component',
    templateUrl: './my-component.component.html',
    styleUrls: ['./my-component.component.css']
})
export class MyComponent implements OnChanges {

  @ViewChildren('ref') ref: QueryList<any>; // this reference is just pointing to a template reference variable in the component html file (i.e. <div #ref></div> )
  @Input() showMe; // this is passed into my component from the parent as a    

  ngOnChanges () { // ngOnChanges is a component LifeCycle Hook that should run the following code when there is a change to the components view (like when the child elements appear in the DOM for example)
    if(showMe) // this if statement checks to see if the component has appeared becuase ngOnChanges may fire for other reasons
      this.ref.changes.subscribe( // subscribe to any changes to the ref which should change from undefined to an actual value once showMe is switched to true (which triggers *ngIf to show the component)
        (result) => {
          // console.log(result.first['_results'][0].nativeElement);                                         
          console.log(result.first.nativeElement);                                          

          // Do Stuff with referenced element here...   
        } 
      ); // end subscribe
    } // end if
  } // end onChanges 
} // end Class

Hope this helps somebody save some time and frustration.

Can't push image to Amazon ECR - fails with "no basic auth credentials"

For Mac OSX

TL;DR Make sure your "auths" key matches your credential store key exactly

  • Check your docker config:

cat ~/.docker/config.json

Sample Result:

{
    "auths": {
        "https://55511155511.dkr.ecr.us-east-1.amazonaws.com": {}
    },
    "HttpHeaders": {
        "User-Agent": "Docker-Client/19.03.5 (darwin)"
    },
    "credsStore": "osxkeychain"
}

Notice that the "auths" value is an empty object and docker is using a credential store "osxkeychain".

  • Open Mac's "Keychain Access" app and find the name "Docker Credentials"

enter image description here

Notice the Where: field

  • Make sure the auths key in ~/.docker/config.json matches the Where: field in Keychain Access.

If the auths key in ~/.docker/config.json does NOT match they Where: field in the keychain, you may get a Login Succeeded from docker login... but still get ERROR: Service 'web' failed to build: Get https://55511155511.dkr.ecr.us-east-1.amazonaws.com/v2/path/to/image/latest: no basic auth credentials when you try to pull.

In my case, I needed to add https://

Original

    "auths": {
        "55511155511.dkr.ecr.us-east-1.amazonaws.com": {}
    },

Fixed

    "auths": {
        "https://55511155511.dkr.ecr.us-east-1.amazonaws.com": {}
    },

converting json to string in python

json.dumps() is much more than just making a string out of a Python object, it would always produce a valid JSON string (assuming everything inside the object is serializable) following the Type Conversion Table.

For instance, if one of the values is None, the str() would produce an invalid JSON which cannot be loaded:

>>> data = {'jsonKey': None}
>>> str(data)
"{'jsonKey': None}"
>>> json.loads(str(data))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 1 column 2 (char 1)

But the dumps() would convert None into null making a valid JSON string that can be loaded:

>>> import json
>>> data = {'jsonKey': None}
>>> json.dumps(data)
'{"jsonKey": null}'
>>> json.loads(json.dumps(data))
{u'jsonKey': None}

Laravel 5.2 - Use a String as a Custom Primary Key for Eloquent Table becomes 0

On the model set $incrementing to false

public $incrementing = false;

This will stop it from thinking it is an auto increment field.

Laravel Docs - Eloquent - Defining Models

cordova run with ios error .. Error code 65 for command: xcodebuild with args:

How to do what @connor said:

iOS

  • Open platforms/ios on XCode
  • Find & Replace io.ionic.starter in all files for a unique identifier
  • Click the project to open settings
  • Signing > Select a team
  • Go to your device Settings > General > DeviceManagement
    • Trust your account/team
  • ionic cordova run ios --device --livereload

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

json.loads() takes a JSON encoded string, not a filename. You want to use json.load() (no s) instead and pass in an open file object:

with open('/Users/JoshuaHawley/clean1.txt') as jsonfile:
    data = json.load(jsonfile)

The open() command produces a file object that json.load() can then read from, to produce the decoded Python object for you. The with statement ensures that the file is closed again when done.

The alternative is to read the data yourself and then pass it into json.loads().

Failed to authenticate on SMTP server error using gmail

I had the same problem and I've already tried everything and nothing seemed to work until I just changed the 'host' value in config.php to:

 'host' => env('smtp.mailtrap.io'),

When I changed that it worked nicely, somehow it was using the default host " smtp.mailtrap.org" and ignoring the .env variable I was setting.

After making some test I realize that if I placed the env variable in this order it would worked as it shoulded:

MAIL_HOST=smtp.mailtrap.io

?MAIL_DRIVER=smtp

?MAIL_PORT=2525?

MAIL_USERNAME=xxxx

?MAIL_PASSWORD=xxx

?MAIL_ENCRYPTION=null

Convert time.Time to string

You can use the Time.String() method to convert a time.Time to a string. This uses the format string "2006-01-02 15:04:05.999999999 -0700 MST".

If you need other custom format, you can use Time.Format(). For example to get the timestamp in the format of yyyy-MM-dd HH:mm:ss use the format string "2006-01-02 15:04:05".

Example:

t := time.Now()
fmt.Println(t.String())
fmt.Println(t.Format("2006-01-02 15:04:05"))

Output (try it on the Go Playground):

2009-11-10 23:00:00 +0000 UTC
2009-11-10 23:00:00

Note: time on the Go Playground is always set to the value seen above. Run it locally to see current date/time.

Also note that using Time.Format(), as the layout string you always have to pass the same time –called the reference time– formatted in a way you want the result to be formatted. This is documented at Time.Format():

Format returns a textual representation of the time value formatted according to layout, which defines the format by showing how the reference time, defined to be

Mon Jan 2 15:04:05 -0700 MST 2006

would be displayed if it were the value; it serves as an example of the desired output. The same display rules will then be applied to the time value.

Laravel migration table field's type change

First composer requires doctrine/dbal, then:

$table->longText('column_name')->change();

What is the difference between json.dumps and json.load?

json loads -> returns an object from a string representing a json object.

json dumps -> returns a string representing a json object from an object.

load and dump -> read/write from/to file instead of string

Bootstrap : TypeError: $(...).modal is not a function

I had also faced same error when i was trying to call bootstrap modal from jquery. But this happens because we are using bootstrap modal and for this we need to attach one cdn bootstrap.min.js which is

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

Hope this will help as I missed that when i was trying to call bootstrap modal from jQuery using

$('#button').on('click',function(){ $('#myModal').modal(); });

myModal is the id of Bootstrap modal and you have to give a click event to a button when you call click that button a pop up modal will be displayed.

SQLSTATE[HY000] [1045] Access denied for user 'username'@'localhost' using CakePHP

Check Following Things

  • Make Sure You Have MySQL Server Running
  • Check connection with default credentials i.e. username : 'root' & password : '' [Blank Password]
  • Try login phpmyadmin with same credentials
  • Try to put 127.0.0.1 instead localhost or your lan IP would do too.
  • Make sure you are running MySql on 3306 and if you have configured make sure to state it while making a connection

Artisan, creating tables in database

In order to give a value in the table, we need to give a command:

php artisan make:migration create_users_table

and after then this command line

php artisan migrate

......

Laravel where on relationship object

[OOT]

A bit OOT, but this question is the most closest topic with my question.

Here is an example if you want to show Event where ALL participant meet certain requirement. Let's say, event where ALL the participant has fully paid. So, it WILL NOT return events which having one or more participants that haven't fully paid .

Simply use the whereDoesntHave of the others 2 statuses.

Let's say the statuses are haven't paid at all [eq:1], paid some of it [eq:2], and fully paid [eq:3]

Event::whereDoesntHave('participants', function ($query) {
   return $query->whereRaw('payment = 1 or payment = 2');
})->get();

Tested on Laravel 5.8 - 7.x

How to compare two Carbon Timestamps?

First, convert the timestamp using the built-in eloquent functionality, as described in this answer.

Then you can just use Carbon's min() or max() function for comparison. For example:

$dt1 = Carbon::create(2012, 1, 1, 0, 0, 0); $dt2 = Carbon::create(2014, 1, 30, 0, 0, 0); echo $dt1->min($dt2);

This will echo the lesser of the two dates, which in this case is $dt1.

See http://carbon.nesbot.com/docs/

What is the difference between LATERAL and a subquery in PostgreSQL?

One thing no one has pointed out is that you can use LATERAL queries to apply a user-defined function on every selected row.

For instance:

CREATE OR REPLACE FUNCTION delete_company(companyId varchar(255))
RETURNS void AS $$
    BEGIN
        DELETE FROM company_settings WHERE "company_id"=company_id;
        DELETE FROM users WHERE "company_id"=companyId;
        DELETE FROM companies WHERE id=companyId;
    END; 
$$ LANGUAGE plpgsql;

SELECT * FROM (
    SELECT id, name, created_at FROM companies WHERE created_at < '2018-01-01'
) c, LATERAL delete_company(c.id);

That's the only way I know how to do this sort of thing in PostgreSQL.

@Autowired - No qualifying bean of type found for dependency at least 1 bean

You forgot @Service annotation in your service class.

Open web in new tab Selenium + Python

Opening the new empty tab within same window in chrome browser is not possible up to my knowledge but you can open the new tab with web-link.

So far I surfed net and I got good working content on this question. Please try to follow the steps without missing.

import selenium.webdriver as webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome()
driver.get('https://www.google.com?q=python#q=python')
first_link = driver.find_element_by_class_name('l')

# Use: Keys.CONTROL + Keys.SHIFT + Keys.RETURN to open tab on top of the stack 
first_link.send_keys(Keys.CONTROL + Keys.RETURN)

# Switch tab to the new tab, which we will assume is the next one on the right
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)

driver.quit()

I think this is better solution so far.

Credits: https://gist.github.com/lrhache/7686903

Java GC (Allocation Failure)

"Allocation Failure" is a cause of GC cycle to kick in.

"Allocation Failure" means that no more space left in Eden to allocate object. So, it is normal cause of young GC.

Older JVM were not printing GC cause for minor GC cycles.

"Allocation Failure" is almost only possible cause for minor GC. Another reason for minor GC to kick could be CMS remark phase (if +XX:+ScavengeBeforeRemark is enabled).

Laravel Unknown Column 'updated_at'

Nice answer by Alex and Sameer, but maybe just additional info on why is necessary to put

public $timestamps = false;

Timestamps are nicely explained on official Laravel page:

By default, Eloquent expects created_at and updated_at columns to exist on your >tables. If you do not wish to have these columns automatically managed by >Eloquent, set the $timestamps property on your model to false.

Converting dictionary to JSON

json.dumps() returns the JSON string representation of the python dict. See the docs

You can't do r['rating'] because r is a string, not a dict anymore

Perhaps you meant something like

r = {'is_claimed': 'True', 'rating': 3.5}
json = json.dumps(r) # note i gave it a different name
file.write(str(r['rating']))

How can I rename column in laravel using migration?

Renaming Columns (Laravel 5.x)

To rename a column, you may use the renameColumn method on the Schema builder. *Before renaming a column, be sure to add the doctrine/dbal dependency to your composer.json file.*

Or you can simply required the package using composer...

composer require doctrine/dbal

Source: https://laravel.com/docs/5.0/schema#renaming-columns

Note: Use make:migration and not migrate:make for Laravel 5.x

Inserting created_at data with Laravel

In my case, I wanted to unit test that users weren't able to verify their email addresses after 1 hour had passed, so I didn't want to do any of the other answers since they would also persist when not unit testing, so I ended up just manually updating the row after insert:

// Create new user
$user = factory(User::class)->create();

// Add an email verification token to the 
// email_verification_tokens table
$token = $user->generateNewEmailVerificationToken();

// Get the time 61 minutes ago
$created_at = (new Carbon())->subMinutes(61);

// Do the update
\DB::update(
    'UPDATE email_verification_tokens SET created_at = ?',
    [$created_at]
);

Note: For anything other than unit testing, I would look at the other answers here.

How can I create basic timestamps or dates? (Python 3.4)

>>> import time
>>> print(time.strftime('%a %H:%M:%S'))
Mon 06:23:14

Laravel Migration table already exists, but I want to add new not the older

I was also facing the same problem, I followed the same process but my problem was not resolving so I try another thing. I dropped the tables from my database and use a header file

use Illuminate\Support\Facades\Schema;

and increase the default string length in boot method to add this:

Schema::defaultStringLength(191);

then again php artisan migrate. Problem is resolved, all tables are created in the database.

Plotting a fast Fourier transform in Python

The high spike that you have is due to the DC (non-varying, i.e. freq = 0) portion of your signal. It's an issue of scale. If you want to see non-DC frequency content, for visualization, you may need to plot from the offset 1 not from offset 0 of the FFT of the signal.

Modifying the example given above by @PaulH

import numpy as np
import matplotlib.pyplot as plt
import scipy.fftpack

# Number of samplepoints
N = 600
# sample spacing
T = 1.0 / 800.0
x = np.linspace(0.0, N*T, N)
y = 10 + np.sin(50.0 * 2.0*np.pi*x) + 0.5*np.sin(80.0 * 2.0*np.pi*x)
yf = scipy.fftpack.fft(y)
xf = np.linspace(0.0, 1.0/(2.0*T), N/2)

plt.subplot(2, 1, 1)
plt.plot(xf, 2.0/N * np.abs(yf[0:N/2]))
plt.subplot(2, 1, 2)
plt.plot(xf[1:], 2.0/N * np.abs(yf[0:N/2])[1:])

The output plots: Ploting FFT signal with DC and then when removing it (skipping freq = 0)

Another way, is to visualize the data in log scale:

Using:

plt.semilogy(xf, 2.0/N * np.abs(yf[0:N/2]))

Will show: enter image description here

Background image jumps when address bar hides iOS/Android/Mobile Chrome

My answer is for everyone who comes here (like I did) to find an answer for a bug caused by the hiding address bare / browser interface.

The hiding address bar causes the resize-event to trigger. But different than other resize-events, like switching to landscape mode, this doesn't change the width of the window. So my solution is to hook into the resize event and check if the width is the same.

// Keep track of window width
let myWindowWidth = window.innerWidth;

window.addEventListener( 'resize', function(event) {

    // If width is the same, assume hiding address bar
    if( myWindowWidth == window.innerWidth ) {
         return;
    }

    // Update the window width
    myWindowWidth = window.innerWidth;

    // Do your thing
    // ...
});

Laravel $q->where() between dates

You can chain your wheres directly, without function(q). There's also a nice date handling package in laravel, called Carbon. So you could do something like:

$projects = Project::where('recur_at', '>', Carbon::now())
    ->where('recur_at', '<', Carbon::now()->addWeek())
    ->where('status', '<', 5)
    ->where('recur_cancelled', '=', 0)
    ->get();

Just make sure you require Carbon in composer and you're using Carbon namespace (use Carbon\Carbon;) and it should work.

EDIT: As Joel said, you could do:

$projects = Project::whereBetween('recur_at', array(Carbon::now(), Carbon::now()->addWeek()))
    ->where('status', '<', 5)
    ->where('recur_cancelled', '=', 0)
    ->get();

Python and JSON - TypeError list indices must be integers not str

You can simplify your code down to

url = "http://worldcup.kimonolabs.com/api/players?apikey=xxx"
json_obj = urllib2.urlopen(url).read
player_json_list = json.loads(json_obj)
for player in readable_json_list:
    print player['firstName']

You were trying to access a list element using dictionary syntax. the equivalent of

foo = [1, 2, 3, 4]
foo["1"]

It can be confusing when you have lists of dictionaries and keeping the nesting in order.

How do I force a vertical scrollbar to appear?

Give your body tag an overflow: scroll;

body {
    overflow: scroll;
}

or if you only want a vertical scrollbar use overflow-y

body {
    overflow-y: scroll;
}

How to remove an element from an array in Swift

Few Operation relates to Array in Swift

Create Array

var stringArray = ["One", "Two", "Three", "Four"]

Add Object in Array

stringArray = stringArray + ["Five"]

Get Value from Index object

let x = stringArray[1]

Append Object

stringArray.append("At last position")

Insert Object at Index

stringArray.insert("Going", at: 1)

Remove Object

stringArray.remove(at: 3)

Concat Object value

var string = "Concate Two object of Array \(stringArray[1]) + \(stringArray[2])"

Laravel migration: unique key is too long, even if specified

The same error pops up because of the way Laravel unique() function works.

The only thing you need to do is specify a shorter index name eg.

$table->unique(['email', 'users_email_uniq'],'my_custom_uniq');

WampServer: php-win.exe The program can't start because MSVCR110.dll is missing

Windows 10 x64 released August 2015 - same issue arising. MSVCR110.dll is also found in the sysWOW64 folder (which is where I found it, copying to system32 does not help). To resolve:

  1. uninstall the x86 versions of VC 11 vcredist_x64/86.exe for 2012 and 2013
  2. uninstall WAMP Server 2.5
  3. delete (maybe back up first) the WAMP folder
  4. restart windows
  5. reinstall WAMP 2.5

Hopefully like me you have a MySQL database backup handy!

Start redis-server with config file

I think that you should make the reference to your config file

26399:C 16 Jan 08:51:13.413 # Warning: no config file specified, using the default config. In order to specify a config file use ./redis-server /path/to/redis.conf

you can try to start your redis server like

./redis-server /path/to/redis-stable/redis.conf

WAMP Cannot access on local network 403 Forbidden

For Apache 2.4.9

in addition, look at the httpd-vhosts.conf file in C:\wamp\bin\apache\apache2.4.9\conf\extra

<VirtualHost *:80>
ServerName localhost
ServerAlias localhost
DocumentRoot C:/wamp/www
<Directory "C:/wamp/www/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Require local
</Directory>
</VirtualHost>

Change to:

<VirtualHost *:80>
ServerName localhost
ServerAlias localhost
DocumentRoot C:/wamp/www
<Directory "C:/wamp/www/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Require all granted
</Directory>
</VirtualHost>

changing from "Require local" to "Require all granted" solved the error 403 in my local network

How to dynamically build a JSON object with Python?

You can use EasyDict library (doc):

EasyDict allows to access dict values as attributes (works recursively). A Javascript-like properties dot notation for python dicts.

USEAGE

>>> from easydict import EasyDict as edict
>>> d = edict({'foo':3, 'bar':{'x':1, 'y':2}})
>>> d.foo
3
>>> d.bar.x
1

>>> d = edict(foo=3)
>>> d.foo
3

[INSTALLATION]:

  • pip install easydict

Converting between datetime and Pandas Timestamp objects

>>> pd.Timestamp('2014-01-23 00:00:00', tz=None).to_datetime()
datetime.datetime(2014, 1, 23, 0, 0)
>>> pd.Timestamp(datetime.date(2014, 3, 26))
Timestamp('2014-03-26 00:00:00')

mkdir's "-p" option

The man pages is the best source of information you can find... and is at your fingertips: man mkdir yields this about -p switch:

-p, --parents
    no error if existing, make parent directories as needed

Use case example: Assume I want to create directories hello/goodbye but none exist:

$mkdir hello/goodbye
mkdir:cannot create directory 'hello/goodbye': No such file or directory
$mkdir -p hello/goodbye
$

-p created both, hello and goodbye

This means that the command will create all the directories necessaries to fulfill your request, not returning any error in case that directory exists.

About rlidwka, Google has a very good memory for acronyms :). My search returned this for example: http://www.cs.cmu.edu/~help/afs/afs_acls.html

 Directory permissions

l (lookup)
    Allows one to list the contents of a directory. It does not allow the reading of files. 
i (insert)
    Allows one to create new files in a directory or copy new files to a directory. 
d (delete)
    Allows one to remove files and sub-directories from a directory. 
a (administer)
    Allows one to change a directory's ACL. The owner of a directory can always change the ACL of a directory that s/he owns, along with the ACLs of any subdirectories in that directory. 

File permissions

r (read)
    Allows one to read the contents of file in the directory. 
w (write)
    Allows one to modify the contents of files in a directory and use chmod on them. 
k (lock)
    Allows programs to lock files in a directory. 

Hence rlidwka means: All permissions on.

It's worth mentioning, as @KeithThompson pointed out in the comments, that not all Unix systems support ACL. So probably the rlidwka concept doesn't apply here.

Migration: Cannot add foreign key constraint

If none of the solutions above work for newbies check if both IDs have the same type: both are integer or both are bigInteger, ... You can have something like this:

Main Table (users for example)

$table->bigIncrements('id');

Child Table (priorities for example)

$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

This query will failed because users.id is a BIG INTEGER whereas priorities.user_id is an INTEGER.

The right query in this case would be the following:

$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

Add element to a JSON file?

One possible issue I see is you set your JSON unconventionally within an array/list object. I would recommend using JSON in its most accepted form, i.e.:

test_json = { "a": 1, "b": 2}

Once you do this, adding a json element only involves the following line:

test_json["c"] = 3

This will result in:

{'a': 1, 'b': 2, 'c': 3}

Afterwards, you can add that json back into an array or a list of that is desired.

UnicodeDecodeError: 'utf8' codec can't decode byte 0xa5 in position 0: invalid start byte

On read csv, I added an encoding method:

import pandas as pd
dataset = pd.read_csv('sample_data.csv', header= 0,
                        encoding= 'unicode_escape')

What is the difference between Sublime text and Github's Atom

ATTENTION ::

-- because of poorly made caching system, in Atom loss of data occurs often when using big files.

It has been proven numerous times.

Fatal error: Call to undefined function sqlsrv_connect()

If you are using Microsoft Drivers 3.1, 3.0, and 2.0. Please check your PHP version already install with IIS.

Use this script to check the php version:

<?php echo phpinfo(); ?>

OR

If you have installed PHP Manager in IIS using web platform Installer you can check the version from it.

Then:
If you are using new PHP version (5.6) please download Drivers from here

For PHP version Lower than 5.6 - please download Drivers from here

  • PHP Driver version 3.1 requires PHP 5.4.32, or PHP 5.5.16, or later.
  • PHP Driver version 3.0 requires PHP 5.3.0 or later. If possible, use PHP 5.3.6, or later.
  • PHP Driver version 2.0 driver works with PHP 5.2.4 or later, but not with PHP 5.4. If possible, use PHP 5.2.13, or later.

Then use the PHP Manager to add that downloaded drivers into php config file.You can do it as shown below (browse the files and press OK). Then Restart the IIS Server

enter image description here

If this method not work please change the php version and try to run your php script. enter image description here

Tip:Change the php version to lower and try to understand what happened.then you can download relevant drivers.

Sequelize, convert entity to plain object

If I get you right, you want to add the sensors collection to the node. If you have a mapping between both models you can either use the include functionality explained here or the values getter defined on every instance. You can find the docs for that here.

The latter can be used like this:

db.Sensors.findAll({
  where: {
    nodeid: node.nodeid
  }
}).success(function (sensors) {
  var nodedata = node.values;

  nodedata.sensors = sensors.map(function(sensor){ return sensor.values });
  // or
  nodedata.sensors = sensors.map(function(sensor){ return sensor.toJSON() });

  nodesensors.push(nodedata);
  response.json(nodesensors);
});

There is chance that nodedata.sensors = sensors could work as well.

Best approach to real time http streaming to HTML5 video client

I wrote an HTML5 video player around broadway h264 codec (emscripten) that can play live (no delay) h264 video on all browsers (desktop, iOS, ...).

Video stream is sent through websocket to the client, decoded frame per frame and displayed in a canva (using webgl for acceleration)

Check out https://github.com/131/h264-live-player on github.

Laravel Eloquent Sum of relation's column

I tried doing something similar, which took me a lot of time before I could figure out the collect() function. So you can have something this way:

collect($items)->sum('amount');

This will give you the sum total of all the items.

WampServer orange icon

Adding to what @Hitesh-sahu said you need all the VC++ redistribution packages for it to turn green. I referred to this thread from wampserver forum. You can install this little tool (check_vcredist) from the tools section here which will check if all the needed dependencies are installed (see attached image) and it will also provide links to missing ones. If you are using x64 version of Windows like I do and your wampserver does not turn green even after installing all the packages then uninstall and do a fresh installation again. Hope it helps.

enter image description here

How can I create a marquee effect?

The accepted answers animation does not work on Safari, I've updated it using translate instead of padding-left which makes for a smoother, bulletproof animation.

Also, the accepted answers demo fiddle has a lot of unnecessary styles.

So I created a simple version if you just want to cut and paste the useful code and not spend 5 mins clearing through the demo.

http://jsfiddle.net/e8ws12pt/

_x000D_
_x000D_
.marquee {_x000D_
    margin: 0 auto;_x000D_
    white-space: nowrap;_x000D_
    overflow: hidden;_x000D_
    box-sizing: border-box;_x000D_
    padding: 0;_x000D_
    height: 16px;_x000D_
    display: block;_x000D_
}_x000D_
.marquee span {_x000D_
    display: inline-block;_x000D_
    text-indent: 0;_x000D_
    overflow: hidden;_x000D_
    -webkit-transition: 15s;_x000D_
    transition: 15s;_x000D_
    -webkit-animation: marquee 15s linear infinite;_x000D_
    animation: marquee 15s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes marquee {_x000D_
    0% { transform: translate(100%, 0); -webkit-transform: translateX(100%); }_x000D_
    100% { transform: translate(-100%, 0); -webkit-transform: translateX(-100%); }_x000D_
}
_x000D_
<p class="marquee"><span>Simple CSS Marquee - Lorem ipsum dolor amet tattooed squid microdosing taiyaki cardigan polaroid single-origin coffee iPhone. Edison bulb blue bottle neutra shabby chic. Kitsch affogato you probably haven't heard of them, keytar forage plaid occupy pitchfork. Enamel pin crucifix tilde fingerstache, lomo unicorn chartreuse plaid XOXO yr VHS shabby chic meggings pinterest kickstarter.</span></p>
_x000D_
_x000D_
_x000D_

What is a 'NoneType' object?

NoneType is the type for the None object, which is an object that indicates no value. None is the return value of functions that "don't return anything". It is also a common default return value for functions that search for something and may or may not find it; for example, it's returned by re.search when the regex doesn't match, or dict.get when the key has no entry in the dict. You cannot add None to strings or other objects.

One of your variables is None, not a string. Maybe you forgot to return in one of your functions, or maybe the user didn't provide a command-line option and optparse gave you None for that option's value. When you try to add None to a string, you get that exception:

send_command(child, SNMPGROUPCMD + group + V3PRIVCMD)

One of group or SNMPGROUPCMD or V3PRIVCMD has None as its value.

MYSQL query between two timestamps

@Amaynut Thanks

SELECT * 
FROM eventList 
WHERE date BETWEEN UNIX_TIMESTAMP('2017-08-01') AND UNIX_TIMESTAMP('2017/08/01');

above mention, code works and my problem solved.

SQLSTATE[42S22]: Column not found: 1054 Unknown column - Laravel

Try to change where Member class

public function users() {
    return $this->hasOne('User');
} 

return $this->belongsTo('User');

Application.WorksheetFunction.Match method

You are getting this error because the value cannot be found in the range. String or integer doesn't matter. Best thing to do in my experience is to do a check first to see if the value exists.

I used CountIf below, but there is lots of different ways to check existence of a value in a range.

Public Sub test()

Dim rng As Range
Dim aNumber As Long

aNumber = 666

Set rng = Sheet5.Range("B16:B615")

    If Application.WorksheetFunction.CountIf(rng, aNumber) > 0 Then

        rowNum = Application.WorksheetFunction.Match(aNumber, rng, 0)

    Else
        MsgBox aNumber & " does not exist in range " & rng.Address
    End If

End Sub

ALTERNATIVE WAY

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Long

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    If Not IsError(Application.Match(aNumber, rng, 0)) Then
        rowNum = Application.Match(aNumber, rng, 0)
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

OR

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Variant

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    rowNum = Application.Match(aNumber, rng, 0)

    If Not IsError(rowNum) Then
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

Disable Laravel's Eloquent timestamps

just declare the public timestamps variable in your Model to false and everything will work great.

public $timestamps = false;

How to convert CSV file to multiline JSON?

Add the indent parameter to json.dumps

 data = {'this': ['has', 'some', 'things'],
         'in': {'it': 'with', 'some': 'more'}}
 print(json.dumps(data, indent=4))

Also note that, you can simply use json.dump with the open jsonfile:

json.dump(data, jsonfile)

Display exact matches only with grep

You need a more specific expression. Try grep " OK$" or grep "[0-9]* OK". You want to choose a pattern that matches what you want, but won't match what you don't want. That pattern will depend upon what your whole file contents might look like.

You can also do: grep -w "OK" which will only match a whole word "OK", such as "1 OK" but won't match "1OK" or "OKFINE".

$ cat test.txt | grep -w "OK"
1 OK
2 OK
4 OK

java.util.Date format SSSSSS: if not microseconds what are the last 3 digits?

tl;dr

Instant.now()
       .toString() 

2018-02-02T00:28:02.487114Z

Instant.parse(
    "2018-02-02T00:28:02.487114Z"
)

java.time

The accepted Answer by ppeterka is correct. Your abuse of the formatting pattern results in an erroneous display of data, while the internal value is always limited milliseconds.

The troublesome SimpleDateFormat and Date classes you are using are now legacy, supplanted by the java.time classes. The java.time classes handle nanoseconds resolution, much finer than the milliseconds limit of the legacy classes.

The equivalent to java.util.Date is java.time.Instant. You can even convert between them using new methods added to the old classes.

Instant instant = myJavaUtilDate.toInstant() ;

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Capture the current moment in UTC. Java 8 captures the current moment in milliseconds, while a new Clock implementation in Java 9 captures the moment in finer granularity, typically microseconds though it depends on the capabilities of your computer hardware clock & OS & JVM implementation.

Instant instant = Instant.now() ;

Generate a String in standard ISO 8601 format.

String output = instant.toString() ;

2018-02-02T00:28:02.487114Z

To generate strings in other formats, search Stack Overflow for DateTimeFormatter, already covered many times.

To adjust into a time zone other than UTC, use ZonedDateTime.

ZonedDateTime zdt = instant.atZone( ZoneId.of( "Pacific/Auckland" ) ) ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How to align form at the center of the page in html/css

Or you can just use the <center></center> tags.

Why is there an unexplainable gap between these inline-block div elements?

Found a solution not involving Flex, because Flex doesn't work in older Browsers. Example:

.container {
    display:block;
    position:relative;
    height:150px;
    width:1024px;
    margin:0 auto;
    padding:0px;
    border:0px;
    background:#ececec;
    margin-bottom:10px;
    text-align:justify;
    box-sizing:border-box;
    white-space:nowrap;
    font-size:0pt;
    letter-spacing:-1em;
}

.cols {
    display:inline-block;
    position:relative;
    width:32%;
    height:100%;
    margin:0 auto;
    margin-right:2%;
    border:0px;
    background:lightgreen;  
    box-sizing:border-box;
    padding:10px;
    font-size:10pt;
    letter-spacing:normal;
}

.cols:last-child {
    margin-right:0;
}

Saving utf-8 texts with json.dumps as UTF8, not as \u escape sequence

If you are loading JSON string from a file & file contents arabic texts. Then this will work.

Assume File like: arabic.json

{ 
"key1" : "?????????",
"key2" : "????? ??????"
}

Get the arabic contents from the arabic.json file

with open(arabic.json, encoding='utf-8') as f:
   # deserialises it
   json_data = json.load(f)
   f.close()


# json formatted string
json_data2 = json.dumps(json_data, ensure_ascii = False)

To use JSON Data in Django Template follow below steps:

# If have to get the JSON index in Django Template file, then simply decode the encoded string.

json.JSONDecoder().decode(json_data2)

done! Now we can get the results as JSON index with arabic value.

Delete all records in a table of MYSQL in phpMyAdmin

You have 2 options delete and truncate :

  1. delete from mytable

    This will delete all the content of the table, not reseting the autoincremental id, this process is very slow. If you want to delete specific records append a where clause at the end.

  2. truncate myTable

    This will reset the table i.e. all the auto incremental fields will be reset. Its a DDL and its very fast. You cannot delete any specific record through truncate.

How Can I Set the Default Value of a Timestamp Column to the Current Timestamp with Laravel Migrations?

Use Paulo Freitas suggestion instead.


Until Laravel fixes this, you can run a standard database query after the Schema::create have been run.

    Schema::create("users", function($table){
        $table->increments('id');
        $table->string('email', 255);
        $table->string('given_name', 100);
        $table->string('family_name', 100);
        $table->timestamp('joined');
        $table->enum('gender', ['male', 'female', 'unisex'])->default('unisex');
        $table->string('timezone', 30)->default('UTC');
        $table->text('about');
    });
    DB::statement("ALTER TABLE ".DB::getTablePrefix()."users CHANGE joined joined TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL");

It worked wonders for me.

Wampserver icon not going green fully, mysql services not starting up?

I have uninstalled the WampServer completelly, and deleted all files in /wamp folder, except www. This folder is preserved when uninstalling. After that I've installed it again and it works fine.

Important: This is helpful only in case when you already have your database backed up. All data from the database will be wiped out this way.

TypeError: Missing 1 required positional argument: 'self'

Works and is simpler than every other solution I see here :

Pump().getPumps()

This is great if you don't need to reuse a class instance. Tested on Python 3.7.3.

Using PHP to upload file and add the path to MySQL database

mysql_connect("localhost", "root", "") or die(mysql_error()) ;
mysql_select_db("altabotanikk") or die(mysql_error()) ;

These are deprecated use the following..

 // Connects to your Database
            $link = mysqli_connect("localhost", "root", "", "");

and to insert data use the following

 $sql = "INSERT INTO  Table-Name (Column-Name)
VALUES ('$filename')" ;

SQL Server 2008 Row Insert and Update timestamps

try

CREATE TABLE [dbo].[Names]
(
    [Name] [nvarchar](64) NOT NULL,
    [CreateTS] [smalldatetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [smalldatetime] NOT NULL

)

PS I think a smalldatetime is good enough. You may decide differently.

Can you not do this at the "moment of impact" ?

In Sql Server, this is common:

Update dbo.MyTable 
Set 

ColA = @SomeValue , 
UpdateDS = CURRENT_TIMESTAMP
Where...........

Sql Server has a "timestamp" datatype.

But it may not be what you think.

Here is a reference:

http://msdn.microsoft.com/en-us/library/ms182776(v=sql.90).aspx

Here is a little RowVersion (synonym for timestamp) example:

CREATE TABLE [dbo].[Names]
(
    [Name] [nvarchar](64) NOT NULL,
    RowVers rowversion ,
    [CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [datetime] NOT NULL

)


INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Update dbo.Names Set Name = Name

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Maybe a complete working example:

DROP TABLE [dbo].[Names]
GO


CREATE TABLE [dbo].[Names]
(
    [Name] [nvarchar](64) NOT NULL,
    RowVers rowversion ,
    [CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [datetime] NOT NULL

)

GO

CREATE TRIGGER dbo.trgKeepUpdateDateInSync_ByeByeBye ON dbo.Names
AFTER INSERT, UPDATE
AS

BEGIN

Update dbo.Names Set UpdateTS = CURRENT_TIMESTAMP from dbo.Names myAlias , inserted triggerInsertedTable where 
triggerInsertedTable.Name = myAlias.Name

END


GO






INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Update dbo.Names Set Name = Name , UpdateTS = '03/03/2003' /* notice that even though I set it to 2003, the trigger takes over */

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Matching on the "Name" value is probably not wise.

Try this more mainstream example with a SurrogateKey

DROP TABLE [dbo].[Names]
GO


CREATE TABLE [dbo].[Names]
(
    SurrogateKey int not null Primary Key Identity (1001,1),
    [Name] [nvarchar](64) NOT NULL,
    RowVers rowversion ,
    [CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [datetime] NOT NULL

)

GO

CREATE TRIGGER dbo.trgKeepUpdateDateInSync_ByeByeBye ON dbo.Names
AFTER UPDATE
AS

BEGIN

   UPDATE dbo.Names
    SET UpdateTS = CURRENT_TIMESTAMP
    From  dbo.Names myAlias
    WHERE exists ( select null from inserted triggerInsertedTable where myAlias.SurrogateKey = triggerInsertedTable.SurrogateKey)

END


GO






INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Update dbo.Names Set Name = Name , UpdateTS = '03/03/2003' /* notice that even though I set it to 2003, the trigger takes over */

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

<Django object > is not JSON serializable

Another great way of solving it while using a model is by using the values() function.

def returnResponse(date):
    response = ScheduledDate.objects.filter(date__startswith=date).values()
    return Response(response)

Find specific string in a text file with VBS script

I'd recommend using a regular expressions instead of string operations for this:

Set fso = CreateObject("Scripting.FileSystemObject")

filename = "C:\VBS\filediprova.txt"

newtext = vbLf & "<tr><td><a href=""..."">Beginning_of_DD_TC5</a></td></tr>"

Set re = New RegExp
re.Pattern = "(\n.*?Test Case \d)"
re.Global  = False
re.IgnoreCase = True

text = f.OpenTextFile(filename).ReadAll
f.OpenTextFile(filename, 2).Write re.Replace(text, newText & "$1")

The regular expression will match a line feed (\n) followed by a line containing the string Test Case followed by a number (\d), and the replacement will prepend that with the text you want to insert (variable newtext). Setting re.Global = False makes the replacement stop after the first match.

If the line breaks in your text file are encoded as CR-LF (carriage return + line feed) you'll have to change \n into \r\n and vbLf into vbCrLf.

If you have to modify several text files, you could do it in a loop like this:

For Each f In fso.GetFolder("C:\VBS").Files
  If LCase(fso.GetExtensionName(f.Name)) = "txt" Then
    text = f.OpenAsTextStream.ReadAll
    f.OpenAsTextStream(2).Write re.Replace(text, newText & "$1")
  End If
Next

is not JSON serializable

It's worth noting that the QuerySet.values_list() method doesn't actually return a list, but an object of type django.db.models.query.ValuesListQuerySet, in order to maintain Django's goal of lazy evaluation, i.e. the DB query required to generate the 'list' isn't actually performed until the object is evaluated.

Somewhat irritatingly, though, this object has a custom __repr__ method which makes it look like a list when printed out, so it's not always obvious that the object isn't really a list.

The exception in the question is caused by the fact that custom objects cannot be serialized in JSON, so you'll have to convert it to a list first, with...

my_list = list(self.get_queryset().values_list('code', flat=True))

...then you can convert it to JSON with...

json_data = json.dumps(my_list)

You'll also have to place the resulting JSON data in an HttpResponse object, which, apparently, should have a Content-Type of application/json, with...

response = HttpResponse(json_data, content_type='application/json')

...which you can then return from your function.

How to find third or n?? maximum salary from salary table?

SELECT Salary,EmpName
FROM
(
SELECT Salary,EmpName,DENSE_RANK() OVER(ORDER BY Salary DESC) Rno from EMPLOYEE
) tbl
WHERE Rno=3

Django DoesNotExist

This line

 except Vehicle.vehicledevice.device.DoesNotExist

means look for device instance for DoesNotExist exception, but there's none, because it's on class level, you want something like

 except Device.DoesNotExist

Converting time stamps in excel to dates

If your file is really big try to use following formula: =A1 / 86400 + 25569

A1 should be replaced to what your need. Should work faster than =(((COLUMN_ID_HERE/60)/60)/24)+DATE(1970,1,1) cause of less number of calculations needed.

Output Django queryset as JSON

from django.http import JsonResponse

def SomeFunction(): dict1 = {}

   obj = list( Mymodel.objects.values() )

   dict1['data']=obj

return JsonResponse(dict1)

Try this code for Django

Android how to convert int to String?

Use Integer.toString(tmpInt) instead.

Pandas DataFrame concat vs append

Pandas concat vs append vs join vs merge

  • Concat gives the flexibility to join based on the axis( all rows or all columns)

  • Append is the specific case(axis=0, join='outer') of concat

  • Join is based on the indexes (set by set_index) on how variable =['left','right','inner','couter']

  • Merge is based on any particular column each of the two dataframes, this columns are variables on like 'left_on', 'right_on', 'on'

High CPU Utilization in java application - why?

In the thread dump you can find the Line Number as below.

for the main thread which is currently running...

"main" #1 prio=5 os_prio=0 tid=0x0000000002120800 nid=0x13f4 runnable [0x0000000001d9f000]
   java.lang.Thread.State: **RUNNABLE**
    at java.io.FileOutputStream.writeBytes(Native Method)
    at java.io.FileOutputStream.write(FileOutputStream.java:313)
    at com.rana.samples.**HighCPUUtilization.main(HighCPUUtilization.java:17)**

CSS Div Background Image Fixed Height 100% Width

But the thing is that the .chapter class is not dynamic you're declaring a height:1200px

so it's better to use background:cover and set with media queries specific height's for popular resolutions.

Read Content from Files which are inside Zip file

Because of the condition in while, the loop might never break:

while (entry != null) {
  // If entry never becomes null here, loop will never break.
}

Instead of the null check there, you can try this:

ZipEntry entry = null;
while ((entry = zip.getNextEntry()) != null) {
  // Rest of your code
}

How To Run PHP From Windows Command Line in WAMPServer

I remember one time when I stumbled upon this issue a few years ago, it's because windows don't have readline, therefore no interactive shell, to use php interactive mode without readline support, you can do this instead:

C:\>php -a 
Interactive mode enabled 

<?php 
echo "Hello, world!"; 
?> 
^Z 
Hello, world!

After entering interactive mode, type using opening (<?php) and closing (?>) php tag, and end with control Z (^Z) which denotes the end of file.

I also recall that I found the solution from php's site user comment: http://www.php.net/manual/en/features.commandline.interactive.php#105729

Exception in thread "main" java.util.NoSuchElementException

You close the second Scanner which closes the underlying InputStream, therefore the first Scanner can no longer read from the same InputStream and a NoSuchElementException results.

The solution: For console apps, use a single Scanner to read from System.in.

Aside: As stated already, be aware that Scanner#nextInt does not consume newline characters. Ensure that these are consumed before attempting to call nextLine again by using Scanner#newLine().

See: Do not create multiple buffered wrappers on a single InputStream

Convert Python dictionary to JSON array

One possible solution that I use is to use python3. It seems to solve many utf issues.

Sorry for the late answer, but it may help people in the future.

For example,

#!/usr/bin/env python3
import json
# your code follows

How to exclude subdirectories in the destination while using /mir /xd switch in robocopy

The argument order seems to matter... to exclude subdirectories, I used

robocopy \\source\folder C:\destinationfolder /XD * /MIR

...and that works for me (Windows 10 copy from Windows Server 2016)

Delete all objects in a list

To delete all objects in a list, you can directly write list = []

Here is example:

>>> a = [1, 2, 3]
>>> a
[1, 2, 3]
>>> a = []
>>> a
[]

String Array object in Java

I think you are a little messed up with what you doing. Athlete is an object, athlete has a name, i has a city where he lives. Athlete can dive.

public class Athlete {

private String name;
private String city;

public Athlete (String name, String city){
this.name = name;
this.city = city;
}
--create method dive, (i am not sure what exactly i has to do)
public void dive (){} 
}




public class Main{
public static void main (String [] args){

String name = in.next(); //enter name from keyboad
String city = in.next(); //enter city form keybord

--create a new object athlete and pass paramenters name and city into the object
Athlete a = new Athlete (name, city);

}
}

Set Focus on EditText

If you try to call requestFocus() before layout is inflated, it will return false. This code runs after layout get inflated. You don't need 200 ms delay as mentioned above.

editText.post(Runnable {
   if(editText.requestFocus()) {
       val imm = editText.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
       imm?.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0)
   }
})

Composer Warning: openssl extension is missing. How to enable in WAMP

you need to edit the "c:\Program Files\wamp\bin\php\php5.3.13\php.ini" file search for: ;extension=php_openssl.dll

remove the semicolon at the beginning

note: if saving the file doesn't work then you need to edit it as administrator. (on win7) go to start menu, search for notepad, right-click on notepad, click "Run As Administrator"

in the composer installation windows just click back then next (or close it and start again) and it should work

MySQL - Operand should contain 1 column(s)

This error can also occur if you accidentally use commas instead of AND in the ON clause of a JOIN:

JOIN joined_table ON (joined_table.column = table.column, joined_table.column2 = table.column2)
                                                        ^
                                             should be AND, not a comma

Find difference between timestamps in seconds in PostgreSQL

select age(timestamp_A, timestamp_B)

Answering to Igor's comment:

select age('2013-02-28 11:01:28'::timestamp, '2011-12-31 11:00'::timestamp);
              age              
-------------------------------
 1 year 1 mon 28 days 00:01:28

"The semaphore timeout period has expired" error for USB connection

I had a similar problem which I solved by changing the Port Settings in the port driver (located in Ports in device manager) to fit the device I was using.

For me it was that wrong Bits per second value was set.

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

Usually the problem is not closing brackets (}) or missing semicolon (;)

How to update json file with python

def updateJsonFile():
    jsonFile = open("replayScript.json", "r") # Open the JSON file for reading
    data = json.load(jsonFile) # Read the JSON into the buffer
    jsonFile.close() # Close the JSON file

    ## Working with buffered content
    tmp = data["location"] 
    data["location"] = path
    data["mode"] = "replay"

    ## Save our changes to JSON file
    jsonFile = open("replayScript.json", "w+")
    jsonFile.write(json.dumps(data))
    jsonFile.close()

SQL Server - calculate elapsed time between two datetime stamps in HH:MM:SS format

SQL Server doesn't support the SQL standard interval data type. Your best bet is to calculate the difference in seconds, and use a function to format the result. The native function CONVERT() might appear to work fine as long as your interval is less than 24 hours. But CONVERT() isn't a good solution for this.

create table test (
  id integer not null,
  ts datetime not null
  );

insert into test values (1, '2012-01-01 08:00');
insert into test values (1, '2012-01-01 09:00');
insert into test values (1, '2012-01-01 08:30');
insert into test values (2, '2012-01-01 08:30');
insert into test values (2, '2012-01-01 10:30');
insert into test values (2, '2012-01-01 09:00');
insert into test values (3, '2012-01-01 09:00');
insert into test values (3, '2012-01-02 12:00');

Values were chosen in such a way that for

  • id = 1, elapsed time is 1 hour
  • id = 2, elapsed time is 2 hours, and
  • id = 3, elapsed time is 3 hours.

This SELECT statement includes one column that calculates seconds, and one that uses CONVERT() with subtraction.

select t.id,
       min(ts) start_time,
       max(ts) end_time,
       datediff(second, min(ts),max(ts)) elapsed_sec,
       convert(varchar, max(ts) - min(ts), 108) do_not_use
from test t
group by t.id;

ID  START_TIME                 END_TIME                   ELAPSED_SEC  DO_NOT_USE
1   January, 01 2012 08:00:00  January, 01 2012 09:00:00  3600         01:00:00
2   January, 01 2012 08:30:00  January, 01 2012 10:30:00  7200         02:00:00
3   January, 01 2012 09:00:00  January, 02 2012 12:00:00  97200        03:00:00

Note the misleading "03:00:00" for the 27-hour difference on id number 3.

Function to format elapsed time in SQL Server

rsync: difference between --size-only and --ignore-times

On a Scientific Linux 6.7 system, the man page on rsync says:

--ignore-times          don't skip files that match size and time

I have two files with identical contents, but with different creation dates:

[root@windstorm ~]# ls -ls /tmp/master/usercron /tmp/new/usercron
4 -rwxrwx--- 1 root root 1595 Feb 15 03:45 /tmp/master/usercron
4 -rwxrwx--- 1 root root 1595 Feb 16 04:52 /tmp/new/usercron

[root@windstorm ~]# diff /tmp/master/usercron /tmp/new/usercron
[root@windstorm ~]# md5sum /tmp/master/usercron /tmp/new/usercron
368165347b09204ce25e2fa0f61f3bbd  /tmp/master/usercron
368165347b09204ce25e2fa0f61f3bbd  /tmp/new/usercron

With --size-only, the two files are regarded the same:

[root@windstorm ~]# rsync -v --size-only -n  /tmp/new/usercron /tmp/master/usercron

sent 29 bytes  received 12 bytes  82.00 bytes/sec
total size is 1595  speedup is 38.90 (DRY RUN)

With --ignore-times, the two files are regarded different:

[root@windstorm ~]# rsync -v --ignore-times -n  /tmp/new/usercron /tmp/master/usercron
usercron

sent 32 bytes  received 15 bytes  94.00 bytes/sec
total size is 1595  speedup is 33.94 (DRY RUN)

So it does not looks like --ignore-times has any effect at all.

Non-static method requires a target

I face this error on testing WebAPI in Postman tool.

After building the code, If we remove any line (For Example: In my case when I remove one Commented line this error was occur...) in debugging mode then the "Non-static method requires a target" error will occur.

Again, I tried to send the same request. This time code working properly. And I get the response properly in Postman.

I hope it will use to someone...

@POST in RESTful web service

Please find example below, it might help you

package jersey.rest.test;

import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HEAD;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;

@Path("/hello")
public class SimpleService {
    @GET
    @Path("/{param}")
    public Response getMsg(@PathParam("param") String msg) {
        String output = "Get:Jersey say : " + msg;
        return Response.status(200).entity(output).build();
    }

    @POST
    @Path("/{param}")
    public Response postMsg(@PathParam("param") String msg) {
        String output = "POST:Jersey say : " + msg;
        return Response.status(200).entity(output).build();
    }

    @POST
    @Path("/post")
    //@Consumes(MediaType.TEXT_XML)
    public Response postStrMsg( String msg) {
        String output = "POST:Jersey say : " + msg;
        return Response.status(200).entity(output).build();
    }

    @PUT
    @Path("/{param}")
    public Response putMsg(@PathParam("param") String msg) {
        String output = "PUT: Jersey say : " + msg;
        return Response.status(200).entity(output).build();
    }

    @DELETE
    @Path("/{param}")
    public Response deleteMsg(@PathParam("param") String msg) {
        String output = "DELETE:Jersey say : " + msg;
        return Response.status(200).entity(output).build();
    }

    @HEAD
    @Path("/{param}")
    public Response headMsg(@PathParam("param") String msg) {
        String output = "HEAD:Jersey say : " + msg;
        return Response.status(200).entity(output).build();
    }
}

for testing you can use any tool like RestClient (http://code.google.com/p/rest-client/)

How can I find the dimensions of a matrix in Python?

To get just a correct number of dimensions in NumPy:

len(a.shape)

In the first case:

import numpy as np
a = np.array([[[1,2,3],[1,2,3]],[[12,3,4],[2,1,3]]])
print("shape = ",np.shape(a))
print("dimensions = ",len(a.shape))

The output will be:

shape =  (2, 2, 3)
dimensions =  3

Convert UNIX epoch to Date object

Go via POSIXct and you want to set a TZ there -- here you see my (Chicago) default:

R> val <- 1352068320
R> as.POSIXct(val, origin="1970-01-01")
[1] "2012-11-04 22:32:00 CST"
R> as.Date(as.POSIXct(val, origin="1970-01-01"))
[1] "2012-11-05" 
R> 

Edit: A few years later, we can now use the anytime package:

R> library(anytime)
R> anytime(1352068320)
[1] "2012-11-04 16:32:00 CST"
R> anydate(1352068320)
[1] "2012-11-04"
R> 

Note how all this works without any format or origin arguments.

adb command for getting ip address assigned by operator

Try this command, it will help you to get ipaddress

adb shell ifconfig tiwlan0

tiwlan0 is the name of the wi-fi network interface on the device. This is generic command for getting ipaddress,

 adb shell netcfg

It will output like this

usb0     DOWN  0.0.0.0         0.0.0.0         0×00001002
sit0     DOWN  0.0.0.0         0.0.0.0         0×00000080
ip6tnl0  DOWN  0.0.0.0         0.0.0.0         0×00000080
gannet0  DOWN  0.0.0.0         0.0.0.0         0×00001082
rmnet0   UP    112.79.87.220   255.0.0.0       0x000000c1
rmnet1   DOWN  0.0.0.0         0.0.0.0         0×00000080
rmnet2   DOWN  0.0.0.0         0.0.0.0         0×00000080

The point of test %eax %eax

You are right, that test "and"s the two operands. But the result is discarded, the only thing that stays, and thats the important part, are the flags. They are set and thats the reason why the test instruction is used (and exist).

JE jumps not when equal (it has the meaning when the instruction before was a comparison), what it really does, it jumps when the ZF flag is set. And as it is one of the flags that is set by test, this instruction sequence (test x,x; je...) has the meaning that it is jumped when x is 0.

For questions like this (and for more details) I can just recommend a book about x86 instruction, e.g. even when it is really big, the Intel documentation is very good and precise.

Invoke a second script with arguments from a script

I tried the accepted solution of using the Invoke-Expression cmdlet but it didn't work for me because my arguments had spaces on them. I tried to parse the arguments and escape the spaces but I couldn't properly make it work and also it was really a dirty work around in my opinion. So after some experimenting, my take on the problem is this:

function Invoke-Script
{
    param
    (
        [Parameter(Mandatory = $true)]
        [string]
        $Script,

        [Parameter(Mandatory = $false)]
        [object[]]
        $ArgumentList
    )

    $ScriptBlock = [Scriptblock]::Create((Get-Content $Script -Raw))
    Invoke-Command -NoNewScope -ArgumentList $ArgumentList -ScriptBlock $ScriptBlock -Verbose
}

# example usage
Invoke-Script $scriptPath $argumentList

The only drawback of this solution is that you need to make sure that your script doesn't have a "Script" or "ArgumentList" parameter.

Populating a database in a Laravel migration file

I tried this DB insert method, but as it does not use the model, it ignored a sluggable trait I had on the model. So, given the Model for this table exists, as soon as its migrated, I figured the model would be available to use to insert data. And I came up with this:

public function up() {
        Schema::create('parent_categories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('slug');
            $table->timestamps();
        });
        ParentCategory::create(
            [
                'id' => 1,
                'name' => 'Occasions',
            ],
        );
    }

This worked correctly, and also took into account the sluggable trait on my Model to automatically generate a slug for this entry, and uses the timestamps too. NB. Adding the ID was no neccesary, however, I wanted specific IDs for my categories in this example. Tested working on Laravel 5.8

get launchable activity name of package from adb

I didn't find it listed so updating the list.

You need to have the apk installed and running in front on your phone for this solution:

Windows CMD line:

adb shell dumpsys window windows | findstr <any unique string from your pkg Name>

Linux Terminal:

adb shell dumpsys window windows | grep -i <any unique string from your Pkg Name>

OUTPUT for Calculator package would be:

Window #7 Window{39ced4b1 u0 com.android.calculator2/com.android.calculator2.Calculator}:

    mOwnerUid=10036 mShowToOwnerOnly=true package=com.android.calculator2 appop=NONE

    mToken=AppWindowToken{29a4bed4 token=Token{2f850b1a ActivityRecord{eefe5c5 u0 com.android.calculator2/.Calculator t322}}}

    mRootToken=AppWindowToken{29a4bed4 token=Token{2f850b1a ActivityRecord{eefe5c5 u0 com.android.calculator2/.Calculator t322}}}

    mAppToken=AppWindowToken{29a4bed4 token=Token{2f850b1a ActivityRecord{eefe5c5 u0 com.android.calculator2/.Calculator t322}}}

    WindowStateAnimator{3e160d22 com.android.calculator2/com.android.calculator2.Calculator}:

      mSurface=Surface(name=com.android.calculator2/com.android.calculator2.Calculator)

  mCurrentFocus=Window{39ced4b1 u0 com.android.calculator2/com.android.calculator2.Calculator}

  mFocusedApp=AppWindowToken{29a4bed4 token=Token{2f850b1a ActivityRecord{eefe5c5 u0 com.android.calculator2/.Calculator t322}}}

Main part is, First Line:

Window #7 Window{39ced4b1 u0 com.android.calculator2/com.android.calculator2.Calculator}:

First part of the output is package name:

com.android.calculator2

Second Part of output (which is after /) can be two things, in our case its:

com.android.calculator2.Calculator

  1. <PKg name>.<activity name> = <com.android.calculator2>.<Calculator>

    so .Calculator is our activity

  2. If second part is entirely different from Package name and doesn't seem to contain pkg name which was before / in out output, then entire second part can be used as main activity.

Select distinct values from a list using LINQ in C#

You can try with this code

var result =  (from  item in List
              select new 
              {
                 EmpLoc = item.empLoc,
                 EmpPL= item.empPL,
                 EmpShift= item.empShift
              })
              .ToList()
              .Distinct();

Visual Studio debugging/loading very slow

I deleted the "Temporary ASP.NET Files" folder and my localhost page load improved dramatically. Here is the path... %temp%\Temporary ASP.NET Files\

wamp server does not start: Windows 7, 64Bit

You can open the Windows event viewer to try to get more information about the errors : in the "Application" section of the Windows logs, there is a good chance you will find error messages from Apache. (At least I found what was wrong in my case there !)

How to compare binary files to check if they are the same?

You can use MD5 hash function to check if two files are the same, with this you can not see the differences in a low level, but is a quick way to compare two files.

md5 <filename1>
md5 <filename2>

If both MD5 hashes (the command output) are the same, then, the two files are not different.

console.log timestamps in Chrome?

I convert arguments to Array using Array.prototype.slice so that I can concat with another Array of what I want to add, then pass it into console.log.apply(console, /*here*/);

var log = function () {
    return console.log.apply(
        console,
        ['['+new Date().toISOString().slice(11,-5)+']'].concat(
            Array.prototype.slice.call(arguments)
        )
    );
};
log(['foo']); // [18:13:17] ["foo"]

It seems that arguments can be Array.prototype.unshifted too, but I don't know if modifying it like this is a good idea/will have other side effects

var log = function () {
    Array.prototype.unshift.call(
        arguments,
        '['+new Date().toISOString().slice(11,-5)+']'
    );
    return console.log.apply(console, arguments);
};
log(['foo']); // [18:13:39] ["foo"]

Markdown to create pages and table of contents?

MultiMarkdown 4.7 has a {{TOC}} macro that inserts a table of contents.

"TypeError: (Integer) is not JSON serializable" when serializing JSON in Python?

You have Numpy Data Type, Just change to normal int() or float() data type. it will work fine.

align an image and some text on the same line without using div width?

Method1:

Inline elements do not use any width or height you specify. To avoid two div and use like this:

 <div id="container">
<img src="tree.png"  align="left"/>
<h1> A very long text(about 300 words) </h1>
</div>
    <style>
            img {
                display: inline;
                width: 100px;
                height: 100px;
            }
            h1 {
                display: inline;
            }
        </style>

Method2:

Change your CSS as follows

.container div {
    display: inline-block;
    }

Method3:

It is the simple method set width Try the following css:

.container div {
overflow:hidden;
position:relative;
width:90%;
margin-bottom:20px;
margin-top:20px;
margin-left:auto;
margin-right:auto;
}
.image {
width:70%;
display: inline-block;
float: left;
}
.texts { 
height: auto;
width: 30%;
display: inline;
}

My httpd.conf is empty

It seems to me, that it is by design that this file is empty.

A similar question has been asked here: https://stackoverflow.com/questions/2567432/ubuntu-apache-httpd-conf-or-apache2-conf

So, you should have a look for /etc/apache2/apache2.conf

Calculating difference between two timestamps in Oracle in milliseconds

I've posted here some methods to convert interval to nanoseconds and nanoseconds to interval. These methods have a nanosecond precision.

You just need to adjust it to get milliseconds instead of nanoseconds.

A shorter method to convert interval to nanoseconds.

SELECT (EXTRACT(DAY FROM (
    INTERVAL '+18500 09:33:47.263027' DAY(5) TO SECOND --Replace line with desired interval --Maximum value: INTERVAL '+694444 10:39:59.999999999' DAY(6) TO SECOND(9) or up to 3871 year
) * 24 * 60) * 60 + EXTRACT(SECOND FROM (
    INTERVAL '+18500 09:33:47.263027' DAY(5) TO SECOND --Replace line with desired interval
))) * 100 AS MILLIS FROM DUAL;

MILLIS
1598434427263.027

Post values from a multiple select

You need to add a name attribute.

Since this is a multiple select, at the HTTP level, the client just sends multiple name/value pairs with the same name, you can observe this yourself if you use a form with method="GET": someurl?something=1&something=2&something=3.

In the case of PHP, Ruby, and some other library/frameworks out there, you would need to add square braces ([]) at the end of the name. The frameworks will parse that string and wil present it in some easy to use format, like an array.

Apart from manually parsing the request there's no language/framework/library-agnostic way of accessing multiple values, because they all have different APIs

For PHP you can use:

<select name="something[]" id="inscompSelected" multiple="multiple" class="lstSelected">

Calculate a MD5 hash from a string

I'd like to offer an alternative that appears to perform at least 10% faster than craigdfrench's answer in my tests (.NET 4.7.2):

public static string GetMD5Hash(string text)
{
    using ( var md5 = MD5.Create() )
    {
        byte[] computedHash = md5.ComputeHash( Encoding.UTF8.GetBytes(text) );
        return new System.Runtime.Remoting.Metadata.W3cXsd2001.SoapHexBinary(computedHash).ToString();
    }
}

If you prefer to have using System.Runtime.Remoting.Metadata.W3cXsd2001; at the top, the method body can be made an easier to read one-liner:

using ( var md5 = MD5.Create() )
{
    return new SoapHexBinary( md5.ComputeHash( Encoding.UTF8.GetBytes(text) ) ).ToString();
}

Obvious enough, but for completeness, in OP's context it would be used as:

sSourceData = "MySourceData";
tmpHash = GetMD5Hash(sSourceData);

What's the Android ADB shell "dumpsys" tool and what are its benefits?

According to official Android information about dumpsys:

The dumpsys tool runs on the device and provides information about the status of system services.

To get a list of available services use

adb shell dumpsys -l

json.dump throwing "TypeError: {...} is not JSON serializable" on seemingly valid object?

I wrote a class to normalize the data in my dictionary. The 'element' in the NormalizeData class below, needs to be of dict type. And you need to replace in the __iterate() with either your custom class object or any other object type that you would like to normalize.

class NormalizeData:

    def __init__(self, element):
        self.element = element

    def execute(self):
        if isinstance(self.element, dict):
            self.__iterate()
        else:
            return

    def __iterate(self):
        for key in self.element:
            if isinstance(self.element[key], <ClassName>):
                self.element[key] = str(self.element[key])

            node = NormalizeData(self.element[key])
            node.execute()

Items in JSON object are out of order using "json.dumps"?

The order of a dictionary doesn't have any relationship to the order it was defined in. This is true of all dictionaries, not just those turned into JSON.

>>> {"b": 1, "a": 2}
{'a': 2, 'b': 1}

Indeed, the dictionary was turned "upside down" before it even reached json.dumps:

>>> {"id":1,"name":"David","timezone":3}
{'timezone': 3, 'id': 1, 'name': 'David'}

offsetting an html anchor to adjust for fixed header

I'm facing this problem in a TYPO3 website, where all "Content Elements" are wrapped with something like:

<div id="c1234" class="contentElement">...</div>

and i changed the rendering so it renders like this:

<div id="c1234" class="anchor"></div>
<div class="contentElement">...</div>

And this CSS:

.anchor{
    position: relative;
    top: -50px;
}

The fixed topbar being 40px high, now the anchors work again and start 10px under the topbar.

Only drawback of this technique is you can no longer use :target.

Serializing class instance to JSON

JSON is not really meant for serializing arbitrary Python objects. It's great for serializing dict objects, but the pickle module is really what you should be using in general. Output from pickle is not really human-readable, but it should unpickle just fine. If you insist on using JSON, you could check out the jsonpickle module, which is an interesting hybrid approach.

https://github.com/jsonpickle/jsonpickle

Set SSH connection timeout

The ConnectTimeout option allows you to tell your ssh client how long you're willing to wait for a connection before returning an error. By setting ConnectTimeout to 1, you're effectively saying "try for at most 1 second and then fail if you haven't connected yet".

The problem is that when you connect by name, the DNS lookup can take several seconds. Connecting by IP address is much faster, and may actually work in one second or less. What sinelaw is experiencing is that every attempt to connect by DNS name is failing to occur within one second. The default setting of ConnectTimeout defers to the linux kernel connect timeout, which is usually pretty long.

Converting a UNIX Timestamp to Formatted Date String

$unixtime_to_date = date('jS F Y h:i:s A (T)', $unixtime);

This should work to.

wampserver doesn't go green - stays orange

WAMP Server may turn orange for various reason as it is not working. This is also a another type of issue. that can be due to webservices is running in services.msc This is explained in the below blog. Please try it. How to resolve HTTP Error 404 and launch localhost with WAMP Server for PHP & MySql?

How to get xdebug var_dump to show full object/array

Checkout Xdebbug's var_dump settings, particularly the values of these settings:

xdebug.var_display_max_children
xdebug.var_display_max_data
xdebug.var_display_max_depth

Append to the end of a Char array in C++

If you are not allowed to use C++'s string class (which is terrible teaching C++ imho), a raw, safe array version would look something like this.

#include <cstring>
#include <iostream>

int main()
{
    char array1[] ="The dog jumps ";
    char array2[] = "over the log";
    char * newArray = new char[std::strlen(array1)+std::strlen(array2)+1];
    std::strcpy(newArray,array1);
    std::strcat(newArray,array2);
    std::cout << newArray << std::endl;
    delete [] newArray;
    return 0;
}

This assures you have enough space in the array you're doing the concatenation to, without assuming some predefined MAX_SIZE. The only requirement is that your strings are null-terminated, which is usually the case unless you're doing some weird fixed-size string hacking.

Edit, a safe version with the "enough buffer space" assumption:

#include <cstring>
#include <iostream>

int main()
{
    const unsigned BUFFER_SIZE = 50;
    char array1[BUFFER_SIZE];
    std::strncpy(array1, "The dog jumps ", BUFFER_SIZE-1); //-1 for null-termination
    char array2[] = "over the log";
    std::strncat(array1,array2,BUFFER_SIZE-strlen(array1)-1); //-1 for null-termination
    std::cout << array1 << std::endl;
    return 0;
}

Find JavaScript function definition in Chrome

Another way to navigate to the location of a function definition would be to break in debugger somewhere you can access the function and enter the functions fully qualified name in the console. This will print the function definition in the console and give a link which on click opens the script location where the function is defined.

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

Just refrain from catching the exception and the traceback that Python prints will tell you what exception occurred.

Removing u in list

For python datasets you can use an index.

tmpColumnsSQL = ("show columns in dim.date_dim")
hiveCursor.execute(tmpColumnsSQL)
columnlist = hiveCursor.fetchall()

for columns in jayscolumnlist:
    print columns[0]

for i in range(len(jayscolumnlist)):    
    print columns[i][0])

How do I get a UTC Timestamp in JavaScript?

The easiest way of getting UTC time in a conventional format is as follows:

new Date().toISOString()
"2016-06-03T23:15:33.008Z"

How to convert integer timestamp to Python datetime

datetime.datetime.fromtimestamp() is correct, except you are probably having timestamp in miliseconds (like in JavaScript), but fromtimestamp() expects Unix timestamp, in seconds.

Do it like that:

>>> import datetime
>>> your_timestamp = 1331856000000
>>> date = datetime.datetime.fromtimestamp(your_timestamp / 1e3)

and the result is:

>>> date
datetime.datetime(2012, 3, 16, 1, 0)

Does it answer your question?

EDIT: J.F. Sebastian correctly suggested to use true division by 1e3 (float 1000). The difference is significant, if you would like to get precise results, thus I changed my answer. The difference results from the default behaviour of Python 2.x, which always returns int when dividing (using / operator) int by int (this is called floor division). By replacing the divisor 1000 (being an int) with the 1e3 divisor (being representation of 1000 as float) or with float(1000) (or 1000. etc.), the division becomes true division. Python 2.x returns float when dividing int by float, float by int, float by float etc. And when there is some fractional part in the timestamp passed to fromtimestamp() method, this method's result also contains information about that fractional part (as the number of microseconds).

How to POST JSON data with Python Requests?

The better way is:

url = "http://xxx.xxxx.xx"
data = {
    "cardno": "6248889874650987",
    "systemIdentify": "s08",
    "sourceChannel": 12
}
resp = requests.post(url, json=data)

What does the 'Z' mean in Unix timestamp '120314170138Z'?

The Z stands for 'Zulu' - your times are in UTC. From Wikipedia:

The UTC time zone is sometimes denoted by the letter Z—a reference to the equivalent nautical time zone (GMT), which has been denoted by a Z since about 1950. The letter also refers to the "zone description" of zero hours, which has been used since 1920 (see time zone history). Since the NATO phonetic alphabet and amateur radio word for Z is "Zulu", UTC is sometimes known as Zulu time. This is especially true in aviation, where Zulu is the universal standard.

Remove DEFINER clause from MySQL Dumps

I don't think there is a way to ignore adding DEFINERs to the dump. But there are ways to remove them after the dump file is created.

  1. Open the dump file in a text editor and replace all occurrences of DEFINER=root@localhost with an empty string ""

  2. Edit the dump (or pipe the output) using perl:

    perl -p -i.bak -e "s/DEFINER=\`\w.*\`@\`\d[0-3].*[0-3]\`//g" mydatabase.sql
    
  3. Pipe the output through sed:

    mysqldump ... | sed -e 's/DEFINER[ ]*=[ ]*[^*]*\*/\*/' > triggers_backup.sql
    

How to beautify JSON in Python?

Your data is poorly formed. The value fields in particular have numerous spaces and new lines. Automated formatters won't work on this, as they will not modify the actual data. As you generate the data for output, filter it as needed to avoid the spaces.

How to determine whether code is running in DEBUG / RELEASE build?

Apple already includes a DEBUG flag in debug builds, so you don't need to define your own.

You might also want to consider just redefining NSLog to a null operation when not in DEBUG mode, that way your code will be more portable and you can just use regular NSLog statements:

//put this in prefix.pch

#ifndef DEBUG
#undef NSLog
#define NSLog(args, ...)
#endif

Oracle SQL : timestamps in where clause

to_timestamp()

You need to use to_timestamp() to convert your string to a proper timestamp value:

to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')

to_date()

If your column is of type DATE (which also supports seconds), you need to use to_date()

to_date('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')

Example

To get this into a where condition use the following:

select * 
from TableA 
where startdate >= to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
  and startdate <= to_timestamp('12-01-2012 21:25:33', 'dd-mm-yyyy hh24:mi:ss')

Note

You never need to use to_timestamp() on a column that is of type timestamp.

How to search a string in a single column (A) in excel using VBA

Below are two methods that are superior to looping. Both handle a "no-find" case.

  1. The VBA equivalent of a normal function VLOOKUP with error-handling if the variable doesn't exist (INDEX/MATCH may be a better route than VLOOKUP, ie if your two columns A and B were in reverse order, or were far apart)
  2. VBAs FIND method (matching a whole string in column A given I use the xlWhole argument)

    Sub Method1()
    Dim strSearch As String
    Dim strOut As String
    Dim bFailed As Boolean
    
    strSearch = "trees"
    
    On Error Resume Next
    strOut = Application.WorksheetFunction.VLookup(strSearch, Range("A:B"), 2, False)
    If Err.Number <> 0 Then bFailed = True
    On Error GoTo 0
    
    If Not bFailed Then
    MsgBox "corresponding value is " & vbNewLine & strOut
    Else
    MsgBox strSearch & " not found"
    End If
    End Sub
    
    Sub Method2()
        Dim rng1 As Range
        Dim strSearch As String
        strSearch = "trees"
        Set rng1 = Range("A:A").Find(strSearch, , xlValues, xlWhole)
        If Not rng1 Is Nothing Then
            MsgBox "Find has matched " & strSearch & vbNewLine & "corresponding cell is " & rng1.Offset(0, 1)
        Else
            MsgBox strSearch & " not found"
        End If
    End Sub
    

Converting datetime.date to UTC timestamp in Python

the question is a little confused. timestamps are not UTC - they're a Unix thing. the date might be UTC? assuming it is, and if you're using Python 3.2+, simple-date makes this trivial:

>>> SimpleDate(date(2011,1,1), tz='utc').timestamp
1293840000.0

if you actually have the year, month and day you don't need to create the date:

>>> SimpleDate(2011,1,1, tz='utc').timestamp
1293840000.0

and if the date is in some other timezone (this matters because we're assuming midnight without an associated time):

>>> SimpleDate(date(2011,1,1), tz='America/New_York').timestamp
1293858000.0

[the idea behind simple-date is to collect all python's date and time stuff in one consistent class, so you can do any conversion. so, for example, it will also go the other way:

>>> SimpleDate(1293858000, tz='utc').date
datetime.date(2011, 1, 1)

]

Updating a JSON object using Javascript

I took Michael Berkowski's answer a step (or two) farther and created a more flexible function allowing any lookup field and any target field. For fun I threw splat (*) capability in there incase someone might want to do a replace all. jQuery is NOT needed. checkAllRows allows the option to break from the search on found for performance or the previously mentioned replace all.

function setVal(update) {
    /* Included to show an option if you care to use jQuery  
    var defaults = { jsonRS: null, lookupField: null, lookupKey: null,
        targetField: null, targetData: null, checkAllRows: false }; 
    //update = $.extend({}, defaults, update); */

    for (var i = 0; i < update.jsonRS.length; i++) {
        if (update.jsonRS[i][update.lookupField] === update.lookupKey || update.lookupKey === '*') {
            update.jsonRS[i][update.targetField] = update.targetData;
            if (!update.checkAllRows) { return; }
        }
    }
}


var jsonObj = [{'Id':'1','Username':'Ray','FatherName':'Thompson'},  
           {'Id':'2','Username':'Steve','FatherName':'Johnson'},
           {'Id':'3','Username':'Albert','FatherName':'Einstein'}]

With your data you would use like:

var update = {
    jsonRS: jsonObj,
    lookupField: "Id",
    lookupKey: 2, 
    targetField: "Username",
    targetData: "Thomas", 
    checkAllRows: false
    };

setVal(update);

And Bob's your Uncle. :) [Works great]

Using port number in Windows host file

You need NGNIX or Apache HTTP server as a proxy server for forwarding http requests to appropriate application -> which listens particular port (or do it with CNAME which provides Hosting company). It is most powerful solution and this is just a really easy way to keep adding new subdomains, or to add new domains automatically when DNS records are pointed at the server.

Replace non ASCII character from string

CharMatcher.retainFrom can be used, if you're using the Google Guava library:

String s = "A função";
String stripped = CharMatcher.ascii().retainFrom(s);
System.out.println(stripped); // Prints "A funo"

How to JSON serialize sets?

If you need just quick dump and don't want to implement custom encoder. You can use the following:

json_string = json.dumps(data, iterable_as_array=True)

This will convert all sets (and other iterables) into arrays. Just beware that those fields will stay arrays when you parse the json back. If you want to preserve the types, you need to write custom encoder.

TypeError: 'float' object not iterable

for i in count: means for i in 7:, which won't work. The bit after the in should be of an iterable type, not a number. Try this:

for i in range(count):

Get a UTC timestamp

new Date().getTime();

For more information, see @James McMahon's answer.

json.dumps vs flask.jsonify

This is flask.jsonify()

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

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

Animate an element's width from 0 to 100%, with it and it's wrapper being only as wide as they need to be, without a pre-set width, in CSS3 or jQuery

I haven't been able to get it to work without specifying a width but the following css worked

.wrapper {
    background: #DDD;
    padding: 10px;
    display: inline-block;
    height: 20px;
    width: auto;
}

.contents {
    background: #c3c;
    overflow: hidden;
    white-space: nowrap;
    display: inline-block;
    visibility: hidden;
    width: 1px;
    -webkit-transition: width 1s ease-in-out, visibility 1s linear;
    -moz-transition: width 1s ease-in-out, visibility 1s linear;
    -o-transition: width 1s ease-in-out, visibility 1s linear;
    transition: width 1s ease-in-out, visibility 1s linear;
}

.wrapper:hover .contents {
    width: 200px;
    visibility: visible;
}

I'm not sure you will be able to get it working without setting a width on it.

How to parse data in JSON format?

For URL or file, use json.load(). For string with .json content, use json.loads().

#! /usr/bin/python

import json
# from pprint import pprint

json_file = 'my_cube.json'
cube = '1'

with open(json_file) as json_data:
    data = json.load(json_data)

# pprint(data)

print "Dimension: ", data['cubes'][cube]['dim']
print "Measures:  ", data['cubes'][cube]['meas']

Why do we always prefer using parameters in SQL statements?

Other answers cover why parameters are important, but there is a downside! In .net, there are several methods for creating parameters (Add, AddWithValue), but they all require you to worry, needlessly, about the parameter name, and they all reduce the readability of the SQL in the code. Right when you're trying to meditate on the SQL, you need to hunt around above or below to see what value has been used in the parameter.

I humbly claim my little SqlBuilder class is the most elegant way to write parameterized queries. Your code will look like this...

C#

var bldr = new SqlBuilder( myCommand );
bldr.Append("SELECT * FROM CUSTOMERS WHERE ID = ").Value(myId);
//or
bldr.Append("SELECT * FROM CUSTOMERS WHERE NAME LIKE ").FuzzyValue(myName);
myCommand.CommandText = bldr.ToString();

Your code will be shorter and much more readable. You don't even need extra lines, and, when you're reading back, you don't need to hunt around for the value of parameters. The class you need is here...

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;

public class SqlBuilder
{
private StringBuilder _rq;
private SqlCommand _cmd;
private int _seq;
public SqlBuilder(SqlCommand cmd)
{
    _rq = new StringBuilder();
    _cmd = cmd;
    _seq = 0;
}
public SqlBuilder Append(String str)
{
    _rq.Append(str);
    return this;
}
public SqlBuilder Value(Object value)
{
    string paramName = "@SqlBuilderParam" + _seq++;
    _rq.Append(paramName);
    _cmd.Parameters.AddWithValue(paramName, value);
    return this;
}
public SqlBuilder FuzzyValue(Object value)
{
    string paramName = "@SqlBuilderParam" + _seq++;
    _rq.Append("'%' + " + paramName + " + '%'");
    _cmd.Parameters.AddWithValue(paramName, value);
    return this;
}
public override string ToString()
{
    return _rq.ToString();
}
}

Check if a string is a date value

This is how I end up doing it. This will not cover all formats. You have to adjust accordingly. I have control on the format, so it works for me

function isValidDate(s) {
            var dt = "";
            var bits = [];
            if (s && s.length >= 6) {
                if (s.indexOf("/") > -1) {
                    bits = s.split("/");
                }
                else if (s.indexOf("-") > -1) {
                    bits = s.split("-");
                }
                else if (s.indexOf(".") > -1) {
                    bits = s.split(".");
                }
                try {
                    dt = new Date(bits[2], bits[0] - 1, bits[1]);
                } catch (e) {
                    return false;
                }
                return (dt.getMonth() + 1) === parseInt(bits[0]);
            } else {
                return false;
            }
        }

How to concatenate two MP4 files using FFmpeg?

From the documentation here: https://trac.ffmpeg.org/wiki/Concatenate

If you have MP4 files, these could be losslessly concatenated by first transcoding them to MPEG-2 transport streams. With H.264 video and AAC audio, the following can be used:

ffmpeg -i input1.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts intermediate1.ts
ffmpeg -i input2.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts intermediate2.ts
ffmpeg -i "concat:intermediate1.ts|intermediate2.ts" -c copy -bsf:a aac_adtstoasc output.mp4

This approach works on all platforms.

I needed the ability to encapsulate this in a cross platform script, so I used fluent-ffmpeg and came up with the following solution:

const unlink = path =>
  new Promise((resolve, reject) =>
    fs.unlink(path, err => (err ? reject(err) : resolve()))
  )

const createIntermediate = file =>
  new Promise((resolve, reject) => {
    const out = `${Math.random()
      .toString(13)
      .slice(2)}.ts`

    ffmpeg(file)
      .outputOptions('-c', 'copy', '-bsf:v', 'h264_mp4toannexb', '-f', 'mpegts')
      .output(out)
      .on('end', () => resolve(out))
      .on('error', reject)
      .run()
  })

const concat = async (files, output) => {
  const names = await Promise.all(files.map(createIntermediate))
  const namesString = names.join('|')

  await new Promise((resolve, reject) =>
    ffmpeg(`concat:${namesString}`)
      .outputOptions('-c', 'copy', '-bsf:a', 'aac_adtstoasc')
      .output(output)
      .on('end', resolve)
      .on('error', reject)
      .run()
  )

  names.map(unlink)
}

concat(['file1.mp4', 'file2.mp4', 'file3.mp4'], 'output.mp4').then(() =>
  console.log('done!')
)

animating addClass/removeClass with jQuery

I was looking into this but wanted to have a different transition rate for in and out.

This is what I ended up doing:

//css
.addedClass {
    background: #5eb4fc;
}

// js
function setParentTransition(id, prop, delay, style, callback) {
    $(id).css({'-webkit-transition' : prop + ' ' + delay + ' ' + style});
    $(id).css({'-moz-transition' : prop + ' ' + delay + ' ' + style});
    $(id).css({'-o-transition' : prop + ' ' + delay + ' ' + style});
    $(id).css({'transition' : prop + ' ' + delay + ' ' + style});
    callback();
}
setParentTransition(id, 'background', '0s', 'ease', function() {
    $('#elementID').addClass('addedClass');
});

setTimeout(function() {
    setParentTransition(id, 'background', '2s', 'ease', function() {
        $('#elementID').removeClass('addedClass');
    });
});

This instantly turns the background color to #5eb4fc and then slowly fades back to normal over 2 seconds.

Here's a fiddle

How do I update/upsert a document in Mongoose?

I just came back to this issue after a while, and decided to publish a plugin based on the answer by Aaron Mast.

https://www.npmjs.com/package/mongoose-recursive-upsert

Use it as a mongoose plugin. It sets up a static method which will recursively merge the object passed in.

Model.upsert({unique: 'value'}, updateObject});

Get the Year/Month/Day from a datetime in php?

Check out the manual: http://www.php.net/manual/en/datetime.format.php

<?php
$date = new DateTime('2000-01-01');
echo $date->format('Y-m-d H:i:s');
?>

Will output: 2000-01-01 00:00:00

Code for download video from Youtube on Java, Android

3 steps:

  1. Check the sorce code (HTML) of YouTube, you'll get the link like this (http%253A%252F%252Fo-o.preferred.telemar-cnf1.v18.lscache6.c.youtube.com%252Fvideoplayback ...);

  2. Decode the url (remove the codes %2B,%25 etc), create a decoder with the codes: http://www.w3schools.com/tags/ref_urlencode.asp and use the function Uri.decode(url) to replace invalid escaped octets;

  3. Use the code to download stream:

    URL u = null;
    InputStream is = null;  
    
    try {
        u = new URL(url);
        is = u.openStream(); 
        HttpURLConnection huc = (HttpURLConnection)u.openConnection(); //to know the size of video
        int size = huc.getContentLength();                 
    
        if(huc != null) {
            String fileName = "FILE.mp4";
            String storagePath = Environment.getExternalStorageDirectory().toString();
            File f = new File(storagePath,fileName);
    
            FileOutputStream fos = new FileOutputStream(f);
            byte[] buffer = new byte[1024];
            int len1 = 0;
            if(is != null) {
                while ((len1 = is.read(buffer)) > 0) {
                    fos.write(buffer,0, len1);  
                }
            }
            if(fos != null) {
                fos.close();
            }
        }                       
    } catch (MalformedURLException mue) {
        mue.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } finally {
        try {               
            if(is != null) {
                is.close();
            }
        } catch (IOException ioe) {
            // just going to ignore this one
        }
    }
    

That's all, most of stuff you'll find on the web!!!

HMAC-SHA256 Algorithm for signature calculation

This is working fine for me

I have add dependency

compile 'commons-codec:commons-codec:1.9'

ref: http://mvnrepository.com/artifact/commons-codec/commons-codec/1.9

my function

public String encode(String key, String data) {
    try {

        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
        sha256_HMAC.init(secret_key);

        return new String(Hex.encodeHex(sha256_HMAC.doFinal(data.getBytes("UTF-8"))));

    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    return null;
}

Trust Anchor not found for Android SSL Connection

Update based on latest Android documentation (March 2017):

When you get this type of error:

javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
        at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:374)
        at libcore.net.http.HttpConnection.setupSecureSocket(HttpConnection.java:209)
        at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:478)
        at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:433)
        at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
        at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
        at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:282)
        at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:177)
        at libcore.net.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:271)

the issue could be one of the following:

  1. The CA that issued the server certificate was unknown
  2. The server certificate wasn't signed by a CA, but was self signed
  3. The server configuration is missing an intermediate CA

The solution is to teach HttpsURLConnection to trust a specific set of CAs. How? Please check https://developer.android.com/training/articles/security-ssl.html#CommonProblems

Others who are using AsyncHTTPClient from com.loopj.android:android-async-http library, please check Setup AsyncHttpClient to use HTTPS.

"Find next" in Vim

It is n for next and N for previous.

And if you use reverse search with ? (for example, ?cake) instead of /, it is the other way round.

If it is installed on your system, you should try to run vimtutor command from your terminal, which will start a tutorial of the basic Vim commands.

Rob Wells advice about * and # is also very pertinent.

How to randomize (or permute) a dataframe rowwise and columnwise?

If the goal is to randomly shuffle each column, some of the above answers don't work since the columns are shuffled jointly (this preserves inter-column correlations). Others require installing a package. Yet a one-liner exist:

df2 = lapply(df1, function(x) { sample(x) })

How to find available directory objects on Oracle 11g system?

The ALL_DIRECTORIES data dictionary view will have information about all the directories that you have access to. That includes the operating system path

SELECT owner, directory_name, directory_path
  FROM all_directories

Using grep to search for hex strings in a file

There's also a pretty handy tool called binwalk, written in python, which provides for binary pattern matching (and quite a lot more besides). Here's how you would search for a binary string, which outputs the offset in decimal and hex (from the docs):

$ binwalk -R "\x00\x01\x02\x03\x04" firmware.bin
DECIMAL     HEX         DESCRIPTION
--------------------------------------------------------------------------
377654      0x5C336     Raw string signature

iTerm 2: How to set keyboard shortcuts to jump to beginning/end of line?

Follow the tutorial you listed above for setting up your key preferences in iterm2.

  1. Create a new shorcut key
  2. Choose "Send escape sequence" as the action
  3. Then, to set cmd-left, in the text below that:
    • Enter [H for line start
      OR
    • Enter [F for line end

Best way to specify whitespace in a String.Split operation

you can use

var FirstString = YourString.Split().First();

to split string .

Difference between timestamps with/without time zone in PostgreSQL

Here is an example that should help. If you have a timestamp with a timezone, you can convert that timestamp into any other timezone. If you haven't got a base timezone it won't be converted correctly.

SELECT now(),
   now()::timestamp,
   now() AT TIME ZONE 'CST',
   now()::timestamp AT TIME ZONE 'CST'

Output:

-[ RECORD 1 ]---------------------------
now      | 2018-09-15 17:01:36.399357+03
now      | 2018-09-15 17:01:36.399357
timezone | 2018-09-15 08:01:36.399357
timezone | 2018-09-16 02:01:36.399357+03

Get a timestamp in C in microseconds?

You need to add in the seconds, too:

unsigned long time_in_micros = 1000000 * tv.tv_sec + tv.tv_usec;

Note that this will only last for about 232/106 =~ 4295 seconds, or roughly 71 minutes though (on a typical 32-bit system).

Git status shows files as changed even though contents are the same

In my case the files were appeared as modified after changing the files permissions.

To make git ignore permission changes, do the following :

# For the current repository
git config core.filemode false   

# Globally
git config --global core.filemode false

Configure WAMP server to send email

I used Mercury/32 and Pegasus Mail to get the mail() functional. It works great too as a mail server if you want an email address ending with your domain name.

Running command line silently with VbScript and getting output?

Look for assigning the output to Clipboard (in your first script) and then in second script parse Clipboard value.

How to set column widths to a jQuery datatable?

The best solution I found this to work for me guys after trying all the other solutions.... Basically i set the sScrollX to 200% then set the individual column widths to the required % that I wanted. The more columns that you have and the more space that you require then you need to raise the sScrollX %... The null means that I want those columns to retain the datatables auto width they have set in their code. enter image description here

            $('#datatables').dataTable
            ({  
                "sScrollX": "200%", //This is what made my columns increase in size.
                "bScrollCollapse": true,
                "sScrollY": "320px",

                "bAutoWidth": false,
                "aoColumns": [
                    { "sWidth": "10%" }, // 1st column width 
                    { "sWidth": "null" }, // 2nd column width 
                    { "sWidth": "null" }, // 3rd column width
                    { "sWidth": "null" }, // 4th column width 
                    { "sWidth": "40%" }, // 5th column width 
                    { "sWidth": "null" }, // 6th column width
                    { "sWidth": "null" }, // 7th column width 
                    { "sWidth": "10%" }, // 8th column width 
                    { "sWidth": "10%" }, // 9th column width
                    { "sWidth": "40%" }, // 10th column width
                    { "sWidth": "null" } // 11th column width
                    ],
                "bPaginate": true,              
                "sDom": '<"H"TCfr>t<"F"ip>',
                "oTableTools": 
                {
                    "aButtons": [ "copy", "csv", "print", "xls", "pdf" ],
                    "sSwfPath": "copy_cvs_xls_pdf.swf"
                },
                "sPaginationType":"full_numbers",
                "aaSorting":[[0, "desc"]],
                "bJQueryUI":true    

            });

Windows: XAMPP vs WampServer vs EasyPHP vs alternative

I won't make such a big deal from this question.
It's not like choosing your new wife or car.
I'd never run any of these on a production server, so, to run just some quick tests any of them are equally good.

How to send an email using PHP?

Also look into the PEAR mail package Pear Mail Page

It seems to be a little more robust than the standard mail() function that is built in (if the standard function isn't adequate).

Here is an excerpt from this page showing how it is used. PEAR Mail send() usage

<?php
    include('Mail.php');

    $recipients = '[email protected]';

    $headers['From']    = '[email protected]';
    $headers['To']      = '[email protected]';
    $headers['Subject'] = 'Test message';

    $body = 'Test message';

    $smtpinfo["host"] = "smtp.server.com";
    $smtpinfo["port"] = "25";
    $smtpinfo["auth"] = true;
    $smtpinfo["username"] = "smtp_user";
    $smtpinfo["password"] = "smtp_password";


    // Create the mail object using the Mail::factory method
    $mail_object =& Mail::factory("smtp", $smtpinfo); 

    $mail_object->send($recipients, $headers, $body);
?> 

jQuery Scroll to Div

$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});

Check this link: http://css-tricks.com/snippets/jquery/smooth-scrolling/ for a demo, I've used it before and it works quite nicely.

How to detect if multiple keys are pressed at once using JavaScript?

document.onkeydown = keydown; 

function keydown (evt) { 

    if (!evt) evt = event; 

    if (evt.ctrlKey && evt.altKey && evt.keyCode === 115) {

        alert("CTRL+ALT+F4"); 

    } else if (evt.shiftKey && evt.keyCode === 9) { 

        alert("Shift+TAB");

    } 

}

Android "Only the original thread that created a view hierarchy can touch its views."

I use Handler with Looper.getMainLooper(). It worked fine for me.

    Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
              // Any UI task, example
              textView.setText("your text");
        }
    };
    handler.sendEmptyMessage(1);

How to serialize SqlAlchemy result to JSON?

step1:
class CNAME:
   ...
   def as_dict(self):
       return {item.name: getattr(self, item.name) for item in self.__table__.columns}

step2:
list = []
for data in session.query(CNAME).all():
    list.append(data.as_dict())

step3:
return jsonify(list)

Adding a column to an existing table in a Rails migration

Use this command at rails console

rails generate migration add_fieldname_to_tablename fieldname:string

and

rake db:migrate

to run this migration

Applying Comic Sans Ms font style

The font may exist with different names, and not at all on some systems, so you need to use different variations and fallback to get the closest possible look on all systems:

font-family: "Comic Sans MS", "Comic Sans", cursive;

Be careful what you use this font for, though. Many consider it as ugly and overused, so it should not be use for something that should look professional.

What is the meaning of # in URL and how can I use that?

Yes, it is mainly to anchor your keywords, in particular the location of your page, so whenever URL loads the page with particular anchor name, then it will be pointed to that particular location.

For example, www.something.com/some_page/#computer if it is very lengthy page and you want to show exactly computer then you can anchor.

<p> adfadsf </p>
<p> adfadsf </p>
<p> adfadsf </p>
<a name="computer"></a><p> Computer topics </p>
<p> adfadsf </p>

Now the page will scroll and bring computer-related topics to the top.

Printing out a linked list using toString

As has been pointed out in some other answers and comments, what you are missing here is a call to the JVM System class to print out the string generated by your toString() method.

LinkedList myLinkedList = new LinkedList();
System.out.println(myLinkedList.toString());

This will get the job done, but I wouldn't recommend doing it that way. If we take a look at the javadocs for the Object class, we find this description for toString():

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

The emphasis added there is my own. You are creating a string that contains the entire state of the linked list, which somebody using your class is probably not expecting. I would recommend the following changes:

  1. Add a toString() method to your LinkedListNode class.
  2. Update the toString() method in your LinkedList class to be more concise.
  3. Add a new method called printList() to your LinkedList class that does what you are currently expecting toString() to do.

In LinkedListNode:

public String toString(){
   return "LinkedListNode with data: " + getData();
}

In LinkedList:

public int size(){
    int currentSize = 0;
    LinkedListNode current = head;
    while(current != null){
        currentSize = currentSize + 1;
        current = current.getNext();
    }

    return currentSize;
}

public String toString(){
    return "LinkedList with " + size() + "elements.";
}

public void printList(){
    System.out.println("Contents of " + toString());

    LinkedListNode current = head;
    while(current != null){
        System.out.println(current.toString());
        current = current.getNext();
    }

}

SSL error SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

The problem is in new PHP Version in macOS Sierra

Please add

stream_context_set_option($ctx, 'ssl', 'verify_peer', false);

How do I convert an ANSI encoded file to UTF-8 with Notepad++?

If you don't have non-ASCII characters (codepoints 128 and above) in your file, UTF-8 without BOM is the same as ASCII, byte for byte - so Notepad++ will guess wrong.

What you need to do is to specify the character encoding when serving the AJAX response - e.g. with PHP, you'd do this:

header('Content-Type: application/json; charset=utf-8');

The important part is to specify the charset with every JS response - else IE will fall back to user's system default encoding, which is wrong most of the time.

Find the index of a char in string?

Contanis occur if using the method of the present letter, and store the corresponding number using the IndexOf method, see example below.

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim myString As String = "abcdef"
    Dim numberString As String = String.Empty

    If myString.Contains("d") Then
        numberString = myString.IndexOf("d")
    End If
End Sub

Another sample with TextBox

  Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim myString As String = "abcdef"
    Dim numberString As String = String.Empty

    If myString.Contains(me.TextBox1.Text) Then
        numberString = myString.IndexOf(Me.TextBox1.Text)
    End If
End Sub

Regards

Bootstrap with jQuery Validation Plugin

for bootstrap 4 this work with me good

    $.validator.setDefaults({
    highlight: function(element) {
        $(element).closest('.form-group').find(".form-control:first").addClass('is-invalid');
    },
    unhighlight: function(element) {
        $(element).closest('.form-group').find(".form-control:first").removeClass('is-invalid');
        $(element).closest('.form-group').find(".form-control:first").addClass('is-valid');

    },
    errorElement: 'span',
    errorClass: 'invalid-feedback',
    errorPlacement: function(error, element) {
        if(element.parent('.input-group').length) {
            error.insertAfter(element.parent());
        } else {
            error.insertAfter(element);
        }
    }
});

hope it will help !

Prevent flicker on webkit-transition of webkit-transform

For a more detailed explanation, check out this post:

http://www.viget.com/inspire/webkit-transform-kill-the-flash/

I would definitely avoid applying it to the entire body. The key is to make sure whatever specific element you plan on transforming in the future starts out rendered in 3d so the browsers doesn't have to switch in and out of rendering modes. Adding

-webkit-transform: translateZ(0) 

(or either of the options already mentioned) to the animated element will accomplish this.

How to search in an array with preg_match?

You can use array_walk to apply your preg_match function to each element of the array.

http://us3.php.net/array_walk

Open Source HTML to PDF Renderer with Full CSS Support

It's not open source, but you can at least get a free personal use license to Prince, which really does a lovely job.

How do I find a default constraint using INFORMATION_SCHEMA?

WHILE EXISTS( 
    SELECT * FROM  sys.all_columns 
    INNER JOIN sys.tables ST  ON all_columns.object_id = ST.object_id
    INNER JOIN sys.schemas ON ST.schema_id = schemas.schema_id
    INNER JOIN sys.default_constraints ON all_columns.default_object_id = default_constraints.object_id
    WHERE 
    schemas.name = 'dbo'
    AND ST.name = 'MyTable'
)
BEGIN 
DECLARE @SQL NVARCHAR(MAX) = N'';

SET @SQL = (  SELECT TOP 1
     'ALTER TABLE ['+  schemas.name + '].[' + ST.name + '] DROP CONSTRAINT ' + default_constraints.name + ';'
   FROM 
      sys.all_columns

         INNER JOIN
      sys.tables ST
         ON all_columns.object_id = ST.object_id

         INNER JOIN 
      sys.schemas
         ON ST.schema_id = schemas.schema_id

         INNER JOIN
      sys.default_constraints
         ON all_columns.default_object_id = default_constraints.object_id

   WHERE 
         schemas.name = 'dbo'
      AND ST.name = 'MyTable'
      )
   PRINT @SQL
   EXECUTE sp_executesql @SQL 

   --End if Error 
   IF @@ERROR <> 0 
   BREAK
END 

How to get the fragment instance from the FragmentActivity?

To get the fragment instance in a class that extends FragmentActivity:

MyclassFragment instanceFragment=
    (MyclassFragment)getSupportFragmentManager().findFragmentById(R.id.idFragment);

To get the fragment instance in a class that extends Fragment:

MyclassFragment instanceFragment =  
    (MyclassFragment)getFragmentManager().findFragmentById(R.id.idFragment);

Getting the name / key of a JToken with JSON.net

JObject obj = JObject.Parse(json);
var attributes = obj["parent"]["child"]...["your desired element"].ToList<JToken>(); 

foreach (JToken attribute in attributes)
{   
    JProperty jProperty = attribute.ToObject<JProperty>();
    string propertyName = jProperty.Name;
}

How to set base url for rest in spring boot?

For spring boot framework version 2.0.4.RELEASE+. Add this line to application.properties

server.servlet.context-path=/api

get value from DataTable

It looks like you have accidentally declared DataType as an array rather than as a string.

Change line 3 to:

Dim DataType As String = myTableData.Rows(i).Item(1)

That should work.

Using 'starts with' selector on individual class names

this is for prefix with

$("div[class^='apple-']")

this is for starts with so you dont need to have the '-' char in there

$("div[class|='apple']")

you can find a bunch of other cool variations of the jQuery selector here https://api.jquery.com/category/selectors/

use std::fill to populate vector with increasing numbers

brainsandwich and underscore_d gave very good ideas. Since to fill is to change content, for_each(), the simplest among the STL algorithms, should also fill the bill:

std::vector<int> v(10);
std::for_each(v.begin(), v.end(), [i=0] (int& x) mutable {x = i++;});    

The generalized capture [i=o] imparts the lambda expression with an invariant and initializes it to a known state (in this case 0). the keyword mutable allows this state to be updated each time lambda is called.

It takes only a slight modification to get a sequence of squares:

std::vector<int> v(10);
std::for_each(v.begin(), v.end(), [i=0] (int& x) mutable {x = i*i; i++;});

To generate R-like seq is no more difficult, but note that in R, the numeric mode is actually double, so there really isn't a need to parametrize the type. Just use double.

Array versus linked-list

Arrays Vs Linked List:

  1. Array memory allocation will fail sometimes because of fragmented memory.
  2. Caching is better in Arrays as all elements are allocated contiguous memory space.
  3. Coding is more complex than Arrays.
  4. No size constraint on Linked List, unlike Arrays
  5. Insertion/Deletion is faster in Linked List and access is faster in Arrays.
  6. Linked List better from multi-threading point of view.

How can I maintain fragment state when added to the back stack?

Here, since onSaveInstanceState in fragment does not call when you add fragment into backstack. The fragment lifecycle in backstack when restored start onCreateView and end onDestroyView while onSaveInstanceState is called between onDestroyView and onDestroy. My solution is create instance variable and init in onCreate. Sample code:

private boolean isDataLoading = true;
private ArrayList<String> listData;
public void onCreate(Bundle savedInstanceState){
     super.onCreate(savedInstanceState);
     isDataLoading = false;
     // init list at once when create fragment
     listData = new ArrayList();
}

And check it in onActivityCreated:

public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    if(isDataLoading){
         fetchData();
    }else{
         //get saved instance variable listData()
    }
}

private void fetchData(){
     // do fetch data into listData
}

How to parse dates in multiple formats using SimpleDateFormat

This solution checks all the possible formats before throwing an exception. This solution is more convenient if you are trying to test for multiple date formats.

Date extractTimestampInput(String strDate){
    final List<String> dateFormats = Arrays.asList("yyyy-MM-dd HH:mm:ss.SSS", "yyyy-MM-dd");    

    for(String format: dateFormats){
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        try{
            return sdf.parse(strDate);
        } catch (ParseException e) {
             //intentionally empty
        }
    }
        throw new IllegalArgumentException("Invalid input for date. Given '"+strDate+"', expecting format yyyy-MM-dd HH:mm:ss.SSS or yyyy-MM-dd.");

}

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

Good answers from gdw2 and d5e5. To make it a little simpler here are the recommendations pulled together in a single series of commands:

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

Configuration System Failed to Initialize

I tried all of the solutions above trying to figure out why one of my unit tests were failing to pick up the configuration from an app.config file that is perfect.

I had 2 references to the same assembly like so:

duplicate reference

project file before and after

Removing the (duplicate) reference in yellow fixed it for me.

I hope this works for someone else, it drove me nuts for a while.

Where to find free public Web Services?

Here you can find some public REST services for encryption and security related things: http://security.jelastic.servint.net

Splitting comma separated string in a PL/SQL stored proc

This should do what you are looking for.. It assumes your list will always be just numbers. If that is not the case, just change the references to DBMS_SQL.NUMBER_TABLE to a table type that works for all of your data:

CREATE OR REPLACE PROCEDURE insert_from_lists(
    list1_in IN VARCHAR2,
    list2_in IN VARCHAR2,
    delimiter_in IN VARCHAR2 := ','
)
IS 
    v_tbl1 DBMS_SQL.NUMBER_TABLE;
    v_tbl2 DBMS_SQL.NUMBER_TABLE;

    FUNCTION list_to_tbl
    (
        list_in IN VARCHAR2
    )
    RETURN DBMS_SQL.NUMBER_TABLE
    IS
        v_retval DBMS_SQL.NUMBER_TABLE;
    BEGIN

        IF list_in is not null
        THEN
            /*
            || Use lengths loop through the list the correct amount of times,
            || and substr to get only the correct item for that row
            */
            FOR i in 1 .. length(list_in)-length(replace(list_in,delimiter_in,''))+1
            LOOP
                /*
                || Set the row = next item in the list
                */
                v_retval(i) := 
                        substr (
                            delimiter_in||list_in||delimiter_in,
                            instr(delimiter_in||list_in||delimiter_in, delimiter_in, 1, i  ) + 1,
                            instr (delimiter_in||list_in||delimiter_in, delimiter_in, 1, i+1) - instr (delimiter_in||list_in||delimiter_in, delimiter_in, 1, i) -1
                        );
            END LOOP;
        END IF;

        RETURN v_retval;

    END list_to_tbl;
BEGIN 
   -- Put lists into collections
   v_tbl1 := list_to_tbl(list1_in);
   v_tbl2 := list_to_tbl(list2_in);

   IF v_tbl1.COUNT <> v_tbl2.COUNT
   THEN
      raise_application_error(num => -20001, msg => 'Length of lists do not match');
   END IF;

   -- Bulk insert from collections
   FORALL i IN INDICES OF v_tbl1
      insert into tmp (a, b)
      values (v_tbl1(i), v_tbl2(i));

END insert_from_lists; 

Clearing state es6 React

This is the solution implemented as a function:

Class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = this.getInitialState();
  }

  getInitialState = () => ({
    /* state props */
  })

  resetState = () => {
     this.setState(this.getInitialState());
  }
}

How can I parse a time string containing milliseconds in it with python?

DNS answer above is actually incorrect. The SO is asking about milliseconds but the answer is for microseconds. Unfortunately, Python`s doesn't have a directive for milliseconds, just microseconds (see doc), but you can workaround it by appending three zeros at the end of the string and parsing the string as microseconds, something like:

datetime.strptime(time_str + '000', '%d/%m/%y %H:%M:%S.%f')

where time_str is formatted like 30/03/09 16:31:32.123.

Hope this helps.

Yum fails with - There are no enabled repos.

ok, so my problem was that I tried to install the package with yum which is the primary tool for getting, installing, deleting, querying, and managing Red Hat Enterprise Linux RPM software packages from official Red Hat software repositories, as well as other third-party repositories.

But I'm using ubuntu and The usual way to install packages on the command line in Ubuntu is with apt-get. so the right command was:

sudo apt-get install libstdc++.i686

Default settings Raspberry Pi /etc/network/interfaces

For my Raspberry Pi 3B model it was

auto lo
iface lo inet loopback

auto eth0
iface eth0 inet manual

allow-hotplug wlan0
iface wlan0 inet manual
    wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf

allow-hotplug wlan1
iface wlan1 inet manual
    wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf

Inserting the iframe into react component

With ES6 you can now do it like this

Example Codepen URl to load

const iframe = '<iframe height="265" style="width: 100%;" scrolling="no" title="fx." src="//codepen.io/ycw/embed/JqwbQw/?height=265&theme-id=0&default-tab=js,result" frameborder="no" allowtransparency="true" allowfullscreen="true">See the Pen <a href="https://codepen.io/ycw/pen/JqwbQw/">fx.</a> by ycw(<a href="https://codepen.io/ycw">@ycw</a>) on <a href="https://codepen.io">CodePen</a>.</iframe>'; 

A function component to load Iframe

function Iframe(props) {
  return (<div dangerouslySetInnerHTML={ {__html:  props.iframe?props.iframe:""}} />);
}

Usage:

import React from "react";
import ReactDOM from "react-dom";
function App() {
  return (
    <div className="App">
      <h1>Iframe Demo</h1>
      <Iframe iframe={iframe} />,
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Edit on CodeSandbox:

https://codesandbox.io/s/react-iframe-demo-g3vst

Using Javascript: How to create a 'Go Back' link that takes the user to a link if there's no history for the tab or window?

Added a new answer to display the code formatted:

The thing is that you were checking for document.referer, because you were in ff it was returning always true, then it was navigating to http://mysite.com. Try the following:

function backAway(){
    if (document.referrer) {
        //firefox, chrome, etc..
        i = 0;
    } else {
        // under ie
        i = 1;
    }
    if (history.length>i)
    {
        // there are items in history property
        history.back();
    } else {
        window.location = 'http://www.mysite.com/';
    }
    return false;
}

Python - Get Yesterday's date as a string in YYYY-MM-DD format

>>> import datetime
>>> datetime.date.fromordinal(datetime.date.today().toordinal()-1).strftime("%F")
'2015-05-26'

How to delete all records from table in sqlite with Android?

//Delete all records of table
db.execSQL("DELETE FROM " + TABLE_NAME);

//Reset the auto_increment primary key if you needed
db.execSQL("UPDATE SQLITE_SEQUENCE SET SEQ=0 WHERE NAME=" + TABLE_NAME);

//For go back free space by shrinking sqlite file
db.execSQL("VACUUM");

How to set top-left alignment for UILabel for iOS application?

If what you need is non-editable text that by default starts at the top left corner you can simply use a Text View instead of a label and then set its state to non-editable, like this:

textview.isEditable = false

Way easier than messing with the labels...

Cheers!

Returning JSON response from Servlet to Javascript/JSP page

I used JSONObject as shown below in Servlet.

    JSONObject jsonReturn = new JSONObject();

    NhAdminTree = AdminTasks.GetNeighborhoodTreeForNhAdministrator( connection, bwcon, userName);

    map = new HashMap<String, String>();
    map.put("Status", "Success");
    map.put("FailureReason", "None");
    map.put("DataElements", "2");

    jsonReturn = new JSONObject();
    jsonReturn.accumulate("Header", map);

    List<String> list = new ArrayList<String>();
    list.add(NhAdminTree);
    list.add(userName);

    jsonReturn.accumulate("Elements", list);

The Servlet returns this JSON object as shown below:

    response.setContentType("application/json");
    response.getWriter().write(jsonReturn.toString());

This Servlet is called from Browser using AngularJs as below

$scope.GetNeighborhoodTreeUsingPost = function(){
    alert("Clicked GetNeighborhoodTreeUsingPost : " + $scope.userName );

    $http({

        method: 'POST',
        url : 'http://localhost:8080/EPortal/xlEPortalService',
        headers: {
           'Content-Type': 'application/json'
         },
        data : {
            'action': 64,
            'userName' : $scope.userName
        }
    }).success(function(data, status, headers, config){
        alert("DATA.header.status : " + data.Header.Status);
        alert("DATA.header.FailureReason : " + data.Header.FailureReason);
        alert("DATA.header.DataElements : " + data.Header.DataElements);
        alert("DATA.elements : " + data.Elements);

    }).error(function(data, status, headers, config) {
        alert(data + " : " + status + " : " + headers + " : " + config);
    });

};

This code worked and it is showing correct data in alert dialog box:

Data.header.status : Success

Data.header.FailureReason : None

Data.header.DetailElements : 2

Data.Elements : Coma seperated string values i.e. NhAdminTree, userName

getDate with Jquery Datepicker

You can format the jquery date with this line:

moment($(elem).datepicker('getDate')).format("YYYY-MM-DD");

http://momentjs.com

MySQL stored procedure vs function, which would I use when?

Stored procedure can be called recursively but stored function can not

Set Windows process (or user) memory limit

Use Windows Job Objects. Jobs are like process groups and can limit memory usage and process priority.

Best algorithm for detecting cycles in a directed graph

Given that this is a schedule of jobs, I suspect that at some point you are going to sort them into a proposed order of execution.

If that's the case, then a topological sort implementation may in any case detect cycles. UNIX tsort certainly does. I think it is likely that it is therefore more efficient to detect cycles at the same time as tsorting, rather than in a separate step.

So the question might become, "how do I most efficiently tsort", rather than "how do I most efficiently detect loops". To which the answer is probably "use a library", but failing that the following Wikipedia article:

http://en.wikipedia.org/wiki/Topological_sorting

has the pseudo-code for one algorithm, and a brief description of another from Tarjan. Both have O(|V| + |E|) time complexity.

Parse a URI String into Name-Value Collection

Here is my solution with reduce and Optional:

private Optional<SimpleImmutableEntry<String, String>> splitKeyValue(String text) {
    String[] v = text.split("=");
    if (v.length == 1 || v.length == 2) {
        String key = URLDecoder.decode(v[0], StandardCharsets.UTF_8);
        String value = v.length == 2 ? URLDecoder.decode(v[1], StandardCharsets.UTF_8) : null;
        return Optional.of(new SimpleImmutableEntry<String, String>(key, value));
    } else
        return Optional.empty();
}

private HashMap<String, String> parseQuery(URI uri) {
    HashMap<String, String> params = Arrays.stream(uri.getQuery()
            .split("&"))
            .map(this::splitKeyValue)
            .filter(Optional::isPresent)
            .map(Optional::get)
            .reduce(
                // initial value
                new HashMap<String, String>(), 
                // accumulator
                (map, kv) -> {
                     map.put(kv.getKey(), kv.getValue()); 
                     return map;
                }, 
                // combiner
                (a, b) -> {
                     a.putAll(b); 
                     return a;
                });
    return params;
}
  • I ignore duplicate parameters (I take the last one).
  • I use Optional<SimpleImmutableEntry<String, String>> to ignore garbage later
  • The reduction start with an empty map, then populate it on each SimpleImmutableEntry

In case you ask, reduce requires this weird combiner in the last parameter, which is only used in parallel streams. Its goal is to merge two intermediate results (here HashMap).

java.net.MalformedURLException: no protocol

Try instead of db.parse(xml):

Document doc = db.parse(new InputSource(new StringReader(**xml**)));

Animate scroll to ID on page load

$(jQuery.browser.webkit ? "body": "html").animate({ scrollTop: $('#title1').offset().top }, 1000);

jquery-animate-body-for-all-browsers.

Printing list elements on separated lines in Python

Another good option for handling this kind of option is the pprint module, which (among other things) pretty prints long lists with one element per line:

>>> import sys
>>> import pprint
>>> pprint.pprint(sys.path)
['',
 '/usr/lib/python27.zip',
 '/usr/lib/python2.7',
 '/usr/lib/python2.7/plat-linux2',
 '/usr/lib/python2.7/lib-tk',
 '/usr/lib/python2.7/lib-old',
 '/usr/lib/python2.7/lib-dynload',
 '/usr/lib/python2.7/site-packages',
 '/usr/lib/python2.7/site-packages/PIL',
 '/usr/lib/python2.7/site-packages/gst-0.10',
 '/usr/lib/python2.7/site-packages/gtk-2.0',
 '/usr/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg-info',
 '/usr/lib/python2.7/site-packages/webkit-1.0']
>>> 

ADB not responding. You can wait more,or kill "adb.exe" process manually and click 'Restart'

1.if your phone system is over 4.2.2 , there will be enter image description here

2.disconnect the USB and try again or restart your phone

3.After after all try , it didn't work. It may be a shortage power supply so try other usb interface on your computer.

I solved the problem doing the first step . anyway have try.

Timer for Python game

As a learning exercise for myself, I created a class to be able to create several stopwatch timer instances that you might find useful (I'm sure there are better/simpler versions around in the time modules or similar)

import time as tm
class Watch:
    count = 0
    description = "Stopwatch class object (default description)"
    author = "Author not yet set"
    name = "not defined"
    instances = []
    def __init__(self,name="not defined"):
        self.name = name
        self.elapsed = 0.
        self.mode = 'init'
        self.starttime = 0.
        self.created = tm.strftime("%Y-%m-%d %H:%M:%S", tm.gmtime())
        Watch.count += 1

    def __call__(self):
        if self.mode == 'running':
            return tm.time() - self.starttime
        elif self.mode == 'stopped':
            return self.elapsed
        else:
            return 0.

    def display(self):
        if self.mode == 'running':
            self.elapsed = tm.time() - self.starttime
        elif self.mode == 'init':
            self.elapsed = 0.
        elif self.mode == 'stopped':
            pass
        else:
            pass
        print "Name:       ", self.name
        print "Address:    ", self
        print "Created:    ", self.created
        print "Start-time: ", self.starttime
        print "Mode:       ", self.mode
        print "Elapsed:    ", self.elapsed
        print "Description:", self.description
        print "Author:     ", self.author

    def start(self):
        if self.mode == 'running':
            self.starttime = tm.time()
            self.elapsed = tm.time() - self.starttime
        elif self.mode == 'init':
            self.starttime = tm.time()
            self.mode = 'running'
            self.elapsed = 0.
        elif self.mode == 'stopped':
            self.mode = 'running'
            #self.elapsed = self.elapsed + tm.time() - self.starttime
            self.starttime = tm.time() - self.elapsed
        else:
            pass
        return

    def stop(self):
        if self.mode == 'running':
            self.mode = 'stopped'
            self.elapsed = tm.time() - self.starttime
        elif self.mode == 'init':
            self.mode = 'stopped'
            self.elapsed = 0.
        elif self.mode == 'stopped':
            pass
        else:
            pass
        return self.elapsed

    def lap(self):
        if self.mode == 'running':
            self.elapsed = tm.time() - self.starttime
        elif self.mode == 'init':
            self.elapsed = 0.
        elif self.mode == 'stopped':
            pass
        else:
            pass
        return self.elapsed

    def reset(self):
        self.starttime=0.
        self.elapsed=0.
        self.mode='init'
        return self.elapsed

def WatchList():
    return [i for i,j in zip(globals().keys(),globals().values()) if '__main__.Watch instance' in str(j)]

I need to learn Web Services in Java. What are the different types in it?

Q1) Here are couple things to read or google more :

Main differences between SOAP and RESTful web services in java http://www.ajaxonomy.com/2008/xml/web-services-part-1-soap-vs-rest

It's up to you what do you want to learn first. I'd recommend you take a look at the CXF framework. You can build both rest/soap services.

Q2) Here are couple of good tutorials for soap (I had them bookmarked) :

http://united-coders.com/phillip-steffensen/developing-a-simple-soap-webservice-using-spring-301-and-apache-cxf-226

http://www.benmccann.com/blog/web-services-tutorial-with-apache-cxf/

http://www.mastertheboss.com/web-interfaces/337-apache-cxf-interceptors.html

Best way to learn is not just reading tutorials. But you would first go trough tutorials to get a basic idea so you can see that you're able to produce something(or not) and that would get you motivated.

SO is great way to learn particular technology (or more), people ask lot of wierd questions, and there are ever weirder answers. But overall you'll learn about ways to solve issues on other way. Maybe you didn't know of that way, maybe you couldn't thought of it by yourself.

Subscribe to couple of tags that are interesting to you and be persistent, ask good questions and try to give good answers and I guarantee you that you'll learn this as time passes (if you're persistent that is).

Q3) You will have to answer this one yourself. First by deciding what you're going to build, after all you will need to think of some mini project or something and take it from there.

If you decide to use CXF as your framework for building either REST/SOAP services I'd recommend you look up this book Apache CXF Web Service Development. It's fantastic, not hard to read and not too big either (win win).

Error Message : Cannot find or open the PDB file

  1. Please check if the setting Generate Debug Info is Yes which under Project Propeties > Configuration Properties > Linker > Debugging tab. If not, try to change it to Yes.

  2. Those perticular pdb's ( for ntdll.dll, mscoree.dll, kernel32.dll, etc ) are for the windows API and shouldn't be needed for simple apps. However, if you cannot find pdb's for your own compiled projects, I suggest making sure the Project Properties > Configuration Properties > Debugging > Working Directory uses the value from Project Properties > Configuration Properties > General > Output Directory .

  3. You need to run Visual c++ in "Run as Administrator" mode.Right click on the executable and click "Run as Administrator"

How to open a web page automatically in full screen mode

window.onload = function() {
    var el = document.documentElement,
        rfs = el.requestFullScreen
        || el.webkitRequestFullScreen
        || el.mozRequestFullScreen;
    rfs.call(el);
};

how to get the one entry from hashmap without iterating

import java.util.*;

public class Friday {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<String, Integer>();

        map.put("code", 10);
        map.put("to", 11);
        map.put("joy", 12);

        if (! map.isEmpty()) {
            Map.Entry<String, Integer> entry = map.entrySet().iterator().next();
            System.out.println(entry);
        }
    }
}

This approach doesn't work because you used HashMap. I assume using LinkedHashMap will be right solution in this case.

How to disable gradle 'offline mode' in android studio?

On Windows:-

Go to File -> Settings.

And open the 'Build,Execution,Deployment'. Then open the

Build Tools -> Gradle

Then uncheck -> Offline work on the right.

Click the OK button.

Then Rebuild the Project.

On Mac OS:-

go to Android Studio -> Preferences, and the rest is the same. OR follow steps given in the image

[For Mac go 1

enter image description here

'ng' is not recognized as an internal or external command, operable program or batch file

I was with the same problem and now discovered a working solution. After successful installation of node and angular CLI do the following steps.

Open C:\usr\local and copy the path or the path where angular CLI located on your machine.

enter image description here

Now open environment variable in your Windows, and add copied path in the following location:

Advanced > Environment Variable > User Variables and System Variables as below image:

enter image description here

That's all, now open cmd and try with any 'ng' command:

enter image description here

android - setting LayoutParams programmatically

For Xamarin Android align to the left of an object

int dp24 = (int)TypedValue.ApplyDimension( ComplexUnitType.Dip, 24, Resources.System.DisplayMetrics );
            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams( dp24, dp24 );
            lp.AddRule( LayoutRules.CenterInParent, 1 );
            lp.AddRule( LayoutRules.LeftOf, //Id of the field Eg m_Button.Id ); 
            m_Button.LayoutParameters = lp;

Jmeter - Run .jmx file through command line and get the summary report in a excel

This worked for me on mac os High sierra 10.13.6, java 8 64-bit, jmeter 4.0

$  jmeter -n --testfile /path/to/Test_Plan.jmx

Sample output:

Creating summariser <summary>
Created the tree successfully using ./src/test/jmeter/Test_Plan.jmx
Starting the test @ Fri Aug 24 17:18:18 PDT 2018 (1535156298333)
Waiting for possible Shutdown/StopTestNow/Heapdump message on port 4445
summary =     10 in 00:00:09 =    1.1/s Avg:  6666 Min:  1000 Max:  8950 Err:     
0 (0.00%)
Tidying up ...    @ Fri Aug 24 17:18:28 PDT 2018 (1535156308049)
... end of run

How do I wait for an asynchronously dispatched block to finish?

I have to wait until a UIWebView is loaded before running my method, I was able to get this working by performing UIWebView ready checks on main thread using GCD in combination with semaphore methods mentioned in this thread. Final code looks like this:

-(void)myMethod {

    if (![self isWebViewLoaded]) {

            dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);

            __block BOOL isWebViewLoaded = NO;

            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

                while (!isWebViewLoaded) {

                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((0.0) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        isWebViewLoaded = [self isWebViewLoaded];
                    });

                    [NSThread sleepForTimeInterval:0.1];//check again if it's loaded every 0.1s

                }

                dispatch_sync(dispatch_get_main_queue(), ^{
                    dispatch_semaphore_signal(semaphore);
                });

            });

            while (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW)) {
                [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0]];
            }

        }

    }

    //Run rest of method here after web view is loaded

}

Javascript How to define multiple variables on a single line?

note you can only do this with Numbers and Strings

you could do...

var a, b, c; a = b = c = 0; //but why?

c++;
// c = 1, b = 0, a = 0;

python pandas convert index to datetime

In my case, my dataframe has the following characteristics

<class 'pandas.core.frame.DataFrame'>
Index: 3040 entries, 15/12/2008 to  
Data columns (total 1 columns):
 #   Column  Non-Null Count  Dtype  
---  ------  --------------  -----  
 0   Close   3038 non-null   float64
dtypes: float64(1)
memory usage: 47.5+ KB

enter image description here

The first option data.index = pd.to_datetime(data.index) returned

ParserError: String does not contain a date: ParserError: String does not contain a date:

The second option: data.index.to_datetime() returned

AttributeError: 'Index' object has no attribute 'to_datetime'

It returned

Another option I have tested is. data.index = pd.to_datetime(data.index)

It returned: ParserError: String does not contain a date:

What could be my problem? Thanks

Override browser form-filling and input highlighting with HTML/CSS

Simple javascript solution for all browser:

setTimeout(function() {
    $(".parent input").each(function(){
        parent = $(this).parents(".parent");
        $(this).clone().appendTo(parent);   
        $(this).attr("id","").attr("name","").hide();
    }); 
}, 300 );

Clone input, reset attribute and hide original input. Timeout is needed for iPad

Excel VBA code to copy a specific string to clipboard

Add a reference to the Microsoft Forms 2.0 Object Library and try this code. It only works with text, not with other data types.

Dim DataObj As New MSForms.DataObject

'Put a string in the clipboard
DataObj.SetText "Hello!"
DataObj.PutInClipboard

'Get a string from the clipboard
DataObj.GetFromClipboard
Debug.Print DataObj.GetText

Here you can find more details about how to use the clipboard with VBA.

A TypeScript GUID class?

There is an implementation in my TypeScript utilities based on JavaScript GUID generators.

Here is the code:

_x000D_
_x000D_
class Guid {_x000D_
  static newGuid() {_x000D_
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {_x000D_
      var r = Math.random() * 16 | 0,_x000D_
        v = c == 'x' ? r : (r & 0x3 | 0x8);_x000D_
      return v.toString(16);_x000D_
    });_x000D_
  }_x000D_
}_x000D_
_x000D_
// Example of a bunch of GUIDs_x000D_
for (var i = 0; i < 100; i++) {_x000D_
  var id = Guid.newGuid();_x000D_
  console.log(id);_x000D_
}
_x000D_
_x000D_
_x000D_

Please note the following:

C# GUIDs are guaranteed to be unique. This solution is very likely to be unique. There is a huge gap between "very likely" and "guaranteed" and you don't want to fall through this gap.

JavaScript-generated GUIDs are great to use as a temporary key that you use while waiting for a server to respond, but I wouldn't necessarily trust them as the primary key in a database. If you are going to rely on a JavaScript-generated GUID, I would be tempted to check a register each time a GUID is created to ensure you haven't got a duplicate (an issue that has come up in the Chrome browser in some cases).

How do I clone a single branch in Git?

For cloning a specific branch you can do :

git clone --branch yourBranchName [email protected]

dbms_lob.getlength() vs. length() to find blob size in oracle

length and dbms_lob.getlength return the number of characters when applied to a CLOB (Character LOB). When applied to a BLOB (Binary LOB), dbms_lob.getlength will return the number of bytes, which may differ from the number of characters in a multi-byte character set.

As the documentation doesn't specify what happens when you apply length on a BLOB, I would advise against using it in that case. If you want the number of bytes in a BLOB, use dbms_lob.getlength.

HTML.HiddenFor value set

For setting value in hidden field do in the following way:

@Html.HiddenFor(model => model.title, 
                new { id= "natureOfVisitField", Value = @Model.title})

It will work

Getting last month's date in php

Oh I figured this out, please ignore unless you have the same problem i did in which case:

$prevmonth = date("M Y",mktime(0,0,0,date("m")-1,1,date("Y")));

How to upgrade rubygems

I wouldn't use the debian packages, have a look at RVM or Rbenv.

List all devices, partitions and volumes in Powershell

Though this isn't 'powershell' specific... you can easily list the drives and partitions using diskpart, list volume

PS C:\Dev> diskpart

Microsoft DiskPart version 6.1.7601
Copyright (C) 1999-2008 Microsoft Corporation.
On computer: Box

DISKPART> list volume

Volume ###  Ltr  Label        Fs     Type        Size     Status     Info
----------  ---  -----------  -----  ----------  -------  ---------  --------
Volume 0     D                       DVD-ROM         0 B  No Media
Volume 1         C = System   NTFS   Partition    100 MB  Healthy    System
Volume 2     G   C = Box      NTFS   Partition    244 GB  Healthy    Boot
Volume 3     H   D = Data     NTFS   Partition    687 GB  Healthy
Volume 4     E   System Rese  NTFS   Partition    100 MB  Healthy

Twitter Bootstrap button click to toggle expand/collapse text section above button

html:

<h4 data-toggle-selector="#me">toggle</h4>
<div id="me">content here</div>

js:

$(function () {
    $('[data-toggle-selector]').on('click',function () {
        $($(this).data('toggle-selector')).toggle(300);
    })
})

How does Facebook disable the browser's integrated Developer Tools?

an simple solution!

setInterval(()=>console.clear(),1500);

Excel VBA Open a Folder

I use this to open a workbook and then copy that workbook's data to the template.

Private Sub CommandButton24_Click()
Set Template = ActiveWorkbook
 With Application.FileDialog(msoFileDialogOpen)
    .InitialFileName = "I:\Group - Finance" ' Yu can select any folder you want
    .Filters.Clear
    .Title = "Your Title"
    If Not .Show Then
        MsgBox "No file selected.": Exit Sub
    End If
    Workbooks.OpenText .SelectedItems(1)

'The below is to copy the file into a new sheet in the workbook and paste those values in sheet 1

    Set myfile = ActiveWorkbook
    ActiveWorkbook.Sheets(1).Copy after:=ThisWorkbook.Sheets(1)
    myfile.Close
    Template.Activate
    ActiveSheet.Cells.Select
    Selection.Copy
    Sheets("Sheet1").Select
    Cells.Select
    ActiveSheet.Paste

End With

Difference between INNER JOIN and LEFT SEMI JOIN

Trying to depict with venn diagrams for better understanding..

Left Semi join : A semi join returns values from the left side of the relation that has a match with the right. It is also referred to as a left semi join.

enter image description here

Note : There is another thing called left anti join : An anti join returns values from the left relation that has no match with the right. It is also referred to as a left anti join.

Inner join : It selects rows that have matching values in both relations.

enter image description here

Read response headers from API response - Angular 5 + TypeScript

Try this simple code.

1. Components side code: to get both body and header property. Here there's a token in body and Authorization in the header.

loginUser() {
    this.userService.loginTest(this.loginCred).
    subscribe(res => {
        let output1 = res;
        console.log(output1.body.token);
        console.log(output1.headers.get('Authorization'));
    })
}

2. Service side code: sending login data in the body and observe the response in Observable any which be subscribed in the component side.

loginTest(loginCred: LoginParams): Observable<any> {
    const header1= {'Content-Type':'application/json',};
    const body =  JSON.stringify(loginCred);
    return this.http.post<any>(this.baseURL+'signin',body,{
        headers: header1,
        observe: 'response',
        responseType: 'json'
    });
}

DNS caching in linux

On Linux (and probably most Unix), there is no OS-level DNS caching unless nscd is installed and running. Even then, the DNS caching feature of nscd is disabled by default at least in Debian because it's broken. The practical upshot is that your linux system very very probably does not do any OS-level DNS caching.

You could implement your own cache in your application (like they did for Squid, according to diegows's comment), but I would recommend against it. It's a lot of work, it's easy to get it wrong (nscd got it wrong!!!), it likely won't be as easily tunable as a dedicated DNS cache, and it duplicates functionality that already exists outside your application.

If an end user using your software needs to have DNS caching because the DNS query load is large enough to be a problem or the RTT to the external DNS server is long enough to be a problem, they can install a caching DNS server such as Unbound on the same machine as your application, configured to cache responses and forward misses to the regular DNS resolvers.

Tool to convert java to c# code

Microsoft has a tool called JLCA: Java Language Conversion Assistant. I can't tell if it is better though, as I have never compared the two.

jQuery AJAX Call to PHP Script with JSON Return

Your datatype is wrong, change datatype for dataType.

Making a Simple Ajax call to controller in asp.net mvc

After the update you have done,

  1. its first calling the FirstAjax action with default HttpGet request and renders the blank Html view . (Earlier you were not having it)
  2. later on loading of DOM elements of that view your Ajax call get fired and displays alert.

Earlier you were only returning JSON to browser without rendering any HTML. Now it has a HTML view rendered where it can get your JSON Data.

You can't directly render JSON its plain data not HTML.

Force LF eol in git repo and working copy

To force LF line endings for all text files, you can create .gitattributes file in top-level of your repository with the following lines (change as desired):

# Ensure all C and PHP files use LF.
*.c         eol=lf
*.php       eol=lf

which ensures that all files that Git considers to be text files have normalized (LF) line endings in the repository (normally core.eol configuration controls which one do you have by default).

Based on the new attribute settings, any text files containing CRLFs should be normalized by Git. If this won't happen automatically, you can refresh a repository manually after changing line endings, so you can re-scan and commit the working directory by the following steps (given clean working directory):

$ echo "* text=auto" >> .gitattributes
$ rm .git/index     # Remove the index to force Git to
$ git reset         # re-scan the working directory
$ git status        # Show files that will be normalized
$ git add -u
$ git add .gitattributes
$ git commit -m "Introduce end-of-line normalization"

or as per GitHub docs:

git add . -u
git commit -m "Saving files before refreshing line endings"
git rm --cached -r . # Remove every file from Git's index.
git reset --hard # Rewrite the Git index to pick up all the new line endings.
git add . # Add all your changed files back, and prepare them for a commit.
git commit -m "Normalize all the line endings" # Commit the changes to your repository.

See also: @Charles Bailey post.

In addition, if you would like to exclude any files to not being treated as a text, unset their text attribute, e.g.

manual.pdf      -text

Or mark it explicitly as binary:

# Denote all files that are truly binary and should not be modified.
*.png binary
*.jpg binary

To see some more advanced git normalization file, check .gitattributes at Drupal core:

# Drupal git normalization
# @see https://www.kernel.org/pub/software/scm/git/docs/gitattributes.html
# @see https://www.drupal.org/node/1542048

# Normally these settings would be done with macro attributes for improved
# readability and easier maintenance. However macros can only be defined at the
# repository root directory. Drupal avoids making any assumptions about where it
# is installed.

# Define text file attributes.
# - Treat them as text.
# - Ensure no CRLF line-endings, neither on checkout nor on checkin.
# - Detect whitespace errors.
#   - Exposed by default in `git diff --color` on the CLI.
#   - Validate with `git diff --check`.
#   - Deny applying with `git apply --whitespace=error-all`.
#   - Fix automatically with `git apply --whitespace=fix`.

*.config  text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.css     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.dist    text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.engine  text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.html    text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=html
*.inc     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.install text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.js      text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.json    text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.lock    text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.map     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.md      text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.module  text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.php     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.po      text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.profile text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.script  text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.sh      text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.sql     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.svg     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.theme   text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.twig    text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.txt     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.xml     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.yml     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2

# Define binary file attributes.
# - Do not treat them as text.
# - Include binary diff in patches instead of "binary files differ."
*.eot     -text diff
*.exe     -text diff
*.gif     -text diff
*.gz      -text diff
*.ico     -text diff
*.jpeg    -text diff
*.jpg     -text diff
*.otf     -text diff
*.phar    -text diff
*.png     -text diff
*.svgz    -text diff
*.ttf     -text diff
*.woff    -text diff
*.woff2   -text diff

See also:

Get timezone from DateTime

DateTime does not know its timezone offset. There is no built-in method to return the offset or the timezone name (e.g. EAT, CEST, EST etc).

Like suggested by others, you can convert your date to UTC:

DateTime localtime = new DateTime.Now;
var utctime = localtime.ToUniversalTime();

and then only calculate the difference:

TimeSpan difference = localtime - utctime;

Also you may convert one time to another by using the DateTimeOffset:

DateTimeOffset targetTime = DateTimeOffset.Now.ToOffset(new TimeSpan(5, 30, 0));

But this is sort of lossy compression - the offset alone cannot tell you which time zone it is as two different countries may be in different time zones and have the same time only for part of the year (eg. South Africa and Europe). Also, be aware that summer daylight saving time may be introduced at different dates (EST vs CET - a 3-week difference).

You can get the name of your local system time zone using TimeZoneInfo class:

TimeZoneInfo localZone = TimeZoneInfo.Local;
localZone.IsDaylightSavingTime(localtime) ? localZone.DaylightName : localZone.StandardName

I agree with Gerrie Schenck, please read the article he suggested.

How to access a DOM element in React? What is the equilvalent of document.getElementById() in React

You can do that by specifying the ref

EDIT: In react v16.8.0 with function component, you can define a ref with useRef. Note that when you specify a ref on a function component, you need to use React.forwardRef on it to forward the ref to the DOM element of use useImperativeHandle to to expose certain functions from within the function component

Ex:

const Child1 = React.forwardRef((props, ref) => {
    return <div ref={ref}>Child1</div> 
});

const Child2 = React.forwardRef((props, ref) => {
    const handleClick= () =>{};
    useImperativeHandle(ref,() => ({
       handleClick
    }))
    return <div>Child2</div> 
});
const App = () => {
    const child1 = useRef(null);
    const child2 = useRef(null);

    return (
        <>
           <Child1 ref={child1} />
           <Child1 ref={child1} />
        </>
    )
}

EDIT:

In React 16.3+, use React.createRef() to create your ref:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  render() {
    return <div ref={this.myRef} />;
  }
}

In order to access the element, use:

const node = this.myRef.current;

DOC for using React.createRef()


EDIT

However facebook advises against it because string refs have some issues, are considered legacy, and are likely to be removed in one of the future releases.

From the docs:

Legacy API: String Refs

If you worked with React before, you might be familiar with an older API where the ref attribute is a string, like "textInput", and the DOM node is accessed as this.refs.textInput. We advise against it because string refs have some issues, are considered legacy, and are likely to be removed in one of the future releases. If you're currently using this.refs.textInput to access refs, we recommend the callback pattern instead.

A recommended way for React 16.2 and earlier is to use the callback pattern:

<Progressbar completed={25} id="Progress1" ref={(input) => {this.Progress[0] = input }}/>

<h2 class="center"></h2>

<Progressbar completed={50} id="Progress2" ref={(input) => {this.Progress[1] = input }}/>

  <h2 class="center"></h2>

<Progressbar completed={75} id="Progress3" ref={(input) => {this.Progress[2] = input }}/>

DOC for using callback


Even older versions of react defined refs using string like below

<Progressbar completed={25} id="Progress1" ref="Progress1"/>

    <h2 class="center"></h2>

    <Progressbar completed={50} id="Progress2" ref="Progress2"/>

      <h2 class="center"></h2>

    <Progressbar completed={75} id="Progress3" ref="Progress3"/>

In order to get the element just do

var object = this.refs.Progress1;

Remember to use this inside an arrow function block like:

print = () => {
  var object = this.refs.Progress1;  
}

and so on...

Quadratic and cubic regression in Excel

The LINEST function described in a previous answer is the way to go, but an easier way to show the 3 coefficients of the output is to additionally use the INDEX function. In one cell, type: =INDEX(LINEST(B2:B21,A2:A21^{1,2},TRUE,FALSE),1) (by the way, the B2:B21 and A2:A21 I used are just the same values the first poster who answered this used... of course you'd change these ranges appropriately to match your data). This gives the X^2 coefficient. In an adjacent cell, type the same formula again but change the final 1 to a 2... this gives the X^1 coefficient. Lastly, in the next cell over, again type the same formula but change the last number to a 3... this gives the constant. I did notice that the three coefficients are very close but not quite identical to those derived by using the graphical trendline feature under the charts tab. Also, I discovered that LINEST only seems to work if the X and Y data are in columns (not rows), with no empty cells within the range, so be aware of that if you get a #VALUE error.

Why is it that "No HTTP resource was found that matches the request URI" here?

Please check the class you inherited. Whether it is simply Controller or APIController.

By mistake we might create a controller from MVC 5 controller. It should be from Web API Controller.

How to get JavaScript variable value in PHP

If you want to use a js variable in a php script you MUST pass it within a HTTP request.

There are basically two ways:

  • Submitting or reloading the page (as per Chris answer).
  • Using AJAX, which is made exactly for communicating between a web page (js) and the server(php) without reloading/changing the page.

A basic example can be:

var profile_viewer_uid = 1;
$.ajax({
  url: "serverScript.php",
  method: "POST",
  data: { "profile_viewer_uid": profile_viewer_uid }
})

And in the serverScript.php file, you can do:

 $profile_viewer_uid = $_POST['profile_viewer_uid'];
 echo($profile_viewer_uid);
 // prints 1

Note: in this example I used jQuery AJAX, which is quicker to implement. You can do it in pure js as well.

SQL Server - Case Statement

I am looking for a way to create a select without repeating the conditional query.

I'm assuming that you don't want to repeat Foo-stuff+bar. You could put your calculation into a derived table:

SELECT CASE WHEN a.TestValue > 2 THEN a.TestValue ELSE 'Fail' END 
FROM (SELECT (Foo-stuff+bar) AS TestValue FROM MyTable) AS a

A common table expression would work just as well:

WITH a AS (SELECT (Foo-stuff+bar) AS TestValue FROM MyTable)
SELECT CASE WHEN a.TestValue > 2 THEN a.TestValue ELSE 'Fail' END    
FROM a

Also, each part of your switch should return the same datatype, so you may have to cast one or more cases.

convert string to number node.js

You do not have to install something.

parseInt(req.params.year, 10);

should work properly.

console.log(typeof parseInt(req.params.year)); // returns 'number'

What is your output, if you use parseInt? is it still a string?

Convert string to datetime

I used Time.parse("02/07/1988"), like some of the other posters.

An interesting gotcha was that Time was loaded by default when I opened up IRB, but Time.parse was not defined. I had to require 'time' to get it to work.

That's with Ruby 2.2.

Dart/Flutter : Converting timestamp

All of that above can work but for a quick and easy fix you can use the time_formatter package.

Using this package you can convert the epoch to human-readable time.

String convertTimeStamp(timeStamp){
//Pass the epoch server time and the it will format it for you 
   String formatted = formatTime(timeStamp).toString();
   return formatted;
}
//Then you can display it
Text(convertTimeStamp['createdTimeStamp'])//< 1 second : "Just now" up to < 730 days : "1 year"

Here you can check the format of the output that is going to be displayed: Formats

Git remote branch deleted, but still it appears in 'branch -a'

Try:

git remote prune origin

From the Git remote documentation:

prune

Deletes all stale remote-tracking branches under <name>. These stale branches have already been removed from the remote repository referenced by <name>, but are still locally available in "remotes/<name>".

With --dry-run option, report what branches will be pruned, but do not actually prune them.

How to add image in Flutter

I think the error is caused by the redundant ,

flutter:
  uses-material-design: true, # <<< redundant , at the end of the line
  assets:
    - images/lake.jpg

I'd also suggest to create an assets folder in the directory that contains the pubspec.yaml file and move images there and use

flutter:
  uses-material-design: true
  assets:
    - assets/images/lake.jpg

The assets directory will get some additional IDE support that you won't have if you put assets somewhere else.

How to access parent Iframe from JavaScript

Simply call window.frameElement from your framed page. If the page is not in a frame then frameElement will be null.

The other way (getting the window element inside a frame is less trivial) but for sake of completeness:

/**
 * @param f, iframe or frame element
 * @return Window object inside the given frame
 * @effect will append f to document.body if f not yet part of the DOM
 * @see Window.frameElement
 * @usage myFrame.document = getFramedWindow(myFrame).document;
 */
function getFramedWindow(f)
{
    if(f.parentNode == null)
        f = document.body.appendChild(f);
    var w = (f.contentWindow || f.contentDocument);
    if(w && w.nodeType && w.nodeType==9)
        w = (w.defaultView || w.parentWindow);
    return w;
}

error: ‘NULL’ was not declared in this scope

NULL isn't a keyword; it's a macro substitution for 0, and comes in stddef.h or cstddef, I believe. You haven't #included an appropriate header file, so g++ sees NULL as a regular variable name, and you haven't declared it.

Configure DataSource programmatically in Spring Boot

You can use DataSourceBuilder if you are using jdbc starter. Also, in order to override the default autoconfiguration bean you need to mark your bean as a @Primary

In my case I have properties starting with datasource.postgres prefix.

E.g

@ConfigurationProperties(prefix = "datasource.postgres")
@Bean
@Primary
public DataSource dataSource() {
    return DataSourceBuilder
        .create()
        .build();
}

If it is not feasible for you, then you can use

@Bean
@Primary
public DataSource dataSource() {
    return DataSourceBuilder
        .create()
        .username("")
        .password("")
        .url("")
        .driverClassName("")
        .build();
}

Regular Expression Match to test for a valid year

Use;

^(19|[2-9][0-9])\d{2}$ 

for years 1900 - 9999.

No need to worry for 9999 and onwards - A.I. will be doing all programming by then !!! Hehehehe

You can test your regex at https://regex101.com/

Also more info about non-capturing groups ( mentioned in one the comments above ) here http://www.manifold.net/doc/radian/why_do_non-capture_groups_exist_.htm

How do I center a window onscreen in C#?

In case of multi monitor and If you prefer to center on correct monitor/screen then you might like to try these lines:

// Save values for future(for example, to center a form on next launch)
int screen_x = Screen.FromControl(Form).WorkingArea.X;
int screen_y = Screen.FromControl(Form).WorkingArea.Y;

// Move it and center using correct screen/monitor
Form.Left = screen_x;
Form.Top = screen_y;
Form.Left += (Screen.FromControl(Form).WorkingArea.Width - Form.Width) / 2;
Form.Top += (Screen.FromControl(Form).WorkingArea.Height - Form.Height) / 2;

Reordering arrays

You could always use the sort method, if you don't know where the record is at present:

playlist.sort(function (a, b) {
    return a.artist == "Lalo Schifrin" 
               ? 1    // Move it down the list
               : 0;   // Keep it the same
});

TypeError: 'builtin_function_or_method' object is not subscriptable

Looks like you typed brackets instead of parenthesis by mistake.

How to fill 100% of remaining height?

Create a div, which contains both divs (full and someid) and set the height of that div to the following:

height: 100vh;

The height of the containing divs (full and someid) should be set to "auto". That's all.

What should a Multipart HTTP request with multiple files look like?

Well, note that the request contains binary data, so I'm not posting the request as such - instead, I've converted every non-printable-ascii character into a dot (".").

POST /cgi-bin/qtest HTTP/1.1
Host: aram
User-Agent: Mozilla/5.0 Gecko/2009042316 Firefox/3.0.10
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://aram/~martind/banner.htm
Content-Type: multipart/form-data; boundary=2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Length: 514

--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile1"; filename="r.gif"
Content-Type: image/gif

GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile2"; filename="g.gif"
Content-Type: image/gif

GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile3"; filename="b.gif"
Content-Type: image/gif

GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f--

Note that every line (including the last one) is terminated by a \r\n sequence.

Changing PowerShell's default output encoding to UTF-8

To be short, use:

write-output "your text" | out-file -append -encoding utf8 "filename"

Convert double to Int, rounded down

double myDouble = 420.5;
//Type cast double to int
int i = (int)myDouble;
System.out.println(i);

The double value is 420.5 and the application prints out the integer value of 420

How do I access command line arguments in Python?

If you call it like this: $ python myfile.py var1 var2 var3

import sys

var1 = sys.argv[1]
var2 = sys.argv[2]
var3 = sys.argv[3]

Similar to arrays you also have sys.argv[0] which is always the current working directory.

JSON post to Spring Controller

Convert your JSON object to JSON String using

JSON.stringify({"name":"testName"})

or manually. @RequestBody expecting json string instead of json object.

Note:stringify function having issue with some IE version, firefox it will work

verify the syntax of your ajax request for POST request. processData:false property is required in ajax request

$.ajax({ 
    url:urlName,
    type:"POST", 
    contentType: "application/json; charset=utf-8",
    data: jsonString, //Stringified Json Object
    async: false,    //Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation
    cache: false,    //This will force requested pages not to be cached by the browser  
     processData:false, //To avoid making query String instead of JSON
     success: function(resposeJsonObject){
        // Success Action
    }
});

Controller

@RequestMapping(value = urlPattern , method = RequestMethod.POST)

public @ResponseBody Test addNewWorker(@RequestBody Test jsonString) {

    //do business logic
    return test;
}

@RequestBody -Covert Json object to java

@ResponseBody - convert Java object to json

How to call a asp:Button OnClick event using JavaScript?

If you're open to using jQuery:

<script type="text/javascript">
 function fncsave()
 {
    $('#<%= savebtn.ClientID %>').click();
 }
</script>

Also, if you are using .NET 4 or better you can make the ClientIDMode == static and simplify the code:

<script type="text/javascript">
 function fncsave()
 {
    $("#savebtn").click();
 }
</script>

Reference: MSDN Article for Control.ClientIDMode

Decompile an APK, modify it and then recompile it

I know this question has been answered and I am not trying to give better answer here. I'll just share my experience in this topic.

Once I lost my code and I had the apk file only. I decompiled it using the tool below and it made my day.

These tools MUST be used in such situation, otherwise, it is unethical and even sometimes it is illegal, (stealing somebody else's effort). So please use it wisely.

Those are my favorite tools for doing that:

javadecompilers.com

and to get the apk from google play you can google it or check out those sites:

On the date of posting this answer I tested all the links and it worked perfect for me.

NOTE: Apk Decompiling is not effective in case of proguarded code. Because Proguard shrink and obfuscates the code and rename classes to nonsense names which make it fairly hard to understand the code.

Bonus:

Basic tutorial of Using Proguard:

HTML CSS Button Positioning

Use margins instead of line-height and then apply float to the buttons. By default they are displaying as inline-block, so when one is pushed down the hole line is pushed down with him. Float fixes this:

#header button {
    float:left;
}

Here's a working jsfidle.

How to write a large buffer into a binary file in C++, fast?

If you copy something from disk A to disk B in explorer, Windows employs DMA. That means for most of the copy process, the CPU will basically do nothing other than telling the disk controller where to put, and get data from, eliminating a whole step in the chain, and one that is not at all optimized for moving large amounts of data - and I mean hardware.

What you do involves the CPU a lot. I want to point you to the "Some calculations to fill a[]" part. Which I think is essential. You generate a[], then you copy from a[] to an output buffer (thats what fstream::write does), then you generate again, etc.

What to do? Multithreading! (I hope you have a multi-core processor)

  • fork.
  • Use one thread to generate a[] data
  • Use the other to write data from a[] to disk
  • You will need two arrays a1[] and a2[] and switch between them
  • You will need some sort of synchronization between your threads (semaphores, message queue, etc.)
  • Use lower level, unbuffered, functions, like the the WriteFile function mentioned by Mehrdad

Static variables in JavaScript

For private static variables, I found this way:

function Class()
{
}

Class.prototype = new function()
{
    _privateStatic = 1;
    this.get = function() { return _privateStatic; }
    this.inc = function() { _privateStatic++; }
};

var o1 = new Class();
var o2 = new Class();

o1.inc();

console.log(o1.get());
console.log(o2.get()); // 2

Set Date in a single line

Use the constructor Date(year,month,date) in Java 8 it is deprecated:

Date date = new Date(1990, 10, 26, 0, 0);

The best way is to use SimpleDateFormat

DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date date = format.parse("26/10/1985");

you need to import import java.text.SimpleDateFormat;

Python JSON encoding

So, simplejson.loads takes a json string and returns a data structure, which is why you are getting that type error there.

simplejson.dumps(data) comes back with

'[["apple", "cat"], ["banana", "dog"], ["pear", "fish"]]'

Which is a json array, which is what you want, since you gave this a python array.

If you want to get an "object" type syntax you would instead do

>>> data2 = {'apple':'cat', 'banana':'dog', 'pear':'fish'}
>>> simplejson.dumps(data2)
'{"pear": "fish", "apple": "cat", "banana": "dog"}'

which is javascript will come out as an object.

Hiding an Excel worksheet with VBA

This can be done in a single line, as long as the worksheet is active:

ActiveSheet.Visible = xlSheetHidden

However, you may not want to do this, especially if you use any "select" operations or you use any more ActiveSheet operations.

How to insert selected columns from a CSV file to a MySQL database using LOAD DATA INFILE

Load data into a table in MySQL and specify columns:

LOAD DATA LOCAL INFILE 'file.csv' INTO TABLE t1 
FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n'  
(@col1,@col2,@col3,@col4) set name=@col4,id=@col2 ;

@col1,2,3,4 are variables to hold the csv file columns (assume 4 ) name,id are table columns.

Get current application physical path within Application_Start

There's, however, slight difference among all these options which

I found out that

If you do

    string URL = Server.MapPath("~");

or

    string URL = Server.MapPath("/");

or

    string URL = HttpRuntime.AppDomainAppPath;

your URL will display resources in your link like this:

    "file:///d:/InetPUB/HOME/Index/bin/Resources/HandlerDoc.htm"

But if you want your URL to show only virtual path not the resources location, you should do

    string URL = HttpRuntime.AppDomainAppVirtualPath; 

then, your URL is displaying a virtual path to your resources as below

    "http://HOME/Index/bin/Resources/HandlerDoc.htm"        

using batch echo with special characters

The way to output > character is to prepend it with ^ escape character:

echo ^>

will print simply

>

git replace local version with remote version

I understand the question as this: you want to completely replace the contents of one file (or a selection) from upstream. You don't want to affect the index directly (so you would go through add + commit as usual).

Simply do

git checkout remote/branch -- a/file b/another/file

If you want to do this for extensive subtrees and instead wish to affect the index directly use

git read-tree remote/branch:subdir/

You can then (optionally) update your working copy by doing

git checkout-index -u --force

How to accept Date params in a GET request to Spring MVC Controller?

If you want to use a PathVariable, you can use an example method below (all methods are and do the same):

//You can consume the path .../users/added-since1/2019-04-25
@GetMapping("/users/added-since1/{since}")
public String userAddedSince1(@PathVariable("since") @DateTimeFormat(pattern = "yyyy-MM-dd") Date since) {
    return "Date: " + since.toString(); //The output is "Date: Thu Apr 25 00:00:00 COT 2019"
}

//You can consume the path .../users/added-since2/2019-04-25
@RequestMapping("/users/added-since2/{since}")
public String userAddedSince2(@PathVariable("since") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date since) {
    return "Date: " + since.toString(); //The output is "Date: Wed Apr 24 19:00:00 COT 2019"
}

//You can consume the path .../users/added-since3/2019-04-25
@RequestMapping("/users/added-since3/{since}")
public String userAddedSince3(@PathVariable("since") @DateTimeFormat(pattern = "yyyy-MM-dd") Date since) {
    return "Date: " + since.toString(); //The output is "Date: Thu Apr 25 00:00:00 COT 2019"
}

What causes "Unable to access jarfile" error?

Just came across the same problem trying to make a bad USB...

I tried to run this command in admin cmd

java -jar c:\fw\ducky\duckencode.jar -I c:\fw\ducky\HelloWorld.txt  -o c:\fw\ducky\inject.bin

But got this error:

Error: unable to access jarfile c:\fw\ducky\duckencode.jar

Solution

1st step

Right click the jarfile in question. Click properties. Click the unblock tab in bottom right corner. The file was blocked, because it was downloaded and not created on my PC.

2nd step

In the cmd I changed the directory to where the jar file is located.

cd C:\fw\ducky\

Then I typed dir and saw the file was named duckencode.jar.jar

So in cmd I changed the original command to reference the file with .jar.jar

java -jar c:\fw\ducky\duckencode.jar.jar -I c:\fw\ducky\HelloWorld.txt  -o c:\fw\ducky\inject.bin

That command executed without error messages and the inject.bin I was trying to create was now located in the directory.

Hope this helps.

JQuery: How to get selected radio button value?

$('input[name=myradiobutton]:radio:checked') will get you the selected radio button $('input[name=myradiobutton]:radio:not(:checked)') will get you the unselected radio buttons

Using this you can do this

$('input[name=myradiobutton]:radio:not(:checked)').val("0");

Update: After reading your Update I think I understand You will want to do something like this

var myRadioValue;

function radioValue(jqRadioButton){
  if (jqRadioButton.length) {
    myRadioValue = jqRadioButton.val();
  }
  else {
    myRadioValue = 0;
  }
}

$(document).ready(function () {
  $('input[name=myradiobutton]:radio').click(function () {   //Hook the click event for selected elements
    radioValue($('input[name=myradiobutton]:radio:checked'));
  });

  radioValue($('input[name=myradiobutton]:radio:checked')); //check for value on page load
});

How do you force a CIFS connection to unmount

I had this issue for a day until I found the real resolution. Instead of trying to force unmount an smb share that is hung, mount the share with the "soft" option. If a process attempts to connect to the share that is not available it will stop trying after a certain amount of time.

soft Make the mount soft. Fail file system calls after a number of seconds.

mount -t smbfs -o soft //username@server/share /users/username/smb/share

stat /users/username/smb/share/file
stat: /users/username/smb/share/file: stat: Operation timed out

May not be a real answer to your question but it is a solution to the problem

Capture iOS Simulator video for App Preview

For Xcode 8.2 or later

You can take videos and screenshots of Simulator using the xcrun simctl, a command-line utility to control the Simulator

  1. Run your app on the simulator

  2. Open a terminal

  3. Run the command

    • To take a screenshot

      xcrun simctl io booted screenshot <filename>.<file extension>

      For example:

      xcrun simctl io booted screenshot myScreenshot.png

    • To take a video

      xcrun simctl io booted recordVideo <filename>.<file extension>

      For example:

      xcrun simctl io booted recordVideo appVideo.mov

  4. Press ctrl + C to stop recording the video.

The default location for the created file is the current directory.

Xcode 11.2 and later gives extra options.

From Xcode 11.2 Beta Release Notes

simctl video recording now produces smaller video files, supports HEIC compression, and takes advantage of hardware encoding support where available. In addition, the ability to record video on iOS 13, tvOS 13, and watchOS 6 devices has been restored.

You could use additional flags:

xcrun simctl io --help
Set up a device IO operation.
Usage: simctl io <device> <operation> <arguments>

...

    recordVideo [--codec=<codec>] [--display=<display>] [--mask=<policy>] [--force] <file or url>
        Records the display to a QuickTime movie at the specified file or url.
        --codec      Specifies the codec type: "h264" or "hevc". Default is "hevc".

        --display    iOS: supports "internal" or "external". Default is "internal".
                     tvOS: supports only "external"
                     watchOS: supports only "internal"

        --mask       For non-rectangular displays, handle the mask by policy:
                     ignored: The mask is ignored and the unmasked framebuffer is saved.
                     alpha: Not supported, but retained for compatibility; the mask is rendered black.
                     black: The mask is rendered black.

        --force      Force the output file to be written to, even if the file already exists.

    screenshot [--type=<type>] [--display=<display>] [--mask=<policy>] <file or url>
        Saves a screenshot as a PNG to the specified file or url(use "-" for stdout).
        --type       Can be "png", "tiff", "bmp", "gif", "jpeg". Default is png.

        --display    iOS: supports "internal" or "external". Default is "internal".
                     tvOS: supports only "external"
                     watchOS: supports only "internal"

                     You may also specify a port by UUID
        --mask       For non-rectangular displays, handle the mask by policy:
                     ignored: The mask is ignored and the unmasked framebuffer is saved.
                     alpha: The mask is used as premultiplied alpha.
                     black: The mask is rendered black.

Now you can take a screenshot in jpeg, with mask (for non-rectangular displays) and some other flags:

xcrun simctl io booted screenshot --type=jpeg --mask=black screenshot.jpeg

Adding system header search path to Xcode

To use quotes just for completeness.

"/Users/my/work/a project with space"/**

If not recursive, remove the /**

Plot data in descending order as appears in data frame

You want reorder(). Here is an example with dummy data

set.seed(42)
df <- data.frame(Category = sample(LETTERS), Count = rpois(26, 6))

require("ggplot2")

p1 <- ggplot(df, aes(x = Category, y = Count)) +
         geom_bar(stat = "identity")

p2 <- ggplot(df, aes(x = reorder(Category, -Count), y = Count)) +
         geom_bar(stat = "identity")

require("gridExtra")
grid.arrange(arrangeGrob(p1, p2))

Giving:

enter image description here

Use reorder(Category, Count) to have Category ordered from low-high.

How to run a C# application at Windows startup?

Code is here (Win form app):

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;

namespace RunAtStartup
{
    public partial class frmStartup : Form
    {
        // The path to the key where Windows looks for startup applications
        RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);

        public frmStartup()
        {
            InitializeComponent();
            // Check to see the current state (running at startup or not)
            if (rkApp.GetValue("MyApp") == null)
            {
                // The value doesn't exist, the application is not set to run at startup
                chkRun.Checked = false;
            }
            else
            {
                // The value exists, the application is set to run at startup
                chkRun.Checked = true;
            }
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            if (chkRun.Checked)
            {
                // Add the value in the registry so that the application runs at startup
                rkApp.SetValue("MyApp", Application.ExecutablePath);
            }
            else
            {
                // Remove the value from the registry so that the application doesn't start
                rkApp.DeleteValue("MyApp", false);
            }
        }
    }
}

Shell script to set environment variables

Run the script as source= to run in debug mode as well.

source= ./myscript.sh

PHP Date Format to Month Name and Year

You could use:

echo date('F Y', strtotime('20130814'));

which should do the trick.

Edit: You have a date which is in a string format. To be able to format it nicelt, you first need to change it into a date itself - which is where strtotime comes in. It is a fantastic feature that converts almost any plausible expression of a date into a date itself. Then we can actually use the date() function to format the output into what you want.

How do I set the figure title and axes labels font size in Matplotlib?

To only modify the title's font (and not the font of the axis) I used this:

import matplotlib.pyplot as plt
fig = plt.Figure()
ax = fig.add_subplot(111)
ax.set_title('My Title', fontdict={'fontsize': 8, 'fontweight': 'medium'})

The fontdict accepts all kwargs from matplotlib.text.Text.

MySQL the right syntax to use near '' at line 1 error

INSERT INTO wp_bp_activity
            (
            user_id,
             component,
             `type`,
             `action`,
             content,
             primary_link,
             item_id,
             secondary_item_id,
             date_recorded,
             hide_sitewide,
             mptt_left,
             mptt_right
             )
             VALUES(
             1,'activity','activity_update','<a title="admin" href="http://brandnewmusicreleases.com/social-network/members/admin/">admin</a> posted an update','<a title="242925_1" href="http://brandnewmusicreleases.com/social-network/wp-content/uploads/242925_1.jpg" class="buddyboss-pics-picture-link">242925_1</a>','http://brandnewmusicreleases.com/social-network/members/admin/',' ',' ','2012-06-22 12:39:07',0,0,0
             )

How do you join tables from two different SQL Server instances in one SQL query

The best way I can think of to accomplish this is via sp_addlinkedserver. You need to make sure that whatever account you use to add the link (via sp_addlinkedsrvlogin) has permissions to the table you're joining, but then once the link is established, you can call the server by name, i.e.:

SELECT *
FROM server1table
    INNER JOIN server2.database.dbo.server2table ON .....

How to set image to fit width of the page using jsPDF?

i faced same problem but i solve using this code

html2canvas(body,{
                onrendered:function(canvas){
                    var pdf=new jsPDF("p", "mm", "a4");
                    var width = pdf.internal.pageSize.getWidth();    
                    var height = pdf.internal.pageSize.getHeight();
                    pdf.addImage(canvas, 'JPEG', 0, 0,width,height);
                    pdf.save('test11.pdf');
                }
            }) 

VBA array sort function?

You didn't want an Excel-based solution but since I had the same problem today and wanted to test using other Office Applications functions I wrote the function below.

Limitations:

  • 2-dimensional arrays;
  • maximum of 3 columns as sort keys;
  • depends on Excel;

Tested calling Excel 2010 from Visio 2010


Option Base 1


Private Function sort_array_2D_excel(array_2D, array_sortkeys, Optional array_sortorders, Optional tag_header As String = "Guess", Optional tag_matchcase As String = "False")

'   Dependencies: Excel; Tools > References > Microsoft Excel [Version] Object Library

    Dim excel_application As Excel.Application
    Dim excel_workbook As Excel.Workbook
    Dim excel_worksheet As Excel.Worksheet

    Set excel_application = CreateObject("Excel.Application")

    excel_application.Visible = True
    excel_application.ScreenUpdating = False
    excel_application.WindowState = xlNormal

    Set excel_workbook = excel_application.Workbooks.Add
    excel_workbook.Activate

    Set excel_worksheet = excel_workbook.Worksheets.Add
    excel_worksheet.Activate
    excel_worksheet.Visible = xlSheetVisible

    Dim excel_range As Excel.Range
    Set excel_range = excel_worksheet.Range("A1").Resize(UBound(array_2D, 1) - LBound(array_2D, 1) + 1, UBound(array_2D, 2) - LBound(array_2D, 2) + 1)
    excel_range = array_2D


    For i_sortkey = LBound(array_sortkeys) To UBound(array_sortkeys)

        If IsNumeric(array_sortkeys(i_sortkey)) Then
            sortkey_range = Chr(array_sortkeys(i_sortkey) + 65 - 1) & "1"
            Set array_sortkeys(i_sortkey) = excel_worksheet.Range(sortkey_range)

        Else
            MsgBox "Error in sortkey parameter:" & vbLf & "array_sortkeys(" & i_sortkey & ") = " & array_sortkeys(i_sortkey) & vbLf & "Terminating..."
            End

        End If

    Next i_sortkey


    For i_sortorder = LBound(array_sortorders) To UBound(array_sortorders)
        Select Case LCase(array_sortorders(i_sortorder))
            Case "asc"
                array_sortorders(i_sortorder) = XlSortOrder.xlAscending
            Case "desc"
                array_sortorders(i_sortorder) = XlSortOrder.xlDescending
            Case Else
                array_sortorders(i_sortorder) = XlSortOrder.xlAscending
        End Select
    Next i_sortorder

    Select Case LCase(tag_header)
        Case "yes"
            tag_header = Excel.xlYes
        Case "no"
            tag_header = Excel.xlNo
        Case "guess"
            tag_header = Excel.xlGuess
        Case Else
            tag_header = Excel.xlGuess
    End Select

    Select Case LCase(tag_matchcase)
        Case "true"
            tag_matchcase = True
        Case "false"
            tag_matchcase = False
        Case Else
            tag_matchcase = False
    End Select


    Select Case (UBound(array_sortkeys) - LBound(array_sortkeys) + 1)
        Case 1
            Call excel_range.Sort(Key1:=array_sortkeys(1), Order1:=array_sortorders(1), Header:=tag_header, MatchCase:=tag_matchcase)
        Case 2
            Call excel_range.Sort(Key1:=array_sortkeys(1), Order1:=array_sortorders(1), Key2:=array_sortkeys(2), Order2:=array_sortorders(2), Header:=tag_header, MatchCase:=tag_matchcase)
        Case 3
            Call excel_range.Sort(Key1:=array_sortkeys(1), Order1:=array_sortorders(1), Key2:=array_sortkeys(2), Order2:=array_sortorders(2), Key3:=array_sortkeys(3), Order3:=array_sortorders(3), Header:=tag_header, MatchCase:=tag_matchcase)
        Case Else
            MsgBox "Error in sortkey parameter:" & vbLf & "Maximum number of sort columns is 3!" & vbLf & "Currently passed: " & (UBound(array_sortkeys) - LBound(array_sortkeys) + 1)
            End
    End Select


    For i_row = 1 To excel_range.Rows.Count

        For i_column = 1 To excel_range.Columns.Count

            array_2D(i_row, i_column) = excel_range(i_row, i_column)

        Next i_column

    Next i_row


    excel_workbook.Close False
    excel_application.Quit

    Set excel_worksheet = Nothing
    Set excel_workbook = Nothing
    Set excel_application = Nothing


    sort_array_2D_excel = array_2D


End Function

This is an example on how to test the function:

Private Sub test_sort()

    array_unsorted = dim_sort_array()

    Call msgbox_array(array_unsorted)

    array_sorted = sort_array_2D_excel(array_unsorted, Array(2, 1, 3), Array("desc", "", "asdas"), "yes", "False")

    Call msgbox_array(array_sorted)

End Sub


Private Function dim_sort_array()

    Dim array_unsorted(1 To 5, 1 To 3) As String

    i_row = 0

    i_row = i_row + 1
    array_unsorted(i_row, 1) = "Column1": array_unsorted(i_row, 2) = "Column2": array_unsorted(i_row, 3) = "Column3"

    i_row = i_row + 1
    array_unsorted(i_row, 1) = "OR": array_unsorted(i_row, 2) = "A": array_unsorted(i_row, 3) = array_unsorted(i_row, 1) & "_" & array_unsorted(i_row, 2)

    i_row = i_row + 1
    array_unsorted(i_row, 1) = "XOR": array_unsorted(i_row, 2) = "A": array_unsorted(i_row, 3) = array_unsorted(i_row, 1) & "_" & array_unsorted(i_row, 2)

    i_row = i_row + 1
    array_unsorted(i_row, 1) = "NOT": array_unsorted(i_row, 2) = "B": array_unsorted(i_row, 3) = array_unsorted(i_row, 1) & "_" & array_unsorted(i_row, 2)

    i_row = i_row + 1
    array_unsorted(i_row, 1) = "AND": array_unsorted(i_row, 2) = "A": array_unsorted(i_row, 3) = array_unsorted(i_row, 1) & "_" & array_unsorted(i_row, 2)

    dim_sort_array = array_unsorted

End Function


Sub msgbox_array(array_2D, Optional string_info As String = "2D array content:")

    msgbox_string = string_info & vbLf

    For i_row = LBound(array_2D, 1) To UBound(array_2D, 1)

        msgbox_string = msgbox_string & vbLf & i_row & vbTab

        For i_column = LBound(array_2D, 2) To UBound(array_2D, 2)

            msgbox_string = msgbox_string & array_2D(i_row, i_column) & vbTab

        Next i_column

    Next i_row

    MsgBox msgbox_string

End Sub

If anybody tests this using other versions of office please post here if there are any problems.

detect back button click in browser

I'm assuming that you're trying to deal with Ajax navigation and not trying to prevent your users from using the back button, which violates just about every tenet of UI development ever.

Here's some possible solutions: JQuery History Salajax A Better Ajax Back Button

How to set specific window (frame) size in java swing?

Try this, but you can adjust frame size with bounds and edit title.

package co.form.Try;

import javax.swing.JFrame;

public class Form {

    public static void main(String[] args) {
        JFrame obj =new JFrame();
        obj.setBounds(10,10,700,600); 
        obj.setTitle("Application Form");
        obj.setResizable(false);                
        obj.setVisible(true);       
        obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

}

Python String and Integer concatenation

I did something else. I wanted to replace a word, in lists off lists, that contained phrases. I wanted to replace that sttring / word with a new word that will be a join between string and number, and that number / digit will indicate the position of the phrase / sublist / lists of lists.

That is, I replaced a string with a string and an incremental number that follow it.

    myoldlist_1=[[' myoldword'],[''],['tttt myoldword'],['jjjj ddmyoldwordd']]
        No_ofposition=[]
        mynewlist_2=[]
        for i in xrange(0,4,1):
            mynewlist_2.append([x.replace('myoldword', "%s" % i+"_mynewword") for x in myoldlist_1[i]])
            if len(mynewlist_2[i])>0:
                No_ofposition.append(i)
mynewlist_2
No_ofposition

QString to char* conversion

David's answer works fine if you're only using it for outputting to a file or displaying on the screen, but if a function or library requires a char* for parsing, then this method works best:

// copy QString to char*
QString filename = "C:\dev\file.xml";
char* cstr;
string fname = filename.toStdString();
cstr = new char [fname.size()+1];
strcpy( cstr, fname.c_str() );

// function that requires a char* parameter
parseXML(cstr);

Best way to repeat a character in C#

Extension methods:

public static string Repeat(this string s, int n)
{
    return new String(Enumerable.Range(0, n).SelectMany(x => s).ToArray());
}

public static string Repeat(this char c, int n)
{
    return new String(c, n);
}

Is there a way to @Autowire a bean that requires constructor arguments?

Another alternative, if you already have an instance of the object created and you want to add it as an @autowired dependency to initialize all the internal @autowired variables, could be the following:

@Autowired 
private AutowireCapableBeanFactory autowireCapableBeanFactory;

public void doStuff() {
   YourObject obj = new YourObject("Value X", "etc");
   autowireCapableBeanFactory.autowireBean(obj);
}

How to add background-image using ngStyle (angular2)?

You can use 2 methods:

Method 1

<div [ngStyle]="{'background-image': 'url(&quot;' + photo + '&quot;)'}"></div>

Method 2

<div [style.background-image]="'url(&quot;' + photo + '&quot;)'"></div>

Note: it is important to surround the URL with " char.

How to read from a text file using VBScript?

Dim obj : Set obj = CreateObject("Scripting.FileSystemObject")
Dim outFile : Set outFile = obj.CreateTextFile("in.txt")
Dim inFile: Set inFile = obj.OpenTextFile("out.txt")

' Read file
Dim strRetVal : strRetVal = inFile.ReadAll
inFile.Close

' Write file
outFile.write (strRetVal)
outFile.Close

How do you cast a List of supertypes to a List of subtypes?

When you cast an object reference you are just casting the type of the reference, not the type of the object. casting won't change the actual type of the object.

Java doesn't have implicit rules for converting Object types. (Unlike primitives)

Instead you need to provide how to convert one type to another and call it manually.

public class TestA {}
public class TestB extends TestA{ 
    TestB(TestA testA) {
        // build a TestB from a TestA
    }
}

List<TestA> result = .... 
List<TestB> data = new List<TestB>();
for(TestA testA : result) {
   data.add(new TestB(testA));
}

This is more verbose than in a language with direct support, but it works and you shouldn't need to do this very often.

Why do we usually use || over |? What is the difference?

The only time you would use | or & instead of || or && is when you have very simple boolean expressions and the cost of short cutting (i.e. a branch) is greater than the time you save by not evaluating the later expressions.

However, this is a micro-optimisation which rarely matters except in the most low level code.

how to toggle attr() in jquery

For readonly/disabled and other attributes with true/false values

$(':submit').attr('disabled', function(_, attr){ return !attr});

SHA-256 or MD5 for file integrity

It is technically approved that MD5 is faster than SHA256 so in just verifying file integrity it will be sufficient and better for performance.

You are able to checkout the following resources:

tslint / codelyzer / ng lint error: "for (... in ...) statements must be filtered with an if statement"

If the behavior of for(... in ...) is acceptable/necessary for your purposes, you can tell tslint to allow it.

in tslint.json, add this to the "rules" section.

"forin": false

Otherwise, @Maxxx has the right idea with

for (const field of Object.keys(this.formErrors)) {

Triggering a checkbox value changed event in DataGridView

Small update.... Make sure you use EditedFormattedValue instead of value as I tried value but it never give right status that is checked/unchecked most of the site still use value but as used in latest c# 2010 express below is one way to access..

grdJobDetails.Rows[e.RowIndex].Cells[0].EditedFormattedValue

Also _CellValueChanged event suggested or used by few must be usable for some cases but if you are looking for every check/uncheck of cell make sure you use _CellContentClick else per my notice I see not every time _CellValueChanged is fired.. that is if the same checkbox is clicked over & over again it does not fire _CellValueChanged but if you click alternately for example you have two chekbox & click one after other _CellValueChanged event will be fired but usually if looking for event to fire everytime the any cell is check/uncheck _CellValueChanged is not fired.

javascript date to string

Maybe it is easier to convert the Date into the actual integer 20110506105524 and then convert this into a string:

function printDate() {
    var temp = new Date();
    var dateInt =
        ((((temp.getFullYear() * 100 + 
            temp.getMonth() + 1) * 100 + 
           temp.getDate()) * 100 +
          temp.getHours()) * 100 + 
         temp.getMinutes()) * 100 + 
        temp.getSeconds();

    debug ( '' + dateInt );  // convert to String
}

When temp.getFullYear() < 1000 the result will be one (or more) digits shorter.

Caution: this wont work with millisecond precision (i.e. 17 digits) since Number.MAX_SAFE_INTEGER is 9007199254740991 which is only 16 digits.

Is there a way to get element by XPath using JavaScript in Selenium WebDriver?

**Different way to Find Element:**

IEDriver.findElement(By.id("id"));
IEDriver.findElement(By.linkText("linkText"));
IEDriver.findElement(By.xpath("xpath"));

IEDriver.findElement(By.xpath(".//*[@id='id']"));
IEDriver.findElement(By.xpath("//button[contains(.,'button name')]"));
IEDriver.findElement(By.xpath("//a[contains(.,'text name')]"));
IEDriver.findElement(By.xpath("//label[contains(.,'label name')]"));

IEDriver.findElement(By.xpath("//*[contains(text(), 'your text')]");

Check Case Sensitive:
IEDriver.findElement(By.xpath("//*[contains(lower-case(text()),'your text')]");

For exact match: 
IEDriver.findElement(By.xpath("//button[text()='your text']");

**Find NG-Element:**

Xpath == //td[contains(@ng-show,'childsegment.AddLocation')]
CssSelector == .sprite.icon-cancel

error: member access into incomplete type : forward declaration of

You must have the definition of class B before you use the class. How else would the compiler otherwise know that there exists such a function as B::add?

Either define class B before class A, or move the body of A::doSomething to after class B have been defined, like

class B;

class A
{
    B* b;

    void doSomething();
};

class B
{
    A* a;

    void add() {}
};

void A::doSomething()
{
    b->add();
}

What is the reason for the error message "System cannot find the path specified"?

The following worked for me:

  1. Open the Registry Editor (press windows key, type regedit and hit Enter) .
  2. Navigate to HKEY_CURRENT_USER\Software\Microsoft\Command Processor\AutoRun and clear the values.
  3. Also check HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\AutoRun.

Vertically align an image inside a div with responsive height

Here's a technique that allows you to center ANY content both vertically and horizontally!

Basically, you just need a two containers and make sure your elements meet the following criteria.

The outher container :

  • should have display: table;

The inner container :

  • should have display: table-cell;
  • should have vertical-align: middle;
  • should have text-align: center;

The content box :

  • should have display: inline-block;

If you use this technique, just add your image (along with any other content you want to go with it) to the content box.

Demo :

_x000D_
_x000D_
body {_x000D_
    margin : 0;_x000D_
}_x000D_
_x000D_
.outer-container {_x000D_
    position : absolute;_x000D_
    display: table;_x000D_
    width: 100%;_x000D_
    height: 100%;_x000D_
    background: #ccc;_x000D_
}_x000D_
_x000D_
.inner-container {_x000D_
    display: table-cell;_x000D_
    vertical-align: middle;_x000D_
    text-align: center;_x000D_
}_x000D_
_x000D_
.centered-content {_x000D_
    display: inline-block;_x000D_
    background: #fff;_x000D_
    padding : 12px;_x000D_
    border : 1px solid #000;_x000D_
}_x000D_
_x000D_
img {_x000D_
   max-width : 120px;_x000D_
}
_x000D_
<div class="outer-container">_x000D_
   <div class="inner-container">_x000D_
     <div class="centered-content">_x000D_
        <img src="https://i.stack.imgur.com/mRsBv.png" />_x000D_
     </div>_x000D_
   </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

See also this Fiddle!

Declare and initialize a Dictionary in Typescript

I agree with thomaux that the initialization type checking error is a TypeScript bug. However, I still wanted to find a way to declare and initialize a Dictionary in a single statement with correct type checking. This implementation is longer, however it adds additional functionality such as a containsKey(key: string) and remove(key: string) method. I suspect that this could be simplified once generics are available in the 0.9 release.

First we declare the base Dictionary class and Interface. The interface is required for the indexer because classes cannot implement them.

interface IDictionary {
    add(key: string, value: any): void;
    remove(key: string): void;
    containsKey(key: string): bool;
    keys(): string[];
    values(): any[];
}

class Dictionary {

    _keys: string[] = new string[];
    _values: any[] = new any[];

    constructor(init: { key: string; value: any; }[]) {

        for (var x = 0; x < init.length; x++) {
            this[init[x].key] = init[x].value;
            this._keys.push(init[x].key);
            this._values.push(init[x].value);
        }
    }

    add(key: string, value: any) {
        this[key] = value;
        this._keys.push(key);
        this._values.push(value);
    }

    remove(key: string) {
        var index = this._keys.indexOf(key, 0);
        this._keys.splice(index, 1);
        this._values.splice(index, 1);

        delete this[key];
    }

    keys(): string[] {
        return this._keys;
    }

    values(): any[] {
        return this._values;
    }

    containsKey(key: string) {
        if (typeof this[key] === "undefined") {
            return false;
        }

        return true;
    }

    toLookup(): IDictionary {
        return this;
    }
}

Now we declare the Person specific type and Dictionary/Dictionary interface. In the PersonDictionary note how we override values() and toLookup() to return the correct types.

interface IPerson {
    firstName: string;
    lastName: string;
}

interface IPersonDictionary extends IDictionary {
    [index: string]: IPerson;
    values(): IPerson[];
}

class PersonDictionary extends Dictionary {
    constructor(init: { key: string; value: IPerson; }[]) {
        super(init);
    }

    values(): IPerson[]{
        return this._values;
    }

    toLookup(): IPersonDictionary {
        return this;
    }
}

And here is a simple initialization and usage example:

var persons = new PersonDictionary([
    { key: "p1", value: { firstName: "F1", lastName: "L2" } },
    { key: "p2", value: { firstName: "F2", lastName: "L2" } },
    { key: "p3", value: { firstName: "F3", lastName: "L3" } }
]).toLookup();


alert(persons["p1"].firstName + " " + persons["p1"].lastName);
// alert: F1 L2

persons.remove("p2");

if (!persons.containsKey("p2")) {
    alert("Key no longer exists");
    // alert: Key no longer exists
}

alert(persons.keys().join(", "));
// alert: p1, p3

How do I set the default schema for a user in MySQL

If your user has a local folder e.g. Linux, in your users home folder you could create a .my.cnf file and provide the credentials to access the server there. for example:-

[client]
host=localhost
user=yourusername
password=yourpassword or exclude to force entry
database=mygotodb

Mysql would then open this file for each user account read the credentials and open the selected database.

Not sure on Windows, I upgraded from Windows because I needed the whole house not just the windows (aka Linux) a while back.

sed edit file in place

The -i option streams the edited content into a new file and then renames it behind the scenes, anyway.

Example:

sed -i 's/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g' filename

and

sed -i '' 's/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g' filename

on macOS.

AngularJs ReferenceError: angular is not defined

You should put the include angular line first, before including any other js file

Can I change the checkbox size using CSS?

My understanding is that this isn't easy at all to do cross-browser. Instead of trying to manipulate the checkbox control, you could always build your own implementation using images, javascript, and hidden input fields. I'm assuming this is similar to what niceforms is (from Staicu lonut's answer above), but wouldn't be particularly difficult to implement. I believe jQuery has a plugin to allow for this custom behavior as well (will look for the link and post here if I can find it).

Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\

mysqli_select_db() should have 2 parameters, the connection link and the database name -

mysqli_select_db($con, 'phpcadet') or die(mysqli_error($con));

Using mysqli_error in the die statement will tell you exactly what is wrong as opposed to a generic error message.

Add one year in current date PYTHON

This is what I do when I need to add months or years and don't want to import more libraries. Just create a datetime.date() object, call add_month(date) to add a month and add_year(date) to add a year.

import datetime
__author__ = 'Daniel Margarido'


# Check if the int given year is a leap year
# return true if leap year or false otherwise
def is_leap_year(year):
    if (year % 4) == 0:
        if (year % 100) == 0:
            if (year % 400) == 0:
                return True
            else:
                return False
        else:
            return True
    else:
        return False


THIRTY_DAYS_MONTHS = [4, 6, 9, 11]
THIRTYONE_DAYS_MONTHS = [1, 3, 5, 7, 8, 10, 12]

# Inputs -> month, year Booth integers
# Return the number of days of the given month
def get_month_days(month, year):
    if month in THIRTY_DAYS_MONTHS:   # April, June, September, November
        return 30
    elif month in THIRTYONE_DAYS_MONTHS:   # January, March, May, July, August, October, December
        return 31
    else:   # February
        if is_leap_year(year):
            return 29
        else:
            return 28

# Checks the month of the given date
# Selects the number of days it needs to add one month
# return the date with one month added
def add_month(date):
    current_month_days = get_month_days(date.month, date.year)
    next_month_days = get_month_days(date.month + 1, date.year)

    delta = datetime.timedelta(days=current_month_days)
    if date.day > next_month_days:
        delta = delta - datetime.timedelta(days=(date.day - next_month_days) - 1)

    return date + delta


def add_year(date):
    if is_leap_year(date.year):
        delta = datetime.timedelta(days=366)
    else:
        delta = datetime.timedelta(days=365)

    return date + delta


# Validates if the expected_value is equal to the given value
def test_equal(expected_value, value):
    if expected_value == value:
        print "Test Passed"
        return True

    print "Test Failed : " + str(expected_value) + " is not equal to " str(value)
    return False

# Test leap year
print "---------- Test leap year ----------"
test_equal(True, is_leap_year(2012))
test_equal(True, is_leap_year(2000))
test_equal(False, is_leap_year(1900))
test_equal(False, is_leap_year(2002))
test_equal(False, is_leap_year(2100))
test_equal(True, is_leap_year(2400))
test_equal(True, is_leap_year(2016))

# Test add month
print "---------- Test add month ----------"
test_equal(datetime.date(2016, 2, 1), add_month(datetime.date(2016, 1, 1)))
test_equal(datetime.date(2016, 6, 16), add_month(datetime.date(2016, 5, 16)))
test_equal(datetime.date(2016, 3, 15), add_month(datetime.date(2016, 2, 15)))
test_equal(datetime.date(2017, 1, 12), add_month(datetime.date(2016, 12, 12)))
test_equal(datetime.date(2016, 3, 1), add_month(datetime.date(2016, 1, 31)))
test_equal(datetime.date(2015, 3, 1), add_month(datetime.date(2015, 1, 31)))
test_equal(datetime.date(2016, 3, 1), add_month(datetime.date(2016, 1, 30)))
test_equal(datetime.date(2016, 4, 30), add_month(datetime.date(2016, 3, 30)))
test_equal(datetime.date(2016, 5, 1), add_month(datetime.date(2016, 3, 31)))

# Test add year
print "---------- Test add year ----------"
test_equal(datetime.date(2016, 2, 2), add_year(datetime.date(2015, 2, 2)))
test_equal(datetime.date(2001, 2, 2), add_year(datetime.date(2000, 2, 2)))
test_equal(datetime.date(2100, 2, 2), add_year(datetime.date(2099, 2, 2)))
test_equal(datetime.date(2101, 2, 2), add_year(datetime.date(2100, 2, 2)))
test_equal(datetime.date(2401, 2, 2), add_year(datetime.date(2400, 2, 2)))

Fastest way to check if string contains only digits

Probably the fastest way is:

myString.All(c => char.IsDigit(c))

Note: it will return True in case your string is empty which is incorrect (if you not considering empty as valid number/digit )

Spark specify multiple column conditions for dataframe join

In Pyspark, using parenthesis around each condition is the key to using multiple column names in the join condition.

joined_df = df1.join(df2, 
    (df1['name'] == df2['name']) &
    (df1['phone'] == df2['phone'])
)

Access to the path is denied

You can try to check if your web properties for the project didn't switch to IIS Express and change it back to IIS Local

How to clear the interpreter console?

Wiper is cool, good thing about it is I don't have to type '()' around it. Here is slight variation to it

# wiper.py
import os
class Cls(object):
    def __repr__(self):
        os.system('cls')
        return ''

The usage is quite simple:

>>> cls = Cls()
>>> cls # this will clear console.

android studio 0.4.2: Gradle project sync failed error

I had the same error. I deleted the android repository from android sdk manager and reinstalled it. It worked.

How do I keep the screen on in my App?

There are multiple ways you can do it:

Solution 1:

class MainActivity extends AppCompactActivity {
    @Override
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);    
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }
}

Solution 2:

In activity_main.xml file, simply add:

<android:KeepScreenOn="true"/>

My advice: please don't use WakeLock. If you use it, you have to define extra permission, and mostly this thing is useful in CPU's development environment.

Also, make sure to turn off the screen while closing the activity. You can do it in this way:

public void onDestry() {
    getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}

Emulate/Simulate iOS in Linux

As far as I know, there is no such a thing as iOS emulator on windows or linux, there are only some gameengines that enable you to compile same code for both iOS and windows or linux and there is a toolchain to compile iOS application using linux. none of them are realy emulator/simulator things. and to use that toolchain you need a jailbreaked iOS device to test binary file created using toolchain. I mean linux itself can't run the binary created itself. and by the way even in mac simulator is just an intermediate program which runs mac-compiled binary, since if you change compiling for iOS from simulator or the other way, all the files are rebuild. and also there are some real differences, like iOS is a case-sensitive operation while simulator is not.

so the best solution is to buy an iOS device yourself.

Bi-directional Map in Java?

Use Google's BiMap

It is more convenient.

Is Unit Testing worth the effort?

When you said, "our code base does not lend itself to easy testing" is the first sign of a code smell. Writing Unit Tests means you typically write code differently in order to make the code more testable. This is a good thing in my opinion as what I've seen over the years in writing code that I had to write tests for, it forced me to put forth a better design.

Remove a character at a certain position in a string - javascript

var str = 'Hello World',
    i = 3,
    result = str.substr(0, i-1)+str.substring(i);

alert(result);

Value of i should not be less then 1.

How can I set a cookie in react?

It appears that the functionality previously present in the react-cookie npm package has been moved to universal-cookie. The relevant example from the universal-cookie repository now is:

import Cookies from 'universal-cookie';
const cookies = new Cookies();
cookies.set('myCat', 'Pacman', { path: '/' });
console.log(cookies.get('myCat')); // Pacman

What's the advantage of a Java enum versus a class with public static final fields?

The biggest advantage is enum Singletons are easy to write and thread-safe :

public enum EasySingleton{
    INSTANCE;
}

and

/**
* Singleton pattern example with Double checked Locking
*/
public class DoubleCheckedLockingSingleton{
     private volatile DoubleCheckedLockingSingleton INSTANCE;

     private DoubleCheckedLockingSingleton(){}

     public DoubleCheckedLockingSingleton getInstance(){
         if(INSTANCE == null){
            synchronized(DoubleCheckedLockingSingleton.class){
                //double checking Singleton instance
                if(INSTANCE == null){
                    INSTANCE = new DoubleCheckedLockingSingleton();
                }
            }
         }
         return INSTANCE;
     }
}

both are similar and it handled Serialization by themselves by implementing

//readResolve to prevent another instance of Singleton
    private Object readResolve(){
        return INSTANCE;
    }

more

How to customise the Jackson JSON mapper implicitly used by Spring Boot?

spring.jackson.serialization-inclusion=non_null used to work for us

But when we upgraded spring boot version to 1.4.2.RELEASE or higher, it stopped working.

Now, another property spring.jackson.default-property-inclusion=non_null is doing the magic.

in fact, serialization-inclusion is deprecated. This is what my intellij throws at me.

Deprecated: ObjectMapper.setSerializationInclusion was deprecated in Jackson 2.7

So, start using spring.jackson.default-property-inclusion=non_null instead

Send POST request using NSURLSession

Motivation

Sometimes I have been getting some errors when you want to pass httpBody serialized to Data from Dictionary, which on most cases is due to the wrong encoding or malformed data due to non NSCoding conforming objects in the Dictionary.

Solution

Depending on your requirements one easy solution would be to create a String instead of Dictionary and convert it to Data. You have the code samples below written on Objective-C and Swift 3.0.

Objective-C

// Create the URLSession on the default configuration
NSURLSessionConfiguration *defaultSessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultSessionConfiguration];

// Setup the request with URL
NSURL *url = [NSURL URLWithString:@"yourURL"];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];

// Convert POST string parameters to data using UTF8 Encoding
NSString *postParams = @"api_key=APIKEY&[email protected]&password=password";
NSData *postData = [postParams dataUsingEncoding:NSUTF8StringEncoding];

// Convert POST string parameters to data using UTF8 Encoding
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:postData];

// Create dataTask
NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    // Handle your response here
}];

// Fire the request
[dataTask resume];

Swift

// Create the URLSession on the default configuration
let defaultSessionConfiguration = URLSessionConfiguration.default
let defaultSession = URLSession(configuration: defaultSessionConfiguration)

// Setup the request with URL
let url = URL(string: "yourURL")
var urlRequest = URLRequest(url: url!)  // Note: This is a demo, that's why I use implicitly unwrapped optional

// Convert POST string parameters to data using UTF8 Encoding
let postParams = "api_key=APIKEY&[email protected]&password=password"
let postData = postParams.data(using: .utf8)

// Set the httpMethod and assign httpBody
urlRequest.httpMethod = "POST"
urlRequest.httpBody = postData

// Create dataTask
let dataTask = defaultSession.dataTask(with: urlRequest) { (data, response, error) in
    // Handle your response here
}

// Fire the request
dataTask.resume()

Hot deploy on JBoss - how do I make JBoss "see" the change?

Unfortunately, it's not that easy. There are more complicated things behind the scenes in JBoss (most of them ClassLoader related) that will prevent you from HOT-DEPLOYING your application.

For example, you are not going to be able to HOT-DEPLOY if some of your classes signatures change.

So far, using MyEclipse IDE (a paid distribution of Eclipse) is the only thing I found that does hot deploying quite successfully. Not 100% accuracy though. But certainly better than JBoss Tools, Netbeans or any other Eclipse based solution.

I've been looking for free tools to accomplish what you've just described by asking people in StackOverflow if you want to take a look.

MessageBodyWriter not found for media type=application/json

Ensure that you have following JARS in place: 1) jackson-core-asl-1.9.13 2) jackson-jaxrs-1.9.13 3) jackson-mapper-asl-1.9.13 4) jackson-xc-1.9.13

Inheritance with base class constructor with parameters

I could be wrong, but I believe since you are inheriting from foo, you have to call a base constructor. Since you explicitly defined the foo constructor to require (int, int) now you need to pass that up the chain.

public bar(int a, int b) : base(a, b)
{
     c = a * b;
}

This will initialize foo's variables first and then you can use them in bar. Also, to avoid confusion I would recommend not naming parameters the exact same as the instance variables. Try p_a or something instead, so you won't accidentally be handling the wrong variable.

Copy / Put text on the clipboard with FireFox, Safari and Chrome

Use document.execCommand('copy'). Supported in the latest versions of Chrome, Firefox, Edge, and Safari.

_x000D_
_x000D_
function copyText(text){_x000D_
  function selectElementText(element) {_x000D_
    if (document.selection) {_x000D_
      var range = document.body.createTextRange();_x000D_
      range.moveToElementText(element);_x000D_
      range.select();_x000D_
    } else if (window.getSelection) {_x000D_
      var range = document.createRange();_x000D_
      range.selectNode(element);_x000D_
      window.getSelection().removeAllRanges();_x000D_
      window.getSelection().addRange(range);_x000D_
    }_x000D_
  }_x000D_
  var element = document.createElement('DIV');_x000D_
  element.textContent = text;_x000D_
  document.body.appendChild(element);_x000D_
  selectElementText(element);_x000D_
  document.execCommand('copy');_x000D_
  element.remove();_x000D_
}_x000D_
_x000D_
_x000D_
var txt = document.getElementById('txt');_x000D_
var btn = document.getElementById('btn');_x000D_
btn.addEventListener('click', function(){_x000D_
  copyText(txt.value);_x000D_
})
_x000D_
<input id="txt" value="Hello World!" />_x000D_
<button id="btn">Copy To Clipboard</button>
_x000D_
_x000D_
_x000D_

HTML checkbox - allow to check only one checkbox

 $(function () {
     $('input[type=checkbox]').click(function () {
         var chks = document.getElementById('<%= chkRoleInTransaction.ClientID %>').getElementsByTagName('INPUT');
         for (i = 0; i < chks.length; i++) {
            chks[i].checked = false;
         }
         if (chks.length > 1)
            $(this)[0].checked = true;
     });
 });

C-like structures in Python

I would also like to add a solution that uses slots:

class Point:
    __slots__ = ["x", "y"]
    def __init__(self, x, y):
        self.x = x
        self.y = y

Definitely check the documentation for slots but a quick explanation of slots is that it is python's way of saying: "If you can lock these attributes and only these attributes into the class such that you commit that you will not add any new attributes once the class is instantiated (yes you can add new attributes to a class instance, see example below) then I will do away with the large memory allocation that allows for adding new attributes to a class instance and use just what I need for these slotted attributes".

Example of adding attributes to class instance (thus not using slots):

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

p1 = Point(3,5)
p1.z = 8
print(p1.z)

Output: 8

Example of trying to add attributes to class instance where slots was used:

class Point:
    __slots__ = ["x", "y"]
    def __init__(self, x, y):
        self.x = x
        self.y = y

p1 = Point(3,5)
p1.z = 8

Output: AttributeError: 'Point' object has no attribute 'z'

This can effectively works as a struct and uses less memory than a class (like a struct would, although I have not researched exactly how much). It is recommended to use slots if you will be creating a large amount of instances of the object and do not need to add attributes. A point object is a good example of this as it is likely that one may instantiate many points to describe a dataset.

What is the equivalent of Select Case in Access SQL?

Consider the Switch Function as an alternative to multiple IIf() expressions. It will return the value from the first expression/value pair where the expression evaluates as True, and ignore any remaining pairs. The concept is similar to the SELECT ... CASE approach you referenced but which is not available in Access SQL.

If you want to display a calculated field as commission:

SELECT
    Switch(
        OpeningBalance < 5001, 20,
        OpeningBalance < 10001, 30,
        OpeningBalance < 20001, 40,
        OpeningBalance >= 20001, 50
        ) AS commission
FROM YourTable;

If you want to store that calculated value to a field named commission:

UPDATE YourTable
SET commission =
    Switch(
        OpeningBalance < 5001, 20,
        OpeningBalance < 10001, 30,
        OpeningBalance < 20001, 40,
        OpeningBalance >= 20001, 50
        );

Either way, see whether you find Switch() easier to understand and manage. Multiple IIf()s can become mind-boggling as the number of conditions grows.

Python ValueError: too many values to unpack

self.materials is a dict and by default you are iterating over just the keys (which are strings).

Since self.materials has more than two keys*, they can't be unpacked into the tuple "k, m", hence the ValueError exception is raised.

In Python 2.x, to iterate over the keys and the values (the tuple "k, m"), we use self.materials.iteritems().

However, since you're throwing the key away anyway, you may as well simply iterate over the dictionary's values:

for m in self.materials.itervalues():

In Python 3.x, prefer dict.values() (which returns a dictionary view object):

for m in self.materials.values():

/usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

I was trying to get clang to work (which also requires 6.0.15), and while poking around I found it was installed at /usr/local/lib/libstdc++.so.6.0.15. It installed there when I installed graphite (an experimental gcc version).

If you need access to libraries at that location, then you’ll need to define LD_LIBRARY_PATH as:

export LD_LIBRARY_PATH=/usr/local/lib:/usr/lib:/usr/local/lib64:/usr/lib64

I was able to get clang to work after doing this. Hope that is helpful to someone.

IPython/Jupyter Problems saving notebook as PDF

To make it work, I installed latex, typical latex extra, and pandoc.

With ubuntu:

sudo apt-get install texlive texlive-latex-extra pandoc

it takes some times: several 100 Mb to download. I read somewhere that you can use --no-install-recommends for texlive and extra to reduce to the dl.

How to overcome the CORS issue in ReactJS

You can set up a express proxy server using http-proxy-middleware to bypass CORS:

const express = require('express');
const proxy = require('http-proxy-middleware');
const path = require('path');
const port = process.env.PORT || 8080;
const app = express();

app.use(express.static(__dirname));
app.use('/proxy', proxy({
    pathRewrite: {
       '^/proxy/': '/'
    },
    target: 'https://server.com',
    secure: false
}));

app.get('*', (req, res) => {
   res.sendFile(path.resolve(__dirname, 'index.html'));
});

app.listen(port);
console.log('Server started');

From your react app all requests should be sent to /proxy endpoint and they will be redirected to the intended server.

const URL = `/proxy/${PATH}`;
return axios.get(URL);

How to sum all the values in a dictionary?

sum(d.values()) - "d" -> Your dictionary Variable

How do you round a double in Dart to a given degree of precision AFTER the decimal point?

double value = 2.8032739273;
String formattedValue = value.toStringAsFixed(3);

Convert array values from string to int?

PHP 7.4 style:

$ids = array_map(fn(string $x): int => (int) $x, explode(',', $string));

Fatal error: Class 'Illuminate\Foundation\Application' not found

Something is clearly corrupt in your Laravel setup and it is very hard to track without more info about your environment. Usually these 2 commands help you resolve such issues

php artisan clear-compiled
composer dump-autoload

If nothing else helps then I recommend you to install fresh Laravel 5 app and copy your application logic over, it should take around 15 min or so.

Clearing an HTML file upload field via JavaScript

For compatibility when ajax is not available, set .val('') or it will resend the last ajax-uploaded file that is still present in the input. The following should properly clear the input whilst retaining .on() events:

var input = $("input[type='file']");
input.html(input.html()).val('');

Get selected item value from Bootstrap DropDown with specific ID

Try this code

<input type="TextBox" ID="yearBox" border="0" disabled>

$('#yearSelected li').on('click', function(){
                $('#yearBox').val($(this).text());
            });



<a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="fas fa-calendar-alt"></i> <span>Academic Years</span> <i class="fas fa-chevron-down"></i> </a>
          <ul class="dropdown-menu">
            <li>
              <ul class="menu" id="yearSelected">
                <li><a href="#">2014-2015</a></li>
                <li><a href="#">2015-2016</a></li>
                <li><a href="#">2016-2017</a></li>
                <li><a href="#">2017-2018</a></li>

              </ul>
            </li>
          </ul>

its work for me

IntelliJ IDEA shows errors when using Spring's @Autowired annotation

It seems like the visibility problem - the parent controller doesn't see the Component you are trying to wire.

Try to add

@ComponentScan("path to respective Component") 

to the parent controller.

Adding rows to dataset

To add rows to existing DataTable in Dataset:

DataRow drPartMtl = DSPartMtl.Tables[0].NewRow();
drPartMtl["Group"] = "Group";
drPartMtl["BOMPart"] = "BOMPart";
DSPartMtl.Tables[0].Rows.Add(drPartMtl);

PHP Session Destroy on Log Out Button

// logout

if(isset($_GET['logout'])) {
    session_destroy();
    unset($_SESSION['username']);
    header('location:login.php');
}

?>

Possible to perform cross-database queries with PostgreSQL?

In case someone needs a more involved example on how to do cross-database queries, here's an example that cleans up the databasechangeloglock table on every database that has it:

CREATE EXTENSION IF NOT EXISTS dblink;

DO 
$$
DECLARE database_name TEXT;
DECLARE conn_template TEXT;
DECLARE conn_string TEXT;
DECLARE table_exists Boolean;
BEGIN
    conn_template = 'user=myuser password=mypass dbname=';

    FOR database_name IN
        SELECT datname FROM pg_database
        WHERE datistemplate = false
    LOOP
        conn_string = conn_template || database_name;

        table_exists = (select table_exists_ from dblink(conn_string, '(select Count(*) > 0 from information_schema.tables where table_name = ''databasechangeloglock'')') as (table_exists_ Boolean));
        IF table_exists THEN
            perform dblink_exec(conn_string, 'delete from databasechangeloglock');
        END IF;     
    END LOOP;

END
$$

ESLint not working in VS Code?

In my case ESLint was disabled in my workspace. I had to enable it in vscode extensions settings.

Using awk to print all columns from the nth to the last

There's a duplicate question with a simpler answer using cut:

 svn status |  grep '\!' | cut -d\  -f2-

-d specifies the delimeter (space), -f specifies the list of columns (all starting with the 2nd)

Does VBA have Dictionary Structure?

VBA can use the dictionary structure of Scripting.Runtime.

And its implementation is actually a fancy one - just by doing myDict(x) = y, it checks whether there is a key x in the dictionary and if there is not such, it even creates it. If it is there, it uses it.

And it does not "yell" or "complain" about this extra step, performed "under the hood". Of course, you may check explicitly, whether a key exists with Dictionary.Exists(key). Thus, these 5 lines:

If myDict.exists("B") Then
    myDict("B") = myDict("B") + i * 3
Else
    myDict.Add "B", i * 3
End If

are the same as this 1 liner - myDict("B") = myDict("B") + i * 3. Check it out:

Sub TestMe()

    Dim myDict As Object, i As Long, myKey As Variant
    Set myDict = CreateObject("Scripting.Dictionary")
    
    For i = 1 To 3
        Debug.Print myDict.Exists("A")
        myDict("A") = myDict("A") + i
        myDict("B") = myDict("B") + 5
    Next i
    
    For Each myKey In myDict.keys
        Debug.Print myKey; myDict(myKey)
    Next myKey

End Sub

enter image description here

How to show Bootstrap table with sort icon

You could try using FontAwesome. It contains a sort-icon (http://fontawesome.io/icon/sort/).

To do so, you would

  1. need to include fontawesome:

    <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
    
  2. and then simply use the fontawesome-icon instead of the default-bootstrap-icons in your th's:

    <th><b>#</b> <i class="fa fa-fw fa-sort"></i></th>
    

Hope that helps.

PHP using Gettext inside <<<EOF string

As far as I can see in the manual, it is not possible to call functions inside HEREDOC strings. A cumbersome way would be to prepare the words beforehand:

<?php

    $world = _("World");

    $str = <<<EOF
    <p>Hello</p>
    <p>$world</p>
EOF;
    echo $str;
?>

a workaround idea that comes to mind is building a class with a magic getter method.

You would declare a class like this:

class Translator
{
 public function __get($name) {
  return _($name); // Does the gettext lookup
  }
 }

Initialize an object of the class at some point:

  $translate = new Translator();

You can then use the following syntax to do a gettext lookup inside a HEREDOC block:

    $str = <<<EOF
    <p>Hello</p>
    <p>{$translate->World}</p>
EOF;
    echo $str;
?>

$translate->World will automatically be translated to the gettext lookup thanks to the magic getter method.

To use this method for words with spaces or special characters (e.g. a gettext entry named Hello World!!!!!!, you will have to use the following notation:

 $translate->{"Hello World!!!!!!"}

This is all untested but should work.

Update: As @mario found out, it is possible to call functions from HEREDOC strings after all. I think using getters like this is a sleek solution, but using a direct function call may be easier. See the comments on how to do this.

How to substitute shell variables in complex text files

Looking, it turns out on my system there is an envsubst command which is part of the gettext-base package.

So, this makes it easy:

envsubst < "source.txt" > "destination.txt"

Note if you want to use the same file for both, you'll have to use something like moreutil's sponge, as suggested by Johnny Utahh: envsubst < "source.txt" | sponge "source.txt". (Because the shell redirect will otherwise empty the file before its read.)

How to uninstall jupyter

If you don't want to use pip-autoremove (since it removes dependencies shared among other packages) and pip3 uninstall jupyter just removed some packages, then do the following:

Copy-Paste:

sudo may be needed as per your need.

python3 -m pip uninstall -y jupyter jupyter_core jupyter-client jupyter-console jupyterlab_pygments notebook qtconsole nbconvert nbformat

Note:

The above command will only uninstall jupyter specific packages. I have not added other packages to uninstall since they might be shared among other packages (eg: Jinja2 is used by Flask, ipython is a separate set of packages themselves, tornado again might be used by others).

In any case, all the dependencies are mentioned below(as of 21 Nov, 2020. jupyter==4.4.0 )

If you are sure you want to remove all the dependencies, then you can use Stan_MD's answer.

attrs
backcall
bleach
decorator
defusedxml
entrypoints
importlib-metadata
ipykernel
ipython
ipython-genutils
ipywidgets
jedi
Jinja2
jsonschema
jupyter
jupyter-client
jupyter-console
jupyter-core
jupyterlab-pygments
MarkupSafe
mistune
more-itertools
nbconvert
nbformat
notebook
pandocfilters
parso
pexpect
pickleshare
prometheus-client
prompt-toolkit
ptyprocess
Pygments
pyrsistent
python-dateutil
pyzmq
qtconsole
Send2Trash
six
terminado
testpath
tornado
traitlets
wcwidth
webencodings
widgetsnbextension
zipp

Executive Edit:

pip3 uninstall jupyter
pip3 uninstall jupyter_core
pip3 uninstall jupyter-client
pip3 uninstall jupyter-console
pip3 uninstall jupyterlab_pygments
pip3 uninstall notebook
pip3 uninstall qtconsole
pip3 uninstall nbconvert
pip3 uninstall nbformat

Explanation of each:

  1. Uninstall jupyter dist-packages:

    pip3 uninstall jupyter

  2. Uninstall jupyter_core dist-packages (It also uninstalls following binaries: jupyter, jupyter-migrate,jupyter-troubleshoot):

    pip3 uninstall jupyter_core

  3. Uninstall jupyter-client:

    pip3 uninstall jupyter-client

  4. Uninstall jupyter-console:

    pip3 uninstall jupyter-console

  5. Uninstall jupyter-notebook (It also uninstalls following binaries: jupyter-bundlerextension, jupyter-nbextension, jupyter-notebook, jupyter-serverextension):

    pip3 uninstall notebook

  6. Uninstall jupyter-qtconsole :

    pip3 uninstall qtconsole

  7. Uninstall jupyter-nbconvert:

    pip3 uninstall nbconvert

  8. Uninstall jupyter-trust:

    pip3 uninstall nbformat

Where can I find System.Web.Helpers, System.Web.WebPages, and System.Web.Razor?

On VS2017 I installed the NuGet package: Microsoft.AspNet.WebPages

That did the trick.

VBA Copy Sheet to End of Workbook (with Hidden Worksheets)

Answer : I found this and wants to share it with you.

Sub Copier4()
   Dim x As Integer

   For x = 1 To ActiveWorkbook.Sheets.Count
      'Loop through each of the sheets in the workbook
      'by using x as the sheet index number.
      ActiveWorkbook.Sheets(x).Copy _
         After:=ActiveWorkbook.Sheets(ActiveWorkbook.Sheets.Count)
         'Puts all copies after the last existing sheet.
   Next
End Sub

But the question, can we use it with following code to rename the sheets, if yes, how can we do so?

Sub CreateSheetsFromAList()
Dim MyCell As Range, MyRange As Range
Set MyRange = Sheets("Summary").Range("A10")
Set MyRange = Range(MyRange, MyRange.End(xlDown))
For Each MyCell In MyRange
Sheets.Add After:=Sheets(Sheets.Count) 'creates a new worksheet
Sheets(Sheets.Count).Name = MyCell.Value ' renames the new worksheet
Next MyCell
End Sub