From component
import { Component, OnInit, ViewChild} from '@angular/core';_x000D_
import { HttpClient } from '@angular/common/http';_x000D_
import { dataService } from "src/app/service/data.service";_x000D_
@Component( {_x000D_
selector: 'app-sideWidget',_x000D_
templateUrl: './sideWidget.html',_x000D_
styleUrls: ['./linked-widget.component.css']_x000D_
} )_x000D_
export class sideWidget{_x000D_
TableColumnNames: object[];_x000D_
SelectedtableName: string = "patient";_x000D_
constructor( private LWTableColumnNames: dataService ) { _x000D_
_x000D_
}_x000D_
_x000D_
ngOnInit() {_x000D_
this.http.post( 'getColumns', this.SelectedtableName )_x000D_
.subscribe(_x000D_
( data: object[] ) => {_x000D_
this.TableColumnNames = data;_x000D_
this.LWTableColumnNames.refLWTableColumnNames = this.TableColumnNames; //this line of code will pass the value through data service_x000D_
} );_x000D_
_x000D_
} _x000D_
}
_x000D_
DataService
import { Injectable } from '@angular/core';_x000D_
import { BehaviorSubject, Observable } from 'rxjs';_x000D_
_x000D_
@Injectable()_x000D_
export class dataService {_x000D_
refLWTableColumnNames: object;//creating an object for the data_x000D_
}
_x000D_
To Component
import { Component, OnInit } from '@angular/core';_x000D_
import { dataService } from "src/app/service/data.service";_x000D_
_x000D_
@Component( {_x000D_
selector: 'app-linked-widget',_x000D_
templateUrl: './linked-widget.component.html',_x000D_
styleUrls: ['./linked-widget.component.css']_x000D_
} )_x000D_
export class LinkedWidgetComponent implements OnInit {_x000D_
_x000D_
constructor(private LWTableColumnNames: dataService) { }_x000D_
_x000D_
ngOnInit() {_x000D_
console.log(this.LWTableColumnNames.refLWTableColumnNames);_x000D_
}_x000D_
createTable(){_x000D_
console.log(this.LWTableColumnNames.refLWTableColumnNames);// calling the object from another component_x000D_
}_x000D_
_x000D_
}
_x000D_
Do you have this namespace setup? You will have to ensure that this namespace matches the message namespace. If you can update your question with the xml input and possibly your data object that would be helpful.
[DataContract(Namespace = "http://CompanyName.com.au/ProjectName")]
public class CustomFields
{
// ...
}
Use repr
and eval
:
>>> s = set([1,2,3])
>>> strs = repr(s)
>>> strs
'set([1, 2, 3])'
>>> eval(strs)
set([1, 2, 3])
Note that eval
is not safe if the source of string is unknown, prefer ast.literal_eval
for safer conversion:
>>> from ast import literal_eval
>>> s = set([10, 20, 30])
>>> lis = str(list(s))
>>> set(literal_eval(lis))
set([10, 20, 30])
help on repr
:
repr(object) -> string
Return the canonical string representation of the object.
For most object types, eval(repr(object)) == object.
One of the versions you posted actually works for all modern browsers (where CSS selectors level 3 are supported):
div ul:not(:first-child) {
background-color: #900;
}
If you need to support legacy browsers, or if you are hindered by the :not
selector's limitation (it only accepts a simple selector as an argument) then you can use another technique:
Define a rule that has greater scope than what you intend and then "revoke" it conditionally, limiting its scope to what you do intend:
div ul {
background-color: #900; /* applies to every ul */
}
div ul:first-child {
background-color: transparent; /* limits the scope of the previous rule */
}
When limiting the scope use the default value for each CSS attribute that you are setting.
There is one edge case where static has a surprising effect(at least it was to me). The C++03 Standard states in 14.6.4.2/1:
For a function call that depends on a template parameter, if the function name is an unqualified-id but not a template-id, the candidate functions are found using the usual lookup rules (3.4.1, 3.4.2) except that:
- For the part of the lookup using unqualified name lookup (3.4.1), only function declarations with external linkage from the template definition context are found.
- For the part of the lookup using associated namespaces (3.4.2), only function declarations with external linkage found in either the template definition context or the template instantiation context are found.
...
The below code will call foo(void*)
and not foo(S const &)
as you might expect.
template <typename T>
int b1 (T const & t)
{
foo(t);
}
namespace NS
{
namespace
{
struct S
{
public:
operator void * () const;
};
void foo (void*);
static void foo (S const &); // Not considered 14.6.4.2(b1)
}
}
void b2()
{
NS::S s;
b1 (s);
}
In itself this is probably not that big a deal, but it does highlight that for a fully compliant C++ compiler (i.e. one with support for export
) the static
keyword will still have functionality that is not available in any other way.
// bar.h
export template <typename T>
int b1 (T const & t);
// bar.cc
#include "bar.h"
template <typename T>
int b1 (T const & t)
{
foo(t);
}
// foo.cc
#include "bar.h"
namespace NS
{
namespace
{
struct S
{
};
void foo (S const & s); // Will be found by different TU 'bar.cc'
}
}
void b2()
{
NS::S s;
b1 (s);
}
The only way to ensure that the function in our unnamed namespace will not be found in templates using ADL is to make it static
.
Update for Modern C++
As of C++ '11, members of an unnamed namespace have internal linkage implicitly (3.5/4):
An unnamed namespace or a namespace declared directly or indirectly within an unnamed namespace has internal linkage.
But at the same time, 14.6.4.2/1 was updated to remove mention of linkage (this taken from C++ '14):
For a function call where the postfix-expression is a dependent name, the candidate functions are found using the usual lookup rules (3.4.1, 3.4.2) except that:
For the part of the lookup using unqualified name lookup (3.4.1), only function declarations from the template definition context are found.
For the part of the lookup using associated namespaces (3.4.2), only function declarations found in either the template definition context or the template instantiation context are found.
The result is that this particular difference between static and unnamed namespace members no longer exists.
I think you need the initSelection
function
$("#programid").select2({
placeholder: "Select a Program",
allowClear: true,
minimumInputLength: 3,
ajax: {
url: "ajax.php",
dataType: 'json',
quietMillis: 200,
data: function (term, page) {
return {
term: term, //search term
flag: 'selectprogram',
page: page // page number
};
},
results: function (data) {
return {results: data};
}
},
initSelection: function (element, callback) {
var id = $(element).val();
if (id !== "") {
$.ajax("ajax.php/get_where", {
data: {programid: id},
dataType: "json"
}).done(function (data) {
$.each(data, function (i, value) {
callback({"text": value.text, "id": value.id});
});
;
});
}
},
dropdownCssClass: "bigdrop",
escapeMarkup: function (m) { return m; }
});
The algorithm is fast, but it has a serious flaw:
>>> sorted(get_primes(530))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73,
79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163,
167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251,
257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349,
353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443,
449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 527, 529]
>>> 17*31
527
>>> 23*23
529
You assume that numbers.pop()
would return the smallest number in the set, but this is not guaranteed at all. Sets are unordered and pop()
removes and returns an arbitrary element, so it cannot be used to select the next prime from the remaining numbers.
I was looking for a solution to quite a related problem: finding the newest records per group which is a specialization of a typical greatest-n-per-group with N = 1.
The solution involves the problem you are dealing with here (i.e., how to build the query in Eloquent) so I am posting it as it might be helpful for others. It demonstrates a cleaner way of sub-query construction using powerful Eloquent fluent interface with multiple join columns and where
condition inside joined sub-select.
In my example I want to fetch the newest DNS scan results (table scan_dns
) per group identified by watch_id
. I build the sub-query separately.
The SQL I want Eloquent to generate:
SELECT * FROM `scan_dns` AS `s`
INNER JOIN (
SELECT x.watch_id, MAX(x.last_scan_at) as last_scan
FROM `scan_dns` AS `x`
WHERE `x`.`watch_id` IN (1,2,3,4,5,42)
GROUP BY `x`.`watch_id`) AS ss
ON `s`.`watch_id` = `ss`.`watch_id` AND `s`.`last_scan_at` = `ss`.`last_scan`
I did it in the following way:
// table name of the model
$dnsTable = (new DnsResult())->getTable();
// groups to select in sub-query
$ids = collect([1,2,3,4,5,42]);
// sub-select to be joined on
$subq = DnsResult::query()
->select('x.watch_id')
->selectRaw('MAX(x.last_scan_at) as last_scan')
->from($dnsTable . ' AS x')
->whereIn('x.watch_id', $ids)
->groupBy('x.watch_id');
$qqSql = $subq->toSql(); // compiles to SQL
// the main query
$q = DnsResult::query()
->from($dnsTable . ' AS s')
->join(
DB::raw('(' . $qqSql. ') AS ss'),
function(JoinClause $join) use ($subq) {
$join->on('s.watch_id', '=', 'ss.watch_id')
->on('s.last_scan_at', '=', 'ss.last_scan')
->addBinding($subq->getBindings());
// bindings for sub-query WHERE added
});
$results = $q->get();
UPDATE:
Since Laravel 5.6.17 the sub-query joins were added so there is a native way to build the query.
$latestPosts = DB::table('posts')
->select('user_id', DB::raw('MAX(created_at) as last_post_created_at'))
->where('is_published', true)
->groupBy('user_id');
$users = DB::table('users')
->joinSub($latestPosts, 'latest_posts', function ($join) {
$join->on('users.id', '=', 'latest_posts.user_id');
})->get();
From IEEE floating-point exceptions in C++ :
This page will answer the following questions.
- My program just printed out 1.#IND or 1.#INF (on Windows) or nan or inf (on Linux). What happened?
- How can I tell if a number is really a number and not a NaN or an infinity?
- How can I find out more details at runtime about kinds of NaNs and infinities?
- Do you have any sample code to show how this works?
- Where can I learn more?
These questions have to do with floating point exceptions. If you get some strange non-numeric output where you're expecting a number, you've either exceeded the finite limits of floating point arithmetic or you've asked for some result that is undefined. To keep things simple, I'll stick to working with the double floating point type. Similar remarks hold for float types.
Debugging 1.#IND, 1.#INF, nan, and inf
If your operation would generate a larger positive number than could be stored in a double, the operation will return 1.#INF on Windows or inf on Linux. Similarly your code will return -1.#INF or -inf if the result would be a negative number too large to store in a double. Dividing a positive number by zero produces a positive infinity and dividing a negative number by zero produces a negative infinity. Example code at the end of this page will demonstrate some operations that produce infinities.
Some operations don't make mathematical sense, such as taking the square root of a negative number. (Yes, this operation makes sense in the context of complex numbers, but a double represents a real number and so there is no double to represent the result.) The same is true for logarithms of negative numbers. Both sqrt(-1.0) and log(-1.0) would return a NaN, the generic term for a "number" that is "not a number". Windows displays a NaN as -1.#IND ("IND" for "indeterminate") while Linux displays nan. Other operations that would return a NaN include 0/0, 0*8, and 8/8. See the sample code below for examples.
In short, if you get 1.#INF or inf, look for overflow or division by zero. If you get 1.#IND or nan, look for illegal operations. Maybe you simply have a bug. If it's more subtle and you have something that is difficult to compute, see Avoiding Overflow, Underflow, and Loss of Precision. That article gives tricks for computing results that have intermediate steps overflow if computed directly.
Starting with the HTML fragment:
<div class='helpTop ...
use the javaScript fragment:
$(...).toggleClass('helpTop').toggleClass('helpBottom');
There are several ways to do this:
You can use the InStr
build-in function to test if a String contains a substring. InStr
will either return the index of the first match, or 0. So you can test if a String begins with a substring by doing the following:
If InStr(1, "Hello World", "Hello W") = 1 Then
MsgBox "Yep, this string begins with Hello W!"
End If
If InStr
returns 1
, then the String ("Hello World"), begins with the substring ("Hello W").
You can also use the like
comparison operator along with some basic pattern matching:
If "Hello World" Like "Hello W*" Then
MsgBox "Yep, this string begins with Hello W!"
End If
In this, we use an asterisk (*) to test if the String begins with our substring.
Typing 'my IP' in google search I got my public IP address and pasted it in IP address (the third option). It works for me.
you have various ways to distinct values on one column or multi columns.
using the GROUP BY
SELECT DISTINCT MIN(o.tblFruit_ID) AS tblFruit_ID,
o.tblFruit_FruitType,
MAX(o.tblFruit_FruitName)
FROM tblFruit AS o
GROUP BY
tblFruit_FruitType
using the subquery
SELECT b.tblFruit_ID,
b.tblFruit_FruitType,
b.tblFruit_FruitName
FROM (
SELECT DISTINCT(tblFruit_FruitType),
MIN(tblFruit_ID) tblFruit_ID
FROM tblFruit
GROUP BY
tblFruit_FruitType
) AS a
INNER JOIN tblFruit b
ON a.tblFruit_ID = b.tblFruit_I
using the join with subquery
SELECT t1.tblFruit_ID,
t1.tblFruit_FruitType,
t1.tblFruit_FruitName
FROM tblFruit AS t1
INNER JOIN (
SELECT DISTINCT MAX(tblFruit_ID) AS tblFruit_ID,
tblFruit_FruitType
FROM tblFruit
GROUP BY
tblFruit_FruitType
) AS t2
ON t1.tblFruit_ID = t2.tblFruit_ID
using the window functions only one column distinct
SELECT tblFruit_ID,
tblFruit_FruitType,
tblFruit_FruitName
FROM (
SELECT tblFruit_ID,
tblFruit_FruitType,
tblFruit_FruitName,
ROW_NUMBER() OVER(PARTITION BY tblFruit_FruitType ORDER BY tblFruit_ID)
rn
FROM tblFruit
) t
WHERE rn = 1
using the window functions multi column distinct
SELECT tblFruit_ID,
tblFruit_FruitType,
tblFruit_FruitName
FROM (
SELECT tblFruit_ID,
tblFruit_FruitType,
tblFruit_FruitName,
ROW_NUMBER() OVER(PARTITION BY tblFruit_FruitType, tblFruit_FruitName
ORDER BY tblFruit_ID) rn
FROM tblFruit
) t
WHERE rn = 1
If you are using npm test
(using package.json scripts) use an extra --
to pass the param through to mocha
e.g. npm test -- --grep "my second test"
EDIT: Looks like --grep
can be a little fussy (probably depending on the other arguments). You can:
Modify the package.json:
"test:mocha": "mocha --grep \"<DealsList />\" .",
Or alternatively use --bail
which seems to be less fussy
npm test -- --bail
From the manual:
Possible values for the parameter timeout: … x set timeout to x seconds
and
readlines(sizehint=None, eol='\n') Read a list of lines, until timeout. sizehint is ignored and only present for API compatibility with built-in File objects.
Note that this function only returns on a timeout.
So your readlines
will return at most every 2 seconds. Use read()
as Tim suggested.
Use which:
set.seed(1)
x <- sample(10, 50, replace = TRUE)
length(which(x > 3 & x < 5))
# [1] 6
You should be able to get what you want here: http://www.merlyn.demon.co.uk/js-date6.htm#YWD.
A better link on the same site is: Working with weeks.
Here is some code based on the links provided and that posted eariler by Dommer. It has been lightly tested against results at http://www.merlyn.demon.co.uk/js-date6.htm#YWD. Please test thoroughly, no guarantee provided.
There was an issue with dates during the period that daylight saving was observed and years where 1 Jan was Friday. Fixed by using all UTC methods. The following returns identical results to Moment.js.
/* For a given date, get the ISO week number_x000D_
*_x000D_
* Based on information at:_x000D_
*_x000D_
* http://www.merlyn.demon.co.uk/weekcalc.htm#WNR_x000D_
*_x000D_
* Algorithm is to find nearest thursday, it's year_x000D_
* is the year of the week number. Then get weeks_x000D_
* between that date and the first day of that year._x000D_
*_x000D_
* Note that dates in one year can be weeks of previous_x000D_
* or next year, overlap is up to 3 days._x000D_
*_x000D_
* e.g. 2014/12/29 is Monday in week 1 of 2015_x000D_
* 2012/1/1 is Sunday in week 52 of 2011_x000D_
*/_x000D_
function getWeekNumber(d) {_x000D_
// Copy date so don't modify original_x000D_
d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));_x000D_
// Set to nearest Thursday: current date + 4 - current day number_x000D_
// Make Sunday's day number 7_x000D_
d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay()||7));_x000D_
// Get first day of year_x000D_
var yearStart = new Date(Date.UTC(d.getUTCFullYear(),0,1));_x000D_
// Calculate full weeks to nearest Thursday_x000D_
var weekNo = Math.ceil(( ( (d - yearStart) / 86400000) + 1)/7);_x000D_
// Return array of year and week number_x000D_
return [d.getUTCFullYear(), weekNo];_x000D_
}_x000D_
_x000D_
var result = getWeekNumber(new Date());_x000D_
document.write('It\'s currently week ' + result[1] + ' of ' + result[0]);
_x000D_
Hours are zeroed when creating the "UTC" date.
Minimized, prototype version (returns only week-number):
Date.prototype.getWeekNumber = function(){_x000D_
var d = new Date(Date.UTC(this.getFullYear(), this.getMonth(), this.getDate()));_x000D_
var dayNum = d.getUTCDay() || 7;_x000D_
d.setUTCDate(d.getUTCDate() + 4 - dayNum);_x000D_
var yearStart = new Date(Date.UTC(d.getUTCFullYear(),0,1));_x000D_
return Math.ceil((((d - yearStart) / 86400000) + 1)/7)_x000D_
};_x000D_
_x000D_
document.write('The current ISO week number is ' + new Date().getWeekNumber());
_x000D_
In this section, you can enter any date in YYYY-MM-DD format and check that this code gives the same week number as Moment.js ISO week number (tested over 50 years from 2000 to 2050).
Date.prototype.getWeekNumber = function(){_x000D_
var d = new Date(Date.UTC(this.getFullYear(), this.getMonth(), this.getDate()));_x000D_
var dayNum = d.getUTCDay() || 7;_x000D_
d.setUTCDate(d.getUTCDate() + 4 - dayNum);_x000D_
var yearStart = new Date(Date.UTC(d.getUTCFullYear(),0,1));_x000D_
return Math.ceil((((d - yearStart) / 86400000) + 1)/7)_x000D_
};_x000D_
_x000D_
function checkWeek() {_x000D_
var s = document.getElementById('dString').value;_x000D_
var m = moment(s, 'YYYY-MM-DD');_x000D_
document.getElementById('momentWeek').value = m.format('W');_x000D_
document.getElementById('answerWeek').value = m.toDate().getWeekNumber(); _x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>_x000D_
_x000D_
Enter date YYYY-MM-DD: <input id="dString" value="2021-02-22">_x000D_
<button onclick="checkWeek(this)">Check week number</button><br>_x000D_
Moment: <input id="momentWeek" readonly><br>_x000D_
Answer: <input id="answerWeek" readonly>
_x000D_
There are (at least) two types of package dependencies you can indicate in your package.json files:
Those packages that are required in order to use your module are listed under the "dependencies" property. Using npm you can add those dependencies to your package.json file this way:
npm install --save packageName
Those packages required in order to help develop your module are listed under the "devDependencies" property. These packages are not necessary for others to use the module, but if they want to help develop the module, these packages will be needed. Using npm you can add those devDependencies to your package.json file this way:
npm install --save-dev packageName
I'm not sure if this breaks any rules but
sudo bash script.sh
seems to work for me.
Here's a method you can use to check if a value is a boolean:
boolean isBoolean(String value) {
return value != null && Arrays.stream(new String[]{"true", "false", "1", "0"})
.anyMatch(b -> b.equalsIgnoreCase(value));
}
Examples of using it:
System.out.println(isBoolean(null)); //false
System.out.println(isBoolean("")); //false
System.out.println(isBoolean("true")); //true
System.out.println(isBoolean("fALsE")); //true
System.out.println(isBoolean("asdf")); //false
System.out.println(isBoolean("01truefalse")); //false
Here it is!! NewLine is known as CRLF(Carriage Return and Line Feed).
Sample:
System.out.println("I\r\nam\r\na\r\nboy");
It worked for me.
"banana".count("ana")
returns 1 instead of 2 !
I think the method iterates over the string (or the list) with a step equal to the length of the substring so it doesn't see this kind of stuff.
So if you want a "full count" you have to implement your own counter with the correct loop of step 1
Correct me if I'm wrong...
Tested and working!
with https, user & password
<?php
//Data, connection, auth
$dataFromTheForm = $_POST['fieldName']; // request data from the form
$soapUrl = "https://connecting.website.com/soap.asmx?op=DoSomething"; // asmx URL of WSDL
$soapUser = "username"; // username
$soapPassword = "password"; // password
// xml post structure
$xml_post_string = '<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetItemPrice xmlns="http://connecting.website.com/WSDL_Service"> // xmlns value to be set to your WSDL URL
<PRICE>'.$dataFromTheForm.'</PRICE>
</GetItemPrice >
</soap:Body>
</soap:Envelope>'; // data from the form, e.g. some ID number
$headers = array(
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/xml",
"Cache-Control: no-cache",
"Pragma: no-cache",
"SOAPAction: http://connecting.website.com/WSDL_Service/GetPrice",
"Content-length: ".strlen($xml_post_string),
); //SOAPAction: your op URL
$url = $soapUrl;
// PHP cURL for https connection with auth
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $soapUser.":".$soapPassword); // username and password - declared at the top of the doc
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// converting
$response = curl_exec($ch);
curl_close($ch);
// converting
$response1 = str_replace("<soap:Body>","",$response);
$response2 = str_replace("</soap:Body>","",$response1);
// convertingc to XML
$parser = simplexml_load_string($response2);
// user $parser to get your data out of XML response and to display it.
?>
You can use the transpose
function from the data.table
library. Simple and fast solution that keeps numeric
values as numeric
.
library(data.table)
# get data
data("mtcars")
# transpose
t_mtcars <- transpose(mtcars)
# get row and colnames in order
colnames(t_mtcars) <- rownames(mtcars)
rownames(t_mtcars) <- colnames(mtcars)
Simple smtp client with php stream socket with tls/ssl smtp STARTTLS command: https://github.com/breakermind/PhpMimeParser/blob/master/PhpSmtpSslSocketClient.php
works with gmail.com with authenticate:
<?php
// Login email and password
$login = "[email protected]";
$pass = "123456";
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'verify_peer', false);
stream_context_set_option($ctx, 'ssl', 'verify_peer_name', false);
try{
// echo $socket = stream_socket_client('ssl://smtp.gmail.com:587', $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);
echo $socket = stream_socket_client('tcp://smtp.gmail.com:587', $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);
if (!$socket) {
print "Failed to connect $err $errstr\n";
return;
}else{
// Http
// fwrite($socket, "GET / HTTP/1.0\r\nHost: www.example.com\r\nAccept: */*\r\n\r\n");
// Smtp
echo fread($socket,8192);
echo fwrite($socket, "EHLO cool.xx\r\n");
echo fread($socket,8192);
// Start tls connection
echo fwrite($socket, "STARTTLS\r\n");
echo fread($socket,8192);
echo stream_socket_enable_crypto($socket, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
// Send ehlo
echo fwrite($socket, "EHLO cool.xx\r\n");
echo fread($socket,8192);
// echo fwrite($socket, "MAIL FROM: <[email protected]>\r\n");
// echo fread($socket,8192);
echo fwrite($socket, "AUTH LOGIN\r\n");
echo fread($socket,8192);
echo fwrite($socket, base64_encode($login)."\r\n");
echo fread($socket,8192);
echo fwrite($socket, base64_encode($pass)."\r\n");
echo fread($socket,8192);
echo fwrite($socket, "rcpt to: <[email protected]>\r\n");
echo fread($socket,8192);
echo fwrite($socket, "DATA\n");
echo fread($socket,8192);
echo fwrite($socket, "Date: ".time()."\r\nTo: <[email protected]>\r\nFrom:<[email protected]\r\nSubject:Hello from php socket tls\r\n.\r\n");
echo fread($socket,8192);
echo fwrite($socket, "QUIT \n");
echo fread($socket,8192);
/* Turn off encryption for the rest */
// stream_socket_enable_crypto($fp, false);
fclose($socket);
}
}catch(Exception $e){
echo $e;
}
If you are using functional component please use this as below.
const [chatHistory, setChatHistory] = useState([]); // define the state
const chatHistoryList = [...chatHistory, {'from':'me', 'message':e.target.value}]; // new array need to update
setChatHistory(chatHistoryList); // update the state
Canvas zoom and pan
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
_x000D_
<canvas id="myCanvas" width="" height=""_x000D_
style="border:1px solid #d3d3d3;">_x000D_
Your browser does not support the canvas element._x000D_
</canvas>_x000D_
_x000D_
<script>_x000D_
console.log("canvas")_x000D_
var ox=0,oy=0,px=0,py=0,scx=1,scy=1;_x000D_
var canvas = document.getElementById("myCanvas");_x000D_
canvas.onmousedown=(e)=>{px=e.x;py=e.y;canvas.onmousemove=(e)=>{ox-=(e.x-px);oy-=(e.y-py);px=e.x;py=e.y;} } _x000D_
_x000D_
canvas.onmouseup=()=>{canvas.onmousemove=null;}_x000D_
canvas.onwheel =(e)=>{let bfzx,bfzy,afzx,afzy;[bfzx,bfzy]=StoW(e.x,e.y);scx-=10*scx/e.deltaY;scy-=10*scy/e.deltaY;_x000D_
[afzx,afzy]=StoW(e.x,e.y);_x000D_
ox+=(bfzx-afzx);_x000D_
oy+=(bfzy-afzy);_x000D_
}_x000D_
var ctx = canvas.getContext("2d");_x000D_
_x000D_
function draw(){_x000D_
window.requestAnimationFrame(draw);_x000D_
ctx.clearRect(0,0,canvas.width,canvas.height);_x000D_
for(let i=0;i<=100;i+=10){_x000D_
let sx=0,sy=i;_x000D_
let ex=100,ey=i;_x000D_
[sx,sy]=WtoS(sx,sy);_x000D_
[ex,ey]=WtoS(ex,ey);_x000D_
ctx.beginPath();_x000D_
ctx.moveTo(sx, sy);_x000D_
ctx.lineTo(ex, ey);_x000D_
ctx.stroke();_x000D_
}_x000D_
for(let i=0;i<=100;i+=10){_x000D_
let sx=i,sy=0;_x000D_
let ex=i,ey=100;_x000D_
[sx,sy]=WtoS(sx,sy);_x000D_
[ex,ey]=WtoS(ex,ey);_x000D_
ctx.beginPath();_x000D_
ctx.moveTo(sx, sy);_x000D_
ctx.lineTo(ex, ey);_x000D_
ctx.stroke();_x000D_
}_x000D_
}_x000D_
draw()_x000D_
function WtoS(wx,wy){_x000D_
let sx=(wx-ox)*scx;_x000D_
let sy=(wy-oy)*scy;_x000D_
return[sx,sy];_x000D_
}_x000D_
function StoW(sx,sy){_x000D_
let wx=sx/scx+ox;_x000D_
let wy=sy/scy+oy;_x000D_
return[wx,wy];_x000D_
}_x000D_
_x000D_
</script>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
The HTTP server doesn't send the response header back to the client until you either specify an error or else you start sending data. If you start sending data back to the client, then the server has to send the response head (which contains the status code) first. Once the header has been sent, you can no longer put a status code in the header, obviously.
Here's the usual problem. You start up the page, and send some initial tags (i.e. <head>
). The server then sends those tags to the client, after first sending the HTTP response header with an assumed SUCCESS status. Now you start working on the meat of the page and discover a problem. You can not send an error at this point because the response header, which would contain the error status, has already been sent.
The solution is this: Before you generate any content at all, check if there are going to be any errors. Only then, when you have assured that there will be no problems, can you then start sending content, like the tag.
In your case, it seems like you have a login page that processes a POST request from a form. You probably throw out some initial HTML, then check if the username and password are valid. Instead, you should authenticate the user/password first, before you generate any HTML at all.
You can use a InputFilter, that's the way:
EditText myEditText = (EditText) findViewById(R.id.editText1);
InputFilter[] filters = new InputFilter[1];
filters[0] = new InputFilter.LengthFilter(10); //Filter to 10 characters
myEditText .setFilters(filters);
How about using streams (Java 8)?
int[] ia = {99, 11, 7, 21, 4, 2};
ia = Arrays.stream(ia).
boxed().
sorted((a, b) -> b.compareTo(a)). // sort descending
mapToInt(i -> i).
toArray();
Or in-place:
int[] ia = {99, 11, 7, 21, 4, 2};
System.arraycopy(
Arrays.stream(ia).
boxed().
sorted((a, b) -> b.compareTo(a)). // sort descending
mapToInt(i -> i).
toArray(),
0,
ia,
0,
ia.length
);
As per the MySQL docs: http://dev.mysql.com/doc/refman/5.0/en/server-system-variables.html#sysvar_max_user_connections
maximum range: 4,294,967,295 (e.g. 2**32 - 1)
You'd probably run out of memory, file handles, and network sockets, on your server long before you got anywhere close to that limit.
This link goes to the best comparison chart around, directly from the Microsoft. It compares ALL aspects of all MS SQL server editions. To compare three editions you are asking about, just focus on the last three columns of every table in there.
Summary compiled from the above document:
* = contains the feature SQLEXPR SQLEXPRWT SQLEXPRADV ---------------------------------------------------------------------------- > SQL Server Core * * * > SQL Server Management Studio - * * > Distributed Replay – Admin Tool - * * > LocalDB - * * > SQL Server Data Tools (SSDT) - - * > Full-text and semantic search - - * > Specification of language in query - - * > some of Reporting services features - - *
What's the difference between "include" and "require" in Ruby?
Answer:
The include and require methods do very different things.
The require method does what include does in most other programming languages: run another file. It also tracks what you've required in the past and won't require the same file twice. To run another file without this added functionality, you can use the load method.
The include method takes all the methods from another module and includes them into the current module. This is a language-level thing as opposed to a file-level thing as with require. The include method is the primary way to "extend" classes with other modules (usually referred to as mix-ins). For example, if your class defines the method "each", you can include the mixin module Enumerable and it can act as a collection. This can be confusing as the include verb is used very differently in other languages.
So if you just want to use a module, rather than extend it or do a mix-in, then you'll want to use require
.
Oddly enough, Ruby's require
is analogous to C's include
, while Ruby's include
is almost nothing like C's include
.
Add bottom:100%
to your #menu:hover ul li:hover ul
rule
#menu:hover ul li:hover ul {
position: absolute;
margin-top: 1px;
font: 10px;
bottom: 100%; /* added this attribute */
}
Or better yet to prevent the submenus from having the same effect, just add this rule
#menu>ul>li:hover>ul {
bottom:100%;
}
source: http://jsfiddle.net/W5FWW/4/
And to get back the border you can add the following attribute
#menu>ul>li:hover>ul {
bottom:100%;
border-bottom: 1px solid transparent
}
You can get the exact age using timesstamp:
const getAge = (dateOfBirth, dateToCalculate = new Date()) => {
const dob = new Date(dateOfBirth).getTime();
const dateToCompare = new Date(dateToCalculate).getTime();
const age = (dateToCompare - dob) / (365 * 24 * 60 * 60 * 1000);
return Math.floor(age);
};
You may check if you have the directory where are the packages of Python (in my machine, this dir is C:\Python27\lib\site-packages) in the Path variable on Windows. If Python's path environment variable does not have this directory, you will not find the packages.
Escape single quote with an additional single as Kirtan pointed out
And if you are trying to execute a dynamic sql (which is not a good idea in the first place) via sp_executesql then the below code would work for you
sp_executesql N'INSERT INTO SomeTable (SomeColumn) VALUES (''John''''s'')'
Use python's clipboard library!
import clipboard as cp
cp.copy("abc")
Clipboard contains 'abc' now. Happy pasting!
You're confusing PATH and PYTHONPATH. You need to do this:
export PATH=$PATH:/home/randy/lib/python
PYTHONPATH is used by the python interpreter to determine which modules to load.
PATH is used by the shell to determine which executables to run.
Please have a look
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
.box{ width:500px; height:200px; background:#000; border:2px solid #ccc;}
.inner-border {
border: 20px solid black;
box-shadow: inset 0px 0px 0px 10px red;
box-sizing: border-box; /* Include padding and border in element's width and height */
}
/* CSS3 solution only for rectangular shape */
.inner-outline {
outline: 10px solid red;
outline-offset: -30px;
}
</style>
</head>
<body>
<div class="box inner-border inner-outline"></div>
</body>
</html>
The backquote operator will also allow you to run python scripts using similar syntax to above
In a python file called python.py:
hello = "hello"
world = "world"
print hello + " " + world
In a php file called python.php:
$python = `python python.py`;
echo $python;
This below code will give selected row, you can parse the values from it and send to the AJAX call.
$(".selected").click(function () {
var row = $(this).parent().parent().parent().html();
});
I'm using this:
var isIframe = (self.frameElement && (self.frameElement+"").indexOf("HTMLIFrameElement") > -1);
var input= $(this);
input.innerHTML = '';
Maybe you're in the wrong perspective?
Eclipse has a construct called a "perspective"; it's a task-oriented arrangement of windows, toolbar buttons, and menus. There's a Java perspective, a Debug perspective, there's probably a PHP perspective, etc. If you're not in the Java perspective, you won't see some of the buttons you expect (like New Class).
To switch perspectives, see the long-ish buttons on the right side of the toolbar, or use the Window menu.
Therefore, before starting '$ sqlplus' on OS, run the followings:
On Windows
set NLS_LANG=AMERICAN_AMERICA.UTF8
On Unix (Solaris and Linux, centos etc)
export NLS_LANG=AMERICAN_AMERICA.UTF8
It would also be advisable to set env variable in your '.bash_profile' [on start up script]
This is the place where other ORACLE env variables (ORACLE_SID, ORACLE_HOME) are usually set.
just fyi - SQL Developer is good at displaying/handling non-English UTF8 characters.
You need to use LogLevel rewrite:trace3
to your httpd.conf
in newer version
http://httpd.apache.org/docs/2.4/mod/mod_rewrite.html#logging
Thanks for the simple solution here from above:
<particular_script/command> || true
The following construction could be used for additional actions/troubleshooting of script steps and additional flow control options:
if <particular_script/command>
then
echo "<particular_script/command> is fine!"
else
echo "<particular_script/command> failed!"
#exit 1
fi
We can brake the further actions and exit 1
if required.
What others have forgotten is Ctrl+Shift+L for easy text search. It searches everywhere and it is fast and efficient. This might be a Sprint tool suit which is an extension of eclipse (and it might be available in newer versions)
ngBind and ngBindTemplate are alternatives that do not require CSS:
<div ng-show="foo != null" ng-cloak>{{name}}</div> <!-- requires CSS -->
<div ng-show="foo != null" ng-bind="name"></div>
<div ng-show="foo != null" ng-bind-template="name = {{name}}"></div>
It is now possible with the HTML5 webapp manifest. See below.
Original answer:
You can't lock a website or a web application in a specific orientation. It goes against the natural behaviour of the device.
You can detect the device orientation with CSS3 media queries like this:
@media screen and (orientation:portrait) {
// CSS applied when the device is in portrait mode
}
@media screen and (orientation:landscape) {
// CSS applied when the device is in landscape mode
}
Or by binding a JavaScript orientation change event like this:
document.addEventListener("orientationchange", function(event){
switch(window.orientation)
{
case -90: case 90:
/* Device is in landscape mode */
break;
default:
/* Device is in portrait mode */
}
});
Update on November 12, 2014: It is now possible with the HTML5 webapp manifest.
As explained on html5rocks.com, you can now force the orientation mode using a manifest.json
file.
You need to include those line into the json file:
{
"display": "standalone", /* Could be "fullscreen", "standalone", "minimal-ui", or "browser" */
"orientation": "landscape", /* Could be "landscape" or "portrait" */
...
}
And you need to include the manifest into your html file like this:
<link rel="manifest" href="manifest.json">
Not exactly sure what the support is on the webapp manifest for locking orientation mode, but Chrome is definitely there. Will update when I have the info.
http://en.wikipedia.org/wiki/Representational_State_Transfer
The basic idea is that instead of having an ongoing connection to the server, you make a request, get some data, show that to a user, but maybe not all of it, and then when the user does something which calls for more data, or to pass some up to the server, the client initiates a change to a new state.
You basically are required to send some information with the request.
Try this,
$opts = array('http'=>array('header' => "User-Agent:MyAgent/1.0\r\n"));
//Basically adding headers to the request
$context = stream_context_create($opts);
$html = file_get_contents($url,false,$context);
$html = htmlspecialchars($html);
This worked out for me
Even if your project has a main()
method, the linker sometimes gets confused. You can solve this issue in Visual Studio 2010 by going to
Project -> Properties -> Configuration Properties -> Linker -> System
and changing SubSystem
to Console.
You can create a VBS script that will force the window to be hidden.
Set WshShell = WScript.CreateObject("WScript.Shell")
obj = WshShell.Run("""C:\Program Files (x86)\McKesson\HRS
Distributed\SwE.bat""", 0)
set WshShell = Nothing
Then, rather than executing the batch file, execute the script.
Try this smooth scrolling demo, or an algorithm like:
self.pageYOffset
element.offsetTop
window.scrollTo
See also the other popular answer to this question.
Andrew Johnson's original code:
function currentYPosition() {
// Firefox, Chrome, Opera, Safari
if (self.pageYOffset) return self.pageYOffset;
// Internet Explorer 6 - standards mode
if (document.documentElement && document.documentElement.scrollTop)
return document.documentElement.scrollTop;
// Internet Explorer 6, 7 and 8
if (document.body.scrollTop) return document.body.scrollTop;
return 0;
}
function elmYPosition(eID) {
var elm = document.getElementById(eID);
var y = elm.offsetTop;
var node = elm;
while (node.offsetParent && node.offsetParent != document.body) {
node = node.offsetParent;
y += node.offsetTop;
} return y;
}
function smoothScroll(eID) {
var startY = currentYPosition();
var stopY = elmYPosition(eID);
var distance = stopY > startY ? stopY - startY : startY - stopY;
if (distance < 100) {
scrollTo(0, stopY); return;
}
var speed = Math.round(distance / 100);
if (speed >= 20) speed = 20;
var step = Math.round(distance / 25);
var leapY = stopY > startY ? startY + step : startY - step;
var timer = 0;
if (stopY > startY) {
for ( var i=startY; i<stopY; i+=step ) {
setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);
leapY += step; if (leapY > stopY) leapY = stopY; timer++;
} return;
}
for ( var i=startY; i>stopY; i-=step ) {
setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);
leapY -= step; if (leapY < stopY) leapY = stopY; timer++;
}
}
Related links:
i will get my answer as follow:
import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
public class findclass {
public static void main(String[] args) throws Exception, IllegalAccessException {
new findclass().findclass(new Object(), "objectName");
new findclass().findclass(1213, "int");
new findclass().findclass("ssdfs", "String");
}
public Map<String, String>map=new HashMap<String, String>();
public void findclass(Object c,String name) throws IllegalArgumentException, IllegalAccessException {
if(map.containsKey(c.getClass().getName() + "@" + Integer.toHexString(c.hashCode()))){
System.out.println(c.getClass().getSimpleName()+" "+name+" = "+map.get(c.getClass().getName() + "@" + Integer.toHexString(c.hashCode()))+" = "+c);
return;}
map.put(c.getClass().getName() + "@" + Integer.toHexString(c.hashCode()), name);
Class te=c.getClass();
if(te.equals(Integer.class)||te.equals(Double.class)||te.equals(Float.class)||te.equals(Boolean.class)||te.equals(Byte.class)||te.equals(Long.class)||te.equals(String.class)||te.equals(Character.class)){
System.out.println(c.getClass().getSimpleName()+" "+name+" = "+c);
return;
}
if(te.isArray()){
if(te==int[].class||te==char[].class||te==double[].class||te==float[].class||te==byte[].class||te==long[].class||te==boolean[].class){
boolean dotflag=true;
for (int i = 0; i < Array.getLength(c); i++) {
System.out.println(Array.get(c, i).getClass().getSimpleName()+" "+name+"["+i+"] = "+Array.get(c, i));
}
return;
}
Object[]arr=(Object[])c;
for (Object object : arr) {
if(object==null)
System.out.println(c.getClass().getSimpleName()+" "+name+" = null");
else {
findclass(object, name+"."+object.getClass().getSimpleName());
}
}
}
Field[] fields=c.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
if(field.get(c)==null){
System.out.println(field.getType().getSimpleName()+" "+name+"."+field.getName()+" = null");
continue;
}
findclass(field.get(c),name+"."+field.getName());
}
if(te.getSuperclass()==Number.class||te.getSuperclass()==Object.class||te.getSuperclass()==null)
return;
Field[]faFields=c.getClass().getSuperclass().getDeclaredFields();
for (Field field : faFields) {
field.setAccessible(true);
if(field.get(c)==null){
System.out.println(field.getType().getSimpleName()+" "+name+"<"+c.getClass().getSuperclass().getSimpleName()+"."+field.getName()+" = null");
continue;
}
Object check=field.get(c);
findclass(field.get(c),name+"<"+c.getClass().getSuperclass().getSimpleName()+"."+field.getName());
}
}
public void findclass(Object c,String name,Writer writer) throws IllegalArgumentException, IllegalAccessException, IOException {
if(map.containsKey(c.getClass().getName() + "@" + Integer.toHexString(c.hashCode()))){
writer.append(c.getClass().getSimpleName()+" "+name+" = "+map.get(c.getClass().getName() + "@" + Integer.toHexString(c.hashCode()))+" = "+c+"\n");
return;}
map.put(c.getClass().getName() + "@" + Integer.toHexString(c.hashCode()), name);
Class te=c.getClass();
if(te.equals(Integer.class)||te.equals(Double.class)||te.equals(Float.class)||te.equals(Boolean.class)||te.equals(Byte.class)||te.equals(Long.class)||te.equals(String.class)||te.equals(Character.class)){
writer.append(c.getClass().getSimpleName()+" "+name+" = "+c+"\n");
return;
}
if(te.isArray()){
if(te==int[].class||te==char[].class||te==double[].class||te==float[].class||te==byte[].class||te==long[].class||te==boolean[].class){
boolean dotflag=true;
for (int i = 0; i < Array.getLength(c); i++) {
writer.append(Array.get(c, i).getClass().getSimpleName()+" "+name+"["+i+"] = "+Array.get(c, i)+"\n");
}
return;
}
Object[]arr=(Object[])c;
for (Object object : arr) {
if(object==null){
writer.append(c.getClass().getSimpleName()+" "+name+" = null"+"\n");
}else {
findclass(object, name+"."+object.getClass().getSimpleName(),writer);
}
}
}
Field[] fields=c.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
if(field.get(c)==null){
writer.append(field.getType().getSimpleName()+" "+name+"."+field.getName()+" = null"+"\n");
continue;
}
findclass(field.get(c),name+"."+field.getName(),writer);
}
if(te.getSuperclass()==Number.class||te.getSuperclass()==Object.class||te.getSuperclass()==null)
return;
Field[]faFields=c.getClass().getSuperclass().getDeclaredFields();
for (Field field : faFields) {
field.setAccessible(true);
if(field.get(c)==null){
writer.append(field.getType().getSimpleName()+" "+name+"<"+c.getClass().getSuperclass().getSimpleName()+"."+field.getName()+" = null"+"\n");
continue;
}
Object check=field.get(c);
findclass(field.get(c),name+"<"+c.getClass().getSuperclass().getSimpleName()+"."+field.getName(),writer);
}
}
}
To access a variable in a class, you must use $this->myVar
instead of $this->$myvar
.
And, you should use access identifier to declare a variable instead of var
.
Please read the doc here.
The Basics:
String
is an immutable class, it can't be changed.
StringBuilder
is a mutable class that can be appended to, characters replaced or removed and ultimately converted to a String
StringBuffer
is the original synchronized version of StringBuilder
You should prefer StringBuilder
in all cases where you have only a single thread accessing your object.
The Details:
Also note that StringBuilder/Buffers
aren't magic, they just use an Array as a backing object and that Array has to be re-allocated when ever it gets full. Be sure and create your StringBuilder/Buffer
objects large enough originally where they don't have to be constantly re-sized every time .append()
gets called.
The re-sizing can get very degenerate. It basically re-sizes the backing Array to 2 times its current size every time it needs to be expanded. This can result in large amounts of RAM getting allocated and not used when StringBuilder/Buffer
classes start to grow large.
In Java String x = "A" + "B";
uses a StringBuilder
behind the scenes. So for simple cases there is no benefit of declaring your own. But if you are building String
objects that are large, say less than 4k, then declaring StringBuilder sb = StringBuilder(4096);
is much more efficient than concatenation or using the default constructor which is only 16 characters. If your String
is going to be less than 10k then initialize it with the constructor to 10k to be safe. But if it is initialize to 10k then you write 1 character more than 10k, it will get re-allocated and copied to a 20k array. So initializing high is better than to low.
In the auto re-size case, at the 17th character the backing Array gets re-allocated and copied to 32 characters, at the 33th character this happens again and you get to re-allocated and copy the Array into 64 characters. You can see how this degenerates to lots of re-allocations and copies which is what you really are trying to avoid using StringBuilder/Buffer
in the first place.
This is from the JDK 6 Source code for AbstractStringBuilder
void expandCapacity(int minimumCapacity) {
int newCapacity = (value.length + 1) * 2;
if (newCapacity < 0) {
newCapacity = Integer.MAX_VALUE;
} else if (minimumCapacity > newCapacity) {
newCapacity = minimumCapacity;
}
value = Arrays.copyOf(value, newCapacity);
}
A best practice is to initialize the StringBuilder/Buffer
a little bit larger than you think you are going to need if you don't know right off hand how big the String
will be but you can guess. One allocation of slightly more memory than you need is going to be better than lots of re-allocations and copies.
Also beware of initializing a StringBuilder/Buffer
with a String
as that will only allocated the size of the String + 16 characters, which in most cases will just start the degenerate re-allocation and copy cycle that you are trying to avoid. The following is straight from the Java 6 source code.
public StringBuilder(String str) {
super(str.length() + 16);
append(str);
}
If you by chance do end up with an instance of StringBuilder/Buffer
that you didn't create and can't control the constructor that is called, there is a way to avoid the degenerate re-allocate and copy behavior. Call .ensureCapacity()
with the size you want to ensure your resulting String
will fit into.
The Alternatives:
Just as a note, if you are doing really heavy String
building and manipulation, there is a much more performance oriented alternative called Ropes.
Another alternative, is to create a StringList
implemenation by sub-classing ArrayList<String>
, and adding counters to track the number of characters on every .append()
and other mutation operations of the list, then override .toString()
to create a StringBuilder
of the exact size you need and loop through the list and build the output, you can even make that StringBuilder
an instance variable and 'cache' the results of .toString()
and only have to re-generate it when something changes.
Also don't forget about String.format()
when building fixed formatted output, which can be optimized by the compiler as they make it better.
Use sed:
MYVAR=ho02123ware38384you443d34o3434ingtod38384day
echo "$MYVAR" | sed -e 's/[a-zA-Z]/X/g' -e 's/[0-9]/N/g'
# prints XXNNNNNXXXXNNNNNXXXNNNXNNXNNNNXXXXXXNNNNNXXX
Note that the subsequent -e
's are processed in order. Also, the g
flag for the expression will match all occurrences in the input.
You can also pick your favorite tool using this method, i.e. perl, awk, e.g.:
echo "$MYVAR" | perl -pe 's/[a-zA-Z]/X/g and s/[0-9]/N/g'
This may allow you to do more creative matches... For example, in the snip above, the numeric replacement would not be used unless there was a match on the first expression (due to lazy and
evaluation). And of course, you have the full language support of Perl to do your bidding...
In my case I had to remove some files that were created by gradle at some point in my study to make things work. So, cleaning up after messing up and then it ran fine ...
If you experienced this issue in a git project, do git status
and remove the unrevisioned files. (For me elasticsearch
had a problem with plugins/analysis-icu
).
Gradle Version
: 5.1.1
Follow the following steps
UIView
.MyView.xib
.UIViewController
from NSObject
in xib. See the image below
Connect the File Owner View to your View. See the image below
Change the class of your View to MyView
. Same as 3.
Here is the code to load the View:
UIViewController *controller=[[UIViewController alloc] initWithNibName:@"MyView" bundle:nil];
MyView* view=(MyView*)controller.view;
[self.view addSubview:myview];
Hope it helps.
Clarification:
UIViewController
is used to load your xib and the View which the UIViewController
has is actually MyView
which you have assigned in the MyView xib..
Demo I have made a demo grab here
If you are using AngularJS, you can use $routeParams
using ngRoute
module
You have to add a module to your app
angular.module('myApp', ['ngRoute'])
Now you can use service $routeParams
:
.controller('AppCtrl', function($routeParams) {
console.log($routeParams); // JSON object
}
Since most of the ansswers seem to be outdated here is the setting that worked for me:
elasticsearch.yml:
cluster.name: production
node.name: node1
network.host: 0.0.0.0
transport.tcp.port: 9300
cluster.initial_master_nodes: node1
Setup:
client = new PreBuiltTransportClient(Settings.builder().put("cluster.name", "production").build());
client.addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"), 9300));
Since PreBuiltTransportClient is deprecated you should use RestHighLevelClient for Elasticsearch-Version 7.3.0: https://artifacts.elastic.co/javadoc/org/elasticsearch/client/elasticsearch-rest-high-level-client/7.3.0/index.html
I had the same problem after upgrading to Windows 10.
This worked for me
Set-ExecutionPolicy Unrestricted
If it still doesn't work try editing devenv.exe.config
Visual Studio 2013: C:\Users\<UserName>\AppData\Local\Microsoft\VisualStudio\12.0
Visual Studio 2015: C:\Users\<UserName>\AppData\Local\Microsoft\VisualStudio\14.0
Add the following
<dependentAssembly>
<assemblyIdentity name="System.Management.Automation" publicKeyToken="31bf3856ad364e35" />
<publisherPolicy apply="no" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.PowerShell.Commands.Utility" publicKeyToken="31bf3856ad364e35" />
<publisherPolicy apply="no" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.PowerShell.ConsoleHost" publicKeyToken="31bf3856ad364e35" />
<publisherPolicy apply="no" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.PowerShell.Commands.Management" publicKeyToken="31bf3856ad364e35" />
<publisherPolicy apply="no" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.PowerShell.Security" publicKeyToken="31bf3856ad364e35" />
<publisherPolicy apply="no" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.PowerShell.Commands.Diagnostics" publicKeyToken="31bf3856ad364e35" />
<publisherPolicy apply="no" />
</dependentAssembly>
You can redirect the output to /dev/null
. For more info regarding /dev/null read this link.
You can hide the output of a comand in the following ways :
echo -n "Installing nano ......"; yum install nano > /dev/null; echo " done.";
Redirect the standard output to /dev/null
, but not the standard error. This will show the errors occurring during the installation, for example if yum
cannot find a package.
echo -n "Installing nano ......"; yum install nano &> /dev/null; echo " done.";
While this code will not show anything in the terminal since both standard error and standard output are redirected and thus nullified to /dev/null
.
This is for Bootstrap 4.0, you only need to enter selected on the first line, it acts as a placeholder. The values are not necessary, but if you want to add value 0-... that is up to you. Much simpler than you may think:
<select class="custom-select">
<option selected>Open This</option>
<option value="">1st Choice</option>
<option value="">2nd Choice</option>
</select>
sum up each row using rowSums
(rowwise
works for any aggreation, but is slower)
df %>%
replace(is.na(.), 0) %>%
mutate(sum = rowSums(across(where(is.numeric))))
sum down each column
df %>%
summarise(across(everything(), ~ sum(., is.na(.), 0)))
sum up each row
df %>%
replace(is.na(.), 0) %>%
mutate(sum = rowSums(.[1:5]))
sum down each column using superseeded summarise_all
:
df %>%
replace(is.na(.), 0) %>%
summarise_all(funs(sum))
You can use the following attributes for webkit, which reach into the shadow DOM:
::-webkit-scrollbar { /* 1 */ }
::-webkit-scrollbar-button { /* 2 */ }
::-webkit-scrollbar-track { /* 3 */ }
::-webkit-scrollbar-track-piece { /* 4 */ }
::-webkit-scrollbar-thumb { /* 5 */ }
::-webkit-scrollbar-corner { /* 6 */ }
::-webkit-resizer { /* 7 */ }
Here's a working fiddle with a red scrollbar, based on code from this page explaining the issues.
http://jsfiddle.net/hmartiro/Xck2A/1/
Using this and your solution, you can handle all browsers except Firefox, which at this point I think still requires a javascript solution.
You can also use strdup:
char* p = strdup("abc");
It's possible that you're not fetching the Joined Set. Be sure to include the set in your HQL:
public List<Node> getAll() {
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("FROM Node as n LEFT JOIN FETCH n.nodeValues LEFT JOIN FETCH n.nodeStats");
return query.list();
}
Where your class has 2 sets like:
public class Node implements Serializable {
@OneToMany(fetch=FetchType.LAZY)
private Set<NodeValue> nodeValues;
@OneToMany(fetch=FetchType.LAZY)
private Set<NodeStat> nodeStats;
}
This link has the break down
http://clang.llvm.org/docs/AutomaticReferenceCounting.html#ownership.spelling.property
assign implies __unsafe_unretained ownership.
copy implies __strong ownership, as well as the usual behavior of copy semantics on the setter.
retain implies __strong ownership.
strong implies __strong ownership.
unsafe_unretained implies __unsafe_unretained ownership.
weak implies __weak ownership.
If for some reason your column logic is complex (case when ... then ... else ... end), then the above solutions causes you to have to repeat the same logic in the len() function. Duplicating the same logic becomes a mess. If this is the case then this is a solution worth noting. This example gets rid of the last unwanted comma. I finally found a use for the REVERSE function.
select reverse(stuff(reverse('a,b,c,d,'), 1, 1, ''))
Try this code it works:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim CustomeDate As String = ("#" & DOE.Value.Date.ToString("d/MM/yyyy") & "#")
MsgBox(CustomeDate.ToString)
con.Open()
dadap = New System.Data.OleDb.OleDbDataAdapter("SELECT * FROM QRY_Tran where FORMAT(qry_tran.doe,'d/mm/yyyy') = " & CustomeDate & "", con)
ds = New System.Data.DataSet
dadap.Fill(ds)
Dgview.DataSource = ds.Tables(0)
con.Close()
Note : if u use dd
for date representation it will return nothing while selecting 1 to 9 so use d
for selection
'Date time format
'MMM Three-letter month.
'ddd Three-letter day of the week.
'd Day of the month.
'HH Two-digit hours on 24-hour scale.
'mm Two-digit minutes.
'yyyy Four-digit year.
The documentation contains a full list of the date formats.
If you want the logo to take space, you are probably better of floating it left and then moving down the content using margin, sort of like this:
#logo { float: left; margin: 0 10px 10px 20px; } #content { margin: 10px 0 0 10px; }
or whatever margin you want.
I was trying to to the same, I found lots of information on reading .docx but much less on .doc; Anyway, I managed to read the text using the following:
import win32com.client
word = win32com.client.Dispatch("Word.Application")
word.visible = False
wb = word.Documents.Open("myfile.doc")
doc = word.ActiveDocument
print(doc.Range().Text)
// I built my datatable first, and populated it, columns, rows and all. //Then, once the datatable is functional, do the following to bind it to the DGV. NOTE: the DGV's AutoGenerateColumns property must be 'true' for this example, or the "assigning" of column names from datatable to dgv will not work. I also "added" my datatable to a dataset previously, but I don't think that is necessary.
BindingSource SBind = new BindingSource();
SBind.DataSource = dtSourceData;
ADGView1.AutoGenerateColumns = true; //must be "true" here
ADGView1.Columns.Clear();
ADGView1.DataSource = SBind;
//set DGV's column names and headings from the Datatable properties
for (int i = 0; i < ADGView1.Columns.Count; i++)
{
ADGView1.Columns[i].DataPropertyName = dtSourceData.Columns[i].ColumnName;
ADGView1.Columns[i].HeaderText = dtSourceData.Columns[i].Caption;
}
ADGView1.Enabled = true;
ADGView1.Refresh();
If you are trying to decode a web image you can simply use this :
import base64
with open("imageToSave.png", "wb") as fh:
fh.write(base64.urlsafe_b64decode('data'))
data => is the encoded string
It will take care of the padding errors
One special case: a cookie has no path.
In this case set path as cookie.setPath(request.getRequestURI())
The javascript sets cookie without path so the browser shows it as cookie for the current page only. If I try to send the expired cookie with path == /
the browser shows two cookies: one expired with path == /
and another one with path == current page
.
input type = number
When you want to provide a number input, you can use the HTML5 input type="number" attribute value.
<input type="number" name="n" />
Here is the keyboard that comes up on iPhone 4:
iPhone Screenshot of HTML5 input type number Android 2.2 uses this keyboard for type=number:
Android Screenshot of HTML5 input type number
You can try onload event. It raised when all scripts has been loaded :
window.onload = function () {
//jquery ready for use here
}
But keep in mind, that you may override others scripts where window.onload using.
This way Convert all Data From Filelds(Columns) In Table To Record (Row).
Declare @TableName [nvarchar](128)
Declare @ExecStr nvarchar(max)
Declare @Where nvarchar(max)
Set @TableName = 'myTableName'
--Enter Filtering If Exists
Set @Where = ''
--Set @ExecStr = N'Select * From '+quotename(@TableName)+@Where
--Exec(@ExecStr)
Drop Table If Exists #tmp_Col2Row
Create Table #tmp_Col2Row
(Field_Name nvarchar(128) Not Null
,Field_Value nvarchar(max) Null
)
Set @ExecStr = N' Insert Into #tmp_Col2Row (Field_Name , Field_Value) '
Select @ExecStr += (Select N'Select '''+C.name+''' ,Convert(nvarchar(max),'+quotename(C.name) + ') From ' + quotename(@TableName)+@Where+Char(10)+' Union All '
from sys.columns as C
where (C.object_id = object_id(@TableName))
for xml path(''))
Select @ExecStr = Left(@ExecStr,Len(@ExecStr)-Len(' Union All '))
--Print @ExecStr
Exec (@ExecStr)
Select * From #tmp_Col2Row
Go
If the JSON data in your array is sorted in some way, there are a variety of searches you could implement. However, if you're not dealing with a lot of data then you're probably going to be fine with an O(n) operation here (as you have). Anything else would probably be overkill.
function user() {
parent::Model();
}
=> class name is User, construct name is User.
function User() {
parent::Model();
}
To close the current cmd windows immediately, just add as the last command/line:
move nul 2>&0
Try move nul
to nowhere and redirect the stderr to stdin
will result in the current window cmd.exe being closed
This is different from closing a bat, or exiting it using goto :EOF
or Exit /b
Works for me too
responsive:true
maintainAspectRatio: false
<div class="row">
<div class="col-xs-12">
<canvas id="mycanvas" width="500" height="300"></canvas>
</div>
</div>
Thank You
All you need is:
[OutputCache(Duration=0)]
public JsonResult MyAction(
or, if you want to disable it for an entire Controller:
[OutputCache(Duration=0)]
public class MyController
Despite the debate in comments here, this is enough to disable browser caching - this causes ASP.Net to emit response headers that tell the browser the document expires immediately:
Doing the same in declarative pipeline syntax, below are few examples:
stage('master-branch-stuff') {
when {
branch 'master'
}
steps {
echo 'run this stage - ony if the branch = master branch'
}
}
stage('feature-branch-stuff') {
when {
branch 'feature/*'
}
steps {
echo 'run this stage - only if the branch name started with feature/'
}
}
stage('expression-branch') {
when {
expression {
return env.BRANCH_NAME != 'master';
}
}
steps {
echo 'run this stage - when branch is not equal to master'
}
}
stage('env-specific-stuff') {
when {
environment name: 'NAME', value: 'this'
}
steps {
echo 'run this stage - only if the env name and value matches'
}
}
More effective ways coming up -
https://issues.jenkins-ci.org/browse/JENKINS-41187
Also look at -
https://jenkins.io/doc/book/pipeline/syntax/#when
The directive beforeAgent true
can be set to avoid spinning up an agent to run the conditional, if the conditional doesn't require git state to decide whether to run:
when { beforeAgent true; expression { return isStageConfigured(config) } }
Release post and docs
UPDATE
New WHEN Clause
REF: https://jenkins.io/blog/2018/04/09/whats-in-declarative
equals - Compares two values - strings, variables, numbers, booleans - and returns true if they’re equal. I’m honestly not sure how we missed adding this earlier! You can do "not equals" comparisons using the not { equals ... } combination too.
changeRequest - In its simplest form, this will return true if this Pipeline is building a change request, such as a GitHub pull request. You can also do more detailed checks against the change request, allowing you to ask "is this a change request against the master branch?" and much more.
buildingTag - A simple condition that just checks if the Pipeline is running against a tag in SCM, rather than a branch or a specific commit reference.
tag - A more detailed equivalent of buildingTag, allowing you to check against the tag name itself.
Or if you dont know the url, you can use
hadoop fs -rm -r -f /user/the/path/to/your/dir
I was facing same issue. I looked into environment variable for 'PATH' variable I could not found this. Then I added a variable 'Path' with "C:\Windows\System32" value. Everything is resolved now.
I had a problem installing virtualenvwrapper
after successfully installing virtualenv
.
My terminal complained after I did this:
pip install virtualenvwrapper
So, I unsuccessfully tried this (NOT RECOMMENDED):
sudo pip install virtualenvwrapper
Then, I successfully installed it with this:
pip install --user virtualenvwrapper
indexOf
is an option, but it's implementation is basically searching the entire array for the value, so execution time grows with array size. (so it is in every browser I guess, I only checked Firefox).
I haven't got an IE6 around to check, but I'd call it a safe bet that you can check at least a million array items per second this way on almost any client machine. If [array size]*[searches per second] may grow bigger than a million you should consider a different implementation.
Basically you can use an object to make an index for your array, like so:
var index={'three':0, 'seven':1, 'eleven':2};
Any sane JavaScript environment will create a searchable index for such objects so that you can quickly translate a key into a value, no matter how many properties the object has.
This is just the basic method, depending on your need you may combine several objects and/or arrays to make the same data quickly searchable for different properties. If you specify your exact needs I can suggest a more specific data structure.
Why not just wrap an anchor tag around a button element.
<a href="somepage.html"><button type="button">Text of Some Page</button></a>
This will work for IE9+, Chrome, Safari, Firefox, and probably Opera.
In my case I have a database class that handle all the direct database interaction such as querying, fetching, and such. So if I had to change my database from MySQL to PostgreSQL there won't be any problem. So adding that extra layer can be useful.
Each table can have its own class and have its specific methods, but to actually get the data, it lets the database class handle it:
Database.php
class Database {
private static $connection;
private static $current_query;
...
public static function query($sql) {
if (!self::$connection){
self::open_connection();
}
self::$current_query = $sql;
$result = mysql_query($sql,self::$connection);
if (!$result){
self::close_connection();
// throw custom error
// The query failed for some reason. here is query :: self::$current_query
$error = new Error(2,"There is an Error in the query.\n<b>Query:</b>\n{$sql}\n");
$error->handleError();
}
return $result;
}
....
public static function find_by_sql($sql){
if (!is_string($sql))
return false;
$result_set = self::query($sql);
$obj_arr = array();
while ($row = self::fetch_array($result_set))
{
$obj_arr[] = self::instantiate($row);
}
return $obj_arr;
}
}
Table object classL
class DomainPeer extends Database {
public static function getDomainInfoList() {
$sql = 'SELECT ';
$sql .='d.`id`,';
$sql .='d.`name`,';
$sql .='d.`shortName`,';
$sql .='d.`created_at`,';
$sql .='d.`updated_at`,';
$sql .='count(q.id) as queries ';
$sql .='FROM `domains` d ';
$sql .='LEFT JOIN queries q on q.domainId = d.id ';
$sql .='GROUP BY d.id';
return self::find_by_sql($sql);
}
....
}
I hope this example helps you create a good structure.
It's all about the order of the scripts. Try to reorder them, place jquery.datetimepicker.js to be last of all scripts!
Eclipse Runnable JAR File
Create a Java Project – RunnableJAR
Main Class
public class RunnableMainClass {
public static void main(String[] args) throws InterruptedException {
System.out.println("Name : "+args[0]);
System.out.println(" ID : "+args[1]);
}
}
Run Jar file using java program (cmd) by supplying arguments and get the output and display in eclipse console.
public class RunJar {
static StringBuilder sb = new StringBuilder();
public static void main(String[] args) throws IOException {
String jarfile = "D:\\JarLocation\\myRunnable.jar";
String name = "Yash";
String id = "777";
try { // jarname arguments has to be saperated by spaces
Process process = Runtime.getRuntime().exec("cmd.exe start /C java -jar "+jarfile+" "+name+" "+id);
//.exec("cmd.exe /C start dir java -jar "+jarfile+" "+name+" "+id+" dir");
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream ()));
String line = null;
while ((line = br.readLine()) != null){
sb.append(line).append("\n");
}
System.out.println("Console OUTPUT : \n"+sb.toString());
process.destroy();
}catch (Exception e){
System.err.println(e.getMessage());
}
}
}
In Eclipse to find Short cuts:
Help ? Help Contents ? Java development user guide ? References ? Menus and Actions
I came across this question when I was trying to learn how to pass data from one View Controller to another. I need something visual to help me learn though, so this answer is a supplement to the others already here. It is a little more general than the original question but it can be adapted to work.
This basic example works like this:
The idea is to pass a string from the text field in the First View Controller to the label in the Second View Controller.
import UIKit
class FirstViewController: UIViewController {
@IBOutlet weak var textField: UITextField!
// This function is called before the segue
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// get a reference to the second view controller
let secondViewController = segue.destinationViewController as! SecondViewController
// set a variable in the second view controller with the String to pass
secondViewController.receivedString = textField.text!
}
}
import UIKit
class SecondViewController: UIViewController {
@IBOutlet weak var label: UILabel!
// This variable will hold the data being passed from the First View Controller
var receivedString = ""
override func viewDidLoad() {
super.viewDidLoad()
// Used the text from the First View Controller to set the label
label.text = receivedString
}
}
UITextField
and the UILabel
.How to send data through segue (swift) (YouTube tutorial)
View Controllers: Passing data forward and passing data back (fuller answer)
Your code is working at my end, i have just tested it. Where are you checking your changes? Use Documents directory path. To get path -
NSLog(@"%@",documentsDirectory);
and copy path from console and then open finder and press Cmd+shift+g and paste path here and then open your file
Using a decorator for measuring execution time for functions can be handy. There is an example at http://www.zopyx.com/blog/a-python-decorator-for-measuring-the-execution-time-of-methods.
Below I've shamelessly pasted the code from the site mentioned above so that the example exists at SO in case the site is wiped off the net.
import time
def timeit(method):
def timed(*args, **kw):
ts = time.time()
result = method(*args, **kw)
te = time.time()
print '%r (%r, %r) %2.2f sec' % \
(method.__name__, args, kw, te-ts)
return result
return timed
class Foo(object):
@timeit
def foo(self, a=2, b=3):
time.sleep(0.2)
@timeit
def f1():
time.sleep(1)
print 'f1'
@timeit
def f2(a):
time.sleep(2)
print 'f2',a
@timeit
def f3(a, *args, **kw):
time.sleep(0.3)
print 'f3', args, kw
f1()
f2(42)
f3(42, 43, foo=2)
Foo().foo()
// John
When I was to get yesterday with just the date in the format Year/Month/Day
I use:
$Variable = Get-Date((get-date ).AddDays(-1)) -Format "yyyy-MM-dd"
In 2021, this is solved* at the language level in Javascript (and Typescript too) with the new Optional Chaining syntax
me.onChange?.(str)
It's as simple as that - onChange
only gets called if it exists.
If onChange
doesn't exist, nothing happens, and the expression returns undefined
.
So if onChange()
would ordinarily return a value
, you'd want to check value !== undefined
before continuing.
An extra thing to note - if onChange
does exist but is not a function, this will throw a TypeError
. This is as you would expect, it's the same behaviour as calling any non-function as a function, just worth pointing out that Optional Chaining doesn't do any magic to make this go away.
* Optional Chaining is a stage 4 TC39 proposal, so isn't technically in the ECMAScript spec yet. But, stage 4 means it's finalised and essentially guaranteed to be included in the next version. You can use Optional Chaining today via Babel or Typescript with confidence it won't change.
That's a half-open interval.
[a,b]
includes the end points.(a,b)
excludes them.In your case the end-point at the start of the interval is included, but the end is excluded. So it means the interval "first1 <= x < last1".
Half-open intervals are useful in programming because they correspond to the common idiom for looping:
for (int i = 0; i < n; ++i) { ... }
Here i is in the range [0, n).
As you've noticed, you have no selectivity to your update statement so it is updating your entire table. If you want to update specific rows (ie where the IDs match) you probably want to do a coordinated subquery.
However, since you are using Oracle, it might be easier to create a materialized view for your query table and let Oracle's transaction mechanism handle the details. MVs work exactly like a table for querying semantics, are quite easy to set up, and allow you to specify the refresh interval.
The filter function wasn't working for me at all; maybe the more recent version of jquery doesn't perform as the version used in above code. Regardless; I used:
var black = $('.black');
var white = $('.white');
The selector will find every element classed under black or white. Button functions stay as stated above:
$('#showBlackButton').click(function() {
black.show();
white.hide();
});
$('#showWhiteButton').click(function() {
white.show();
black.hide();
});
Try this,simple and easy
System.getProperty("os.name");
System.getProperty("os.version");
System.getProperty("os.arch");
If you are having this error on Intellij IDEA even after adding the log4j.properties
or log4j.xml
file on your resources test folder, maybe the Intellij IDEA is not aware yet about the existence of the file.
So, after add the file, right click on the file and choose Recompile log4j.xml.
As mentioned in this answer, you can create a git alias and assign a set of commands for it. In this case, it would be:
git config --global alias.add-com-push '!git add . && git commit -a -m "commit" && git push'
and use it with
git add-com-push
Thanks Darin, For me, to be able to post to the create method, It only worked after I modified the BindModel code to :
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (!string.IsNullOrEmpty(displayFormat) && value != null)
{
DateTime date;
displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
// use the format specified in the DisplayFormat attribute to parse the date
if (DateTime.TryParse(value.AttemptedValue, CultureInfo.GetCultureInfo("en-GB"), DateTimeStyles.None, out date))
{
return date;
}
else
{
bindingContext.ModelState.AddModelError(
bindingContext.ModelName,
string.Format("{0} is an invalid date format", value.AttemptedValue)
);
}
}
return base.BindModel(controllerContext, bindingContext);
}
Hope this could help someone else...
Unused "private http: Http" argument in the constructor of app.component.ts had caused me the same error and it resolved upon removing the unused argument of the constructor
Or you can use:
echo "1: " | awk '/1/{print $1-":"}'
This is a really funny equation.
You were close. format=
needs to be added to the as.Date
call:
mydate <- factor("1/15/2006 0:00:00")
as.Date(mydate, format = "%m/%d/%Y")
## [1] "2006-01-15"
When working with a version control system where all files are read only until checked out (like Perforce), the problem may be that you accidentally submitted into this version control system one of the VS files (like filters, for example) and the file thus cannot be overridden during build.
Just go to your working directory and check that none of VS solution related files and none of temporary created files (like all moc_ and ui_ prefixed files in QT, for example) is read only.
For iOS 8 we can just use this [UIScreen mainScreen].nativeBounds
, like that:
- (NSInteger)resolutionX
{
return CGRectGetWidth([UIScreen mainScreen].nativeBounds);
}
- (NSInteger)resolutionY
{
return CGRectGetHeight([UIScreen mainScreen].nativeBounds);
}
Take a look at the Google solution. Here is a deletion method only.
ListViewRemovalAnimation project code and Video demonstration
It needs Android 4.1+ (API 16). But we have 2014 outside.
I think PHP is a good solution. It's simple to set up, free and there is plenty of documentation on how to create a database management app. Ruby on Rails is faster to code but a bit more difficult to set up.
import("time")
layout := "2006-01-02T15:04:05.000Z"
str := "2014-11-12T11:45:26.371Z"
t, err := time.Parse(layout, str)
if err != nil {
fmt.Println(err)
}
fmt.Println(t)
gives:
>> 2014-11-12 11:45:26.371 +0000 UTC
You can use
text.replace('old', 'new')
And to change multiple values in one string at once, for example to change # to string v and _ to string w:
text.replace(/#|_/g,function(match) {return (match=="#")? v: w;});
GoalSeek will throw an "Invalid Reference" error if the GoalSeek cell contains a value rather than a formula or if the ChangingCell contains a formula instead of a value or nothing.
The GoalSeek cell must contain a formula that refers directly or indirectly to the ChangingCell; if the formula doesn't refer to the ChangingCell in some way, GoalSeek either may not converge to an answer or may produce a nonsensical answer.
I tested your code with a different GoalSeek formula than yours (I wasn't quite clear whether some of the terms referred to cells or values).
For the test, I set:
the GoalSeek cell H18 = (G18^3)+(3*G18^2)+6
the Goal cell H32 = 11
the ChangingCell G18 = 0
The code was:
Sub GSeek()
With Worksheets("Sheet1")
.Range("H18").GoalSeek _
Goal:=.Range("H32").Value, _
ChangingCell:=.Range("G18")
End With
End Sub
And the code produced the (correct) answer of 1.1038, the value of G18 at which the formula in H18 produces the value of 11, the goal I was seeking.
In Python 3,
urllib2
was replaced by two in-built modules namedurllib.request
andurllib.error
Adapted from source
So replace this:
import urllib2
With this:
import urllib.request as urllib2
Difference Between For and For Each Loop in C#
For Loops executes a block of code until an expression returns false while ForEach loop executed a block of code through the items in object collections.
For loop can execute with object collections or without any object collections while ForEach loop can execute with object collections only.
The for loop is a normal loop construct which can be used for multiple purposes where as foreach is designed to work only on Collections or IEnumerables object.
If you would like to have a histogram of unique values here's oneliner
import numpy as np
unique_labels, unique_counts = np.unique(labels_list, return_counts=True)
labels_histogram = dict(zip(unique_labels, unique_counts))
When your table is not part of the default schema, you should write:
\d+ schema_name.table_name
Otherwise, you would get the error saying that "the relation doesn not exist."
Here is a great one http://download.oracle.com/javase/1.5.0/docs/api/
These languages are big. You cant expect a cheat sheet to fit on a piece of paper
By adding 100 to the number, then run a substring function from index 1 to the last position in right.
var dt = new Date();
var month = (100 + dt.getMonth()+1).toString().substr(1, 2);
var day = (100 + dt.getDate()).toString().substr(1, 2);
console.log(month,day);
you will got this result from the date of 2020-11-3
11,03
I hope the answer is useful
package com.concepttimes.java;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class IllegalStateExceptionDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
List al = new ArrayList();
al.add("Sachin");
al.add("Rahul");
al.add("saurav");
Iterator itr = al.iterator();
while (itr.hasNext()) {
itr.remove();
}
}
}
IllegalStateException signals that method has been invoked at the wrong time. In this below example, we can see that. remove() method is called at the same time element is being used in while loop.
Please refer to below link for more details. http://www.elitmuszone.com/elitmus/illegalstateexception-in-java/
For people (like me) coming here via search engine and just looking for a solution which works out of the box, I recommend installing mpu
. Install it via pip install mpu --user
and use it like this to get the haversine distance:
import mpu
# Point one
lat1 = 52.2296756
lon1 = 21.0122287
# Point two
lat2 = 52.406374
lon2 = 16.9251681
# What you were looking for
dist = mpu.haversine_distance((lat1, lon1), (lat2, lon2))
print(dist) # gives 278.45817507541943.
An alternative package is gpxpy
.
If you don't want dependencies, you can use:
import math
def distance(origin, destination):
"""
Calculate the Haversine distance.
Parameters
----------
origin : tuple of float
(lat, long)
destination : tuple of float
(lat, long)
Returns
-------
distance_in_km : float
Examples
--------
>>> origin = (48.1372, 11.5756) # Munich
>>> destination = (52.5186, 13.4083) # Berlin
>>> round(distance(origin, destination), 1)
504.2
"""
lat1, lon1 = origin
lat2, lon2 = destination
radius = 6371 # km
dlat = math.radians(lat2 - lat1)
dlon = math.radians(lon2 - lon1)
a = (math.sin(dlat / 2) * math.sin(dlat / 2) +
math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) *
math.sin(dlon / 2) * math.sin(dlon / 2))
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
d = radius * c
return d
if __name__ == '__main__':
import doctest
doctest.testmod()
The other alternative package is [haversine][1]
from haversine import haversine, Unit
lyon = (45.7597, 4.8422) # (lat, lon)
paris = (48.8567, 2.3508)
haversine(lyon, paris)
>> 392.2172595594006 # in kilometers
haversine(lyon, paris, unit=Unit.MILES)
>> 243.71201856934454 # in miles
# you can also use the string abbreviation for units:
haversine(lyon, paris, unit='mi')
>> 243.71201856934454 # in miles
haversine(lyon, paris, unit=Unit.NAUTICAL_MILES)
>> 211.78037755311516 # in nautical miles
They claim to have performance optimization for distances between all points in two vectors
from haversine import haversine_vector, Unit
lyon = (45.7597, 4.8422) # (lat, lon)
paris = (48.8567, 2.3508)
new_york = (40.7033962, -74.2351462)
haversine_vector([lyon, lyon], [paris, new_york], Unit.KILOMETERS)
>> array([ 392.21725956, 6163.43638211])
SELECT
logcount, logUserID, maxlogtm,
DATEDIFF(day, maxlogtm, GETDATE()) AS daysdiff
FROM statslogsummary
WHERE ( DATEDIFF(day, maxlogtm, GETDATE() > 120)
Normally you can't refer to field aliases in the WHERE
clause. (Think of it as the entire SELECT
including aliases, is applied after the WHERE
clause.)
But, as mentioned in other answers, you can force SQL to treat SELECT
to be handled before the WHERE
clause. This is usually done with parenthesis to force logical order of operation or with a Common Table Expression (CTE):
Parenthesis/Subselect:
SELECT
*
FROM
(
SELECT
logcount, logUserID, maxlogtm,
DATEDIFF(day, maxlogtm, GETDATE()) AS daysdiff
FROM statslogsummary
) as innerTable
WHERE daysdiff > 120
Or see Adam's answer for a CTE version of the same.
Beware: The correct answer is below. This no longer works
Create a file called .ember-cli
in your project, and include in it these contents:
{
"output-path": "./location/to/your/dist/"
}
From the Wikipedia entry on Quicksort:
Quicksort also competes with mergesort, another recursive sort algorithm but with the benefit of worst-case T(nlogn) running time. Mergesort is a stable sort, unlike quicksort and heapsort, and can be easily adapted to operate on linked lists and very large lists stored on slow-to-access media such as disk storage or network attached storage. Although quicksort can be written to operate on linked lists, it will often suffer from poor pivot choices without random access. The main disadvantage of mergesort is that, when operating on arrays, it requires T(n) auxiliary space in the best case, whereas the variant of quicksort with in-place partitioning and tail recursion uses only T(logn) space. (Note that when operating on linked lists, mergesort only requires a small, constant amount of auxiliary storage.)
I think one efficient way is the use of bash arrays:
array=( $string ) # do not use quotes in order to allow word expansion
echo ${array[0]} # You can retrieve any word. Index runs from 0 to length-1
Also, you can directly read arrays in a pipe-line:
echo "word1 word2" | while read -a array; do echo "${array[0]}" ; done
The need is the possible desire for reproducible results, which may for example come from trying to debug your program, or of course from trying to redo what it does:
These two results we will "never" reproduce as I just asked for something "random":
R> sample(LETTERS, 5)
[1] "K" "N" "R" "Z" "G"
R> sample(LETTERS, 5)
[1] "L" "P" "J" "E" "D"
These two, however, are identical because I set the seed:
R> set.seed(42); sample(LETTERS, 5)
[1] "X" "Z" "G" "T" "O"
R> set.seed(42); sample(LETTERS, 5)
[1] "X" "Z" "G" "T" "O"
R>
There is vast literature on all that; Wikipedia is a good start. In essence, these RNGs are called Pseudo Random Number Generators because they are in fact fully algorithmic: given the same seed, you get the same sequence. And that is a feature and not a bug.
I resolved it by giving permission to the user on each of the directories that you're using, like so:
sudo chown user /home/user/git
and so on.
If you are ok to do transformation, you may try this.
DocumentBuilderFactory domFact = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = domFact.newDocumentBuilder();
Document doc = builder.parse(st);
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
System.out.println("XML IN String format is: \n" + writer.toString());
You can try styling with LevelSubMenuStyles
<asp:Menu ID="mainMenu" runat="server" Orientation="Horizontal"
StaticEnableDefaultPopOutImage="False">
<StaticMenuStyle CssClass="test" />
<LevelSubMenuStyles>
<asp:SubMenuStyle BackColor="#33CCFF" BorderColor="#FF9999"
Font-Underline="False" />
<asp:SubMenuStyle BackColor="#FF99FF" Font-Underline="False" />
</LevelSubMenuStyles>
<StaticMenuItemStyle CssClass="main-nav-item" />
</asp:Menu>
Of course you could use blocks as properties. But make sure they are declared as @property(copy). For example:
typedef void(^TestBlock)(void);
@interface SecondViewController : UIViewController
@property (nonatomic, copy) TestBlock block;
@end
In MRC, blocks capturing context variables are allocated in stack; they will be released when the stack frame is destroyed. If they are copied, a new block will be allocated in heap, which can be executed later on after the stack frame is poped.
You should stop the submit procedure by returning false on the onsubmit callback.
<script>
function checkRegistration(){
if(!form_valid){
alert('Given data is not correct');
return false;
}
return true;
}
</script>
<form onsubmit="return checkRegistration()"...
Here you have a fully working example. The form will submit only when you write google into input, otherwise it will return an error:
<script>
function checkRegistration(){
var form_valid = (document.getElementById('some_input').value == 'google');
if(!form_valid){
alert('Given data is incorrect');
return false;
}
return true;
}
</script>
<form onsubmit="return checkRegistration()" method="get" action="http://google.com">
Write google to go to google...<br/>
<input type="text" id="some_input" value=""/>
<input type="submit" value="google it"/>
</form>
<span id="span">HOI</span>
<script>
var span = document.getElementById("span");
console.log(span);
span.style.fontSize = "25px";
span.innerHTML = "String";
</script>
You have two errors in your code:
document.getElementById
-
This retrieves the element with an Id that is "span", you did not specify an id on the span-element.
Capitals in Javascript - Also you forgot the capital of Size.
The correct answer should be 2nCn/(n+1) for unlabelled nodes and if the nodes are labelled then (2nCn)*n!/(n+1).
I found this to be the simplest way.
>>> t = datetime.datetime.now()
>>> t
datetime.datetime(2018, 11, 30, 17, 21, 26, 606191)
>>> t = str(t).split('.')
>>> t
['2018-11-30 17:21:26', '606191']
>>> t = t[0]
>>> t
'2018-11-30 17:21:26'
>>>
I feel most people have pip installed already with Python. On Windows, one way to check for pip is to open Command Prompt and typing in:
python -m pip
If you get Usage and Commands instructions then you have it installed.
If python
was not found though, then it needs to be added to the path. Alternatively you can run the same command from within the installation directory of python.
If all is good, then this command will install BeautifulSoup easily:
python -m pip install BeautifulSoup4
Screenshot:
N' now I see I need to upgrade my pip, which I just did :)
Django has support for this, check get_or_create
person, created = Person.objects.get_or_create(name='abc')
if created:
# A new person object created
else:
# person object already exists
First zip or gzip the folders:
Use the following command:
zip -r NameYouWantForZipFile.zip foldertozip/
or
tar -pvczf BackUpDirectory.tar.gz /path/to/directory
for gzip compression use SCP:
scp [email protected]:~/serverpath/public_html ~/Desktop
I usually do this:
Const Q = """"
Dim a, g
a = "xyz"
g = "abcd " & Q & a & Q
If you need to wrap strings in quotes more often in your code and find the above approach noisy or unreadable, you can also wrap it in a function:
a = "xyz"
g = "abcd " & Q(a)
Function Q(s)
Q = """" & s & """"
End Function
You can use the .not() method:
$(".content_box a").not(".button")
Alternatively, you can also use the :not() selector:
$(".content_box a:not('.button')")
There is little difference between the two approaches, except .not()
is more readable (especially when chained) and :not()
is very marginally faster. See this Stack Overflow answer for more info on the differences.
This is exactly what bytearray
is for:
newFileByteArray = bytearray(newFileBytes)
newFile.write(newFileByteArray)
If you're using Python 3.x, you can use bytes
instead (and probably ought to, as it signals your intention better). But in Python 2.x, that won't work, because bytes
is just an alias for str
. As usual, showing with the interactive interpreter is easier than explaining with text, so let me just do that.
Python 3.x:
>>> bytearray(newFileBytes)
bytearray(b'{\x03\xff\x00d')
>>> bytes(newFileBytes)
b'{\x03\xff\x00d'
Python 2.x:
>>> bytearray(newFileBytes)
bytearray(b'{\x03\xff\x00d')
>>> bytes(newFileBytes)
'[123, 3, 255, 0, 100]'
I had this problem. Couldn't install apk via the Downloads app. However opening the apk in a file manager app allowed me to install it fine. Using OI File Manager on stock Nexus 7 4.2.1
INSERT
INTO remotedblink.remotedatabase.remoteschema.remotetable
SELECT *
FROM mytable
There is no such thing as "the end of the table" in relational databases.
For swift
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]){
++notificationNumber
application.applicationIconBadgeNumber = notificationNumber;
if let aps = userInfo["aps"] as? NSDictionary {
var message = aps["alert"]
println("my messages : \(message)")
}
}
For more solution i have completed the solution of (the great) Tiago Gouvêa exposed before only for strings and arrays
i used md_convert_encoding() function instead of utf8_encode(), it works for me : (12 hours loosed ...)
// this object return me a big array who have multiple arrays imbricated
$get_days = program::get_days($ARR, $client);
// and i use this function for well parsing what the server return *
function convert_to_utf8_recursively($dat){
if( is_string($dat) ){
return mb_convert_encoding($dat, 'UTF-8', 'UTF-8');
}
elseif( is_array($dat) ){
$ret = [];
foreach($dat as $i => $d){
$ret[$i] = convert_to_utf8_recursively($d);
}
return $ret;
}
else{
return $dat;
}
}
// use
$data = convert_to_utf8_recursively($get_days);
get radio value by name
$('input').on('className', function(event){
console.log($(this).attr('name'));
if($(this).attr('name') == "worker")
{
resetAll();
}
});
I'm new to Python, but found a way to convert
2017-05-27T07:20:18.000-04:00
to
2017-05-27T07:20:18
without downloading new utilities.
from datetime import datetime, timedelta
time_zone1 = int("2017-05-27T07:20:18.000-04:00"[-6:][:3])
>>returns -04
item_date = datetime.strptime("2017-05-27T07:20:18.000-04:00".replace(".000", "")[:-6], "%Y-%m-%dT%H:%M:%S") + timedelta(hours=-time_zone1)
I'm sure there are better ways to do this without slicing up the string so much, but this got the job done.
Javascript in a browser only really has a couple of effective scopes: function scope and global scope.
If a variable isn't in function scope, it's in global scope. And global variables are generally bad, so this is a construct to keep a library's variables to itself.
In pip
package management, there are 4 different OpenCV packages all using the same namespace, cv2
. Although they are not officially supported by OpenCV.org, they are commonly used in developers' community. You could install any of them using the following command:
pip install PACKAGE_NAME
where PACKAGE_NAME
can be
opencv-python
(only contains main modules)opencv-contrib-python
(contains both main and contrib modules)opencv-python-headless
(same as opencv-python
but without GUI functionality)opencv-contrib-python-headless
(same as opencv-contrib-python
but without GUI functionality)You should only install one of them depending on your needs. If you accidentally installed multiple of them in the same environment, you can remove them using pip uninstall
before installing the correct one again.
For more details, you can refer to the project description of OpenCV on Wheels.
@keithwyland answer is great. Here's a SCSS mixin:
@mixin font-awesome($content){
font-family: FontAwesome;
font-weight: normal;
font-style: normal;
display: inline-block;
text-decoration: inherit;
content: $content;
}
Usage:
@include font-awesome("\f054");
For what it's worth, I had the same problem but it wasn't because of an extra semicolon, it was because I'd forgotten a semicolon on the previous statement.
My situation was something like
mynamespace::MyObject otherObject
for (const auto& element: otherObject.myVector) {
// execute arbitrary code on element
//...
//...
}
From this code, my compiler kept telling me:
error: expected unqualified-id before for (const auto& element: otherObject.myVector) {
etc...
which I'd taken to mean I'd writtten the for loop wrong. Nope! I'd simply forgotten a ;
after declaring otherObject
.
If you want to have DATE as string with TIME as well. We can do like this:
//Date and Time is taking as current system Date-Time
DateTime.Now.ToString("yyyyMMdd-HHmmss");
Graphs are tough, because most non-trivial graph problems tend to require a decent amount of actual code to implement, if more than a sketch of an algorithm is required. A lot of it tends to come down to whether or not the candidate knows the shortest path and graph traversal algorithms, is familiar with cycle types and detection, and whether they know the complexity bounds. I think a lot of questions about this stuff comes down to trivia more than on the spot creative thinking ability.
I think problems related to trees tend to cover most of the difficulties of graph questions, but without as much code complexity.
I like the Project Euler problem that asks to find the most expensive path down a tree (16/67); common ancestor is a good warm up, but a lot of people have seen it. Asking somebody to design a tree class, perform traversals, and then figure out from which traversals they could rebuild a tree also gives some insight into data structure and algorithm implementation. The Stern-Brocot programming challenge is also interesting and quick to develop on a board (http://online-judge.uva.es/p/v100/10077.html).
Let's take an example. If your table has columns as follows:
<!-- ID Column -->
<ng-container matColumnDef="id" >
<th mat-header-cell *matHeaderCellDef mat-sort-header> ID </th>
<td mat-cell *matCellDef="let row"> {{row.sid}} </td>
</ng-container>
<!-- Name Column -->
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Name </th>
<td mat-cell *matCellDef="let row"> {{row.name}} </td>
</ng-container>
As this contain two columns. then we can set the width of columns using
.mat-column-<matColumnDef-value>{
width: <witdh-size>% !important;
}
for this example, we take
.mat-column-id{
width: 20% !important;
}
.mat-column-name{
width: 80% !important;
}
Is this what you are trying?
Option Explicit
Public Sub SaveWorksheetsAsCsv()
Dim WS As Worksheet
Dim SaveToDirectory As String, newName As String
SaveToDirectory = "H:\test\"
For Each WS In ThisWorkbook.Worksheets
newName = GetBookName(ThisWorkbook.Name) & "_" & WS.Name
WS.Copy
ActiveWorkbook.SaveAs SaveToDirectory & newName, xlCSV
ActiveWorkbook.Close Savechanges:=False
Next
End Sub
Function GetBookName(strwb As String) As String
GetBookName = Left(strwb, (InStrRev(strwb, ".", -1, vbTextCompare) - 1))
End Function
Following on from Sergey's answer, I think this more generic version is more in line with Fowler's Range
idea, and resolves some of the issues with that answer such as being able to have the Includes
methods within a generic class by constraining T
as IComparable<T>
. It's also immutable like what you would expect with types that extend the functionality of other value types like DateTime
.
public struct Range<T> where T : IComparable<T>
{
public Range(T start, T end)
{
Start = start;
End = end;
}
public T Start { get; }
public T End { get; }
public bool Includes(T value) => Start.CompareTo(value) <= 0 && End.CompareTo(value) >= 0;
public bool Includes(Range<T> range) => Start.CompareTo(range.Start) <= 0 && End.CompareTo(range.End) >= 0;
}
Weak Reference http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/ref/WeakReference.html
Principle: weak reference
is related to garbage collection. Normally, object having one or more reference
will not be eligible for garbage collection.
The above principle is not applicable when it is weak reference
. If an object has only weak reference with other objects, then its ready for garbage collection.
Let's look at the below example: We have an Map
with Objects where Key is reference a object.
import java.util.HashMap;
public class Test {
public static void main(String args[]) {
HashMap<Employee, EmployeeVal> aMap = new
HashMap<Employee, EmployeeVal>();
Employee emp = new Employee("Vinoth");
EmployeeVal val = new EmployeeVal("Programmer");
aMap.put(emp, val);
emp = null;
System.gc();
System.out.println("Size of Map" + aMap.size());
}
}
Now, during the execution of the program we have made emp = null
. The Map
holding the key makes no sense here as it is null
. In the above situation, the object is not garbage collected.
WeakHashMap
WeakHashMap
is one where the entries (key-to-value mappings
) will be removed when it is no longer possible to retrieve them from the Map
.
Let me show the above example same with WeakHashMap
import java.util.WeakHashMap;
public class Test {
public static void main(String args[]) {
WeakHashMap<Employee, EmployeeVal> aMap =
new WeakHashMap<Employee, EmployeeVal>();
Employee emp = new Employee("Vinoth");
EmployeeVal val = new EmployeeVal("Programmer");
aMap.put(emp, val);
emp = null;
System.gc();
int count = 0;
while (0 != aMap.size()) {
++count;
System.gc();
}
System.out.println("Took " + count
+ " calls to System.gc() to result in weakHashMap size of : "
+ aMap.size());
}
}
Output: Took 20 calls to System.gc()
to result in aMap size
of : 0.
WeakHashMap
has only weak references to the keys, not strong references like other Map
classes. There are situations which you have to take care when the value or key is strongly referenced though you have used WeakHashMap
. This can avoided by wrapping the object in a WeakReference.
import java.lang.ref.WeakReference;
import java.util.HashMap;
public class Test {
public static void main(String args[]) {
HashMap<Employee, EmployeeVal> map =
new HashMap<Employee, EmployeeVal>();
WeakReference<HashMap<Employee, EmployeeVal>> aMap =
new WeakReference<HashMap<Employee, EmployeeVal>>(
map);
map = null;
while (null != aMap.get()) {
aMap.get().put(new Employee("Vinoth"),
new EmployeeVal("Programmer"));
System.out.println("Size of aMap " + aMap.get().size());
System.gc();
}
System.out.println("Its garbage collected");
}
}
Soft References.
Soft Reference
is slightly stronger that weak reference. Soft reference allows for garbage collection, but begs the garbage collector to clear it only if there is no other option.
The garbage collector does not aggressively collect softly reachable objects the way it does with weakly reachable ones -- instead it only collects softly reachable objects if it really "needs" the memory. Soft references are a way of saying to the garbage collector, "As long as memory isn't too tight, I'd like to keep this object around. But if memory gets really tight, go ahead and collect it and I'll deal with that." The garbage collector is required to clear all soft references before it can throw OutOfMemoryError
.
As mentioned in a different post Read .txt file from workspace groovy script in Jenkins I was struggling to make it work for the pom modules for a file in the workspace, in the Extended Choice Parameter. Here is my solution with the printlns:
import groovy.util.XmlSlurper
import java.util.Map
import jenkins.*
import jenkins.model.*
import hudson.*
import hudson.model.*
try{
//get Jenkins instance
def jenkins = Jenkins.instance
//get job Item
def item = jenkins.getItemByFullName("The_JOB_NAME")
println item
// get workspacePath for the job Item
def workspacePath = jenkins.getWorkspaceFor (item)
println workspacePath
def file = new File(workspacePath.toString()+"\\pom.xml")
def pomFile = new XmlSlurper().parse(file)
def pomModules = pomFile.modules.children().join(",")
return pomModules
} catch (Exception ex){
println ex.message
}
function myFunction(e) {
var x = e.clientX - e.currentTarget.offsetLeft ;
var y = e.clientY - e.currentTarget.offsetTop ;
}
this works ok!
Ugly, (and doesn't use your method call above) but works:
echo 'First day of the month: ' . date('m/d/y h:i a',(strtotime('this month',strtotime(date('m/01/y')))));
The difflib library is useful for this, and comes in the standard library. I like the unified diff format.
http://docs.python.org/2/library/difflib.html#difflib.unified_diff
import difflib
import sys
with open('/tmp/hosts0', 'r') as hosts0:
with open('/tmp/hosts1', 'r') as hosts1:
diff = difflib.unified_diff(
hosts0.readlines(),
hosts1.readlines(),
fromfile='hosts0',
tofile='hosts1',
)
for line in diff:
sys.stdout.write(line)
Outputs:
--- hosts0
+++ hosts1
@@ -1,5 +1,4 @@
one
two
-dogs
three
And here is a dodgy version that ignores certain lines. There might be edge cases that don't work, and there are surely better ways to do this, but maybe it will be good enough for your purposes.
import difflib
import sys
with open('/tmp/hosts0', 'r') as hosts0:
with open('/tmp/hosts1', 'r') as hosts1:
diff = difflib.unified_diff(
hosts0.readlines(),
hosts1.readlines(),
fromfile='hosts0',
tofile='hosts1',
n=0,
)
for line in diff:
for prefix in ('---', '+++', '@@'):
if line.startswith(prefix):
break
else:
sys.stdout.write(line[1:])
It was a problem in Instagram Developer Console. max_id
and min_id
doesn't work there.
Matt Zeunert's version with use arraw function (ES6)
const nums = a.split(',').map(x => parseInt(x, 10));
cat table |
perl -ne '/\d+\s+(\d+)\s+(\S+)/ && print "".**int**(log($1)/log(2))."\t$2\n";'
Approach: 1
Given original string
format: 2019/03/04 00:08:48
you can use
updated_df = df['timestamp'].astype('datetime64[ns]')
The result will be in this datetime
format: 2019-03-04 00:08:48
Approach: 2
updated_df = df.astype({'timestamp':'datetime64[ns]'})
I couldn't get The DataRowAttribute
to work in Visual Studio 2015, and this is what I ended up with:
[TestClass]
public class Tests
{
private Foo _toTest;
[TestInitialize]
public void Setup()
{
this._toTest = new Foo();
}
[TestMethod]
public void ATest()
{
this.Perform_ATest(1, 1, 2);
this.Setup();
this.Perform_ATest(100, 200, 300);
this.Setup();
this.Perform_ATest(817001, 212, 817213);
this.Setup();
}
private void Perform_ATest(int a, int b, int expected)
{
// Obviously this would be way more complex...
Assert.IsTrue(this._toTest.Add(a,b) == expected);
}
}
public class Foo
{
public int Add(int a, int b)
{
return a + b;
}
}
The real solution here is to just use NUnit (unless you're stuck in MSTest like I am in this particular instance).
Perl string match can also be used for a simple yes/no.
my @foo=("hello", "world", "foo", "bar");
if ("@foo" =~ /\bhello\b/){
print "found";
}
else{
print "not found";
}
Plese try this:
var sizeInKB = input.files[0].size/1024; //Normally files are in bytes but for KB divide by 1024 and so on
var sizeLimit= 30;
if (sizeInKB >= sizeLimit) {
alert("Max file size 30KB");
return false;
}
I had the same question, and I tested 3 main solution :
(df != null) && (df.count > 0)
df.head(1).isEmpty()
as @hulin003 suggestdf.rdd.isEmpty()
as @Justin Pihony suggestand of course the 3 works, however in term of perfermance, here is what I found, when executing the these methods on the same DF in my machine, in terme of execution time :
therefore I think that the best solution is df.rdd.isEmpty()
as @Justin Pihony suggest
Paul Dardeau answer is perfect, the only thing is, what if all the files inside those folders are not PDF files and you want to grab it all no matter the extension. Well just change it to
find . -name "*.*" -type f -exec cp {} ./pdfsfolder \;
Just to sum up!
Here's a script to remove an image and all the images that depend on it.
#!/bin/bash
if [[ $# -lt 1 ]]; then
echo must supply image to remove;
exit 1;
fi;
get_image_children ()
{
ret=()
for i in $(docker image ls -a --no-trunc -q); do
#>&2 echo processing image "$i";
#>&2 echo parent is $(docker image inspect --format '{{.Parent}}' "$i")
if [[ "$(docker image inspect --format '{{.Parent}}' "$i")" == "$1" ]]; then
ret+=("$i");
fi;
done;
echo "${ret[@]}";
}
realid=$(docker image inspect --format '{{.Id}}' "$1")
if [[ -z "$realid" ]]; then
echo "$1 is not a valid image.";
exit 2;
fi;
images_to_remove=("$realid");
images_to_process=("$realid");
while [[ "${#images_to_process[@]}" -gt 0 ]]; do
children_to_process=();
for i in "${!images_to_process[@]}"; do
children=$(get_image_children "${images_to_process[$i]}");
if [[ ! -z "$children" ]]; then
# allow word splitting on the children.
children_to_process+=($children);
fi;
done;
if [[ "${#children_to_process[@]}" -gt 0 ]]; then
images_to_process=("${children_to_process[@]}");
images_to_remove+=("${children_to_process[@]}");
else
#no images have any children. We're done creating the graph.
break;
fi;
done;
echo images_to_remove = "$(printf %s\n "${images_to_remove[@]}")";
indices=(${!images_to_remove[@]});
for ((i="${#indices[@]}" - 1; i >= 0; --i)) ; do
image_to_remove="${images_to_remove[indices[i]]}"
if [[ "${image_to_remove:0:7}" == "sha256:" ]]; then
image_to_remove="${image_to_remove:7}";
fi
echo removing image "$image_to_remove";
docker rmi "$image_to_remove";
done
In ES6 you can use Math.sign function to determine if,
1. its +ve no
2. its -ve no
3. its zero (0)
4. its NaN
console.log(Math.sign(1)) // prints 1
console.log(Math.sign(-1)) // prints -1
console.log(Math.sign(0)) // prints 0
console.log(Math.sign("abcd")) // prints NaN
To show leading zeros infront of hours, minutes and seconds use below modified code. The trick here is we are converting (or more accurately formatting) integer into string so that it shows leading zero whenever applicable :
public String convertTimeWithTimeZome(long time) {
Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("UTC"));
cal.setTimeInMillis(time);
String curTime = String.format("%02d:%02d:%02d", cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND));
return curTime;
}
Result would be like : 00:01:30
You need to follow below 2 steps instructions:
[Issue] remote: Hint: To automatically insert Change-Id, install the hook:
1) gitdir=$(git rev-parse --git-dir);
2) scp -p -P 29418 <username>@gerrit.xyz.se:hooks/commit-msg ${gitdir}/hooks/
normally $gitdir = ".git". You need to update the username and the Gerrit link.
As mentioned in the earlier comment, stacked bar chart does the trick, though the data needs to be setup differently.(See image below)
Duration column = End - Start
I was facing the same issue for one of my PhoneGap project (Android studio 3.0.1). To resolve this I have followed, the following step
1) Right click on Project name (In my Case android), select "Open Module Settings"
2) Select modules (android and CordovaLib)
3) Click properties on top
4) Chose Compile SDK version (I have chosen API 26: Android 8.0 )
5) Choose Build Tools Version (I have chosen 26.0.2)
6) Source Compatibility ( 1.6)
7) Target Compatibility ( 1.6)
Click Ok and rebuild project.
The following link shows my setting for step I have followed
https://app.box.com/s/o11xc8dy0c2c7elsaoppa0kwe1d94ogh https://app.box.com/s/ofdcg0a8n0zalumvpyju58he402ag1th
I think Disjoint Set is pretty nifty for cases when you need to divide a bunch of items into distinct sets and query membership. Good implementation of the Union and Find operations result in amortized costs that are effectively constant (inverse of Ackermnan's Function, if I recall my data structures class correctly).
the same problem make crazy.finally, i find put the 'import xxx.h' in implementation instead of interface can fix the problem.And if you use Cocoapods to manager your project.you can add
s.user_target_xcconfig = { 'CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES' => 'YES' }
in your 'xxx.podspec' file.
I fixed this issue on Windows 10 by uninstalling node from Add or remove programs -> Node.js
Then I installed version 11.15.0 from https://nodejs.org/download/release/v11.15.0/
Choose node-v11.15.0-x64.msi if your running windows 64bit.
You can't multiply string and float.instead of you try as below.it works fine
totalAmount = salesAmount * float(salesTax)
You'll do it the same way you would apply a css selector. For instanse you can do
$("#mydiv > .myclass")
or
$("#mydiv .myclass")
The last one will match every myclass inside myDiv, including myclass inside myclass.
Update for Android Studio 1.0
Since Android Studio 1.0 was released (and a lot of versions between v1.0 and one of the firsts from the time of my previous answer) some things has changed.
My description is focused on adding external library project by hand via Gradle files (for better understanding the process). If you want to add a library via Android Studio creator just check the answer below with visual guide (there are some differences between Android Studio 1.0 and those from screenshots, but the process is very similar).
Before you start adding a library to your project by hand, consider adding the external dependency. It won’t mess in your project structure. Almost every well-known Android library is available in a Maven repository and its installation takes only one line of code in the app/build.gradle
file:
dependencies {
compile 'com.jakewharton:butterknife:6.0.0'
}
Adding the library
Here is the full process of adding external Android library to our project:
HelloWorld/ app/ - build.gradle // local Gradle configuration (for app only) ... - build.gradle // Global Gradle configuration (for whole project) - settings.gradle - gradle.properties ...
HelloWorld/
), create new folder: /libs
in which we’ll place our external libraries (this step is not required - only for keeping a cleaner project structure)./libs
folder. In this example I used PagerSlidingTabStrip library (just download ZIP from GitHub, rename library directory to „PagerSlidingTabStrip" and copy it). Here is the new structure of our project:HelloWorld/ app/ - build.gradle // Local Gradle configuration (for app only) ... libs/ PagerSlidingTabStrip/ - build.gradle // Local Gradle configuration (for library only) - build.gradle // Global Gradle configuration (for whole project) - settings.gradle - gradle.properties ...
Edit settings.gradle by adding your library to include
. If you use a custom path like I did, you have also to define the project directory for our library. A whole settings.gradle should look like below:
include ':app', ':PagerSlidingTabStrip'
project(':PagerSlidingTabStrip').projectDir = new File('libs/PagerSlidingTabStrip')
5.1 If you face "Default Configuration" error, then try this instead of step 5,
include ':app'
include ':libs:PagerSlidingTabStrip'
In app/build.gradle
add our library project as an dependency:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:21.0.3'
compile project(":PagerSlidingTabStrip")
}
6.1. If you followed step 5.1, then follow this instead of 6,
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:21.0.3'
compile project(":libs:PagerSlidingTabStrip")
}
If your library project doesn’t have build.gradle
file you have to create it manually. Here is example of that file:
apply plugin: 'com.android.library'
dependencies {
compile 'com.android.support:support-v4:21.0.3'
}
android {
compileSdkVersion 21
buildToolsVersion "21.1.2"
defaultConfig {
minSdkVersion 14
targetSdkVersion 21
}
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
res.srcDirs = ['res']
}
}
}
Additionally you can create a global configuration for your project which will contain SDK versions and build tools version for every module to keep consistency. Just edit gradle.properties
file and add lines:
ANDROID_BUILD_MIN_SDK_VERSION=14
ANDROID_BUILD_TARGET_SDK_VERSION=21
ANDROID_BUILD_TOOLS_VERSION=21.1.3
ANDROID_BUILD_SDK_VERSION=21
Now you can use it in your build.gradle
files (in app and libraries modules) like below:
//...
android {
compileSdkVersion Integer.parseInt(project.ANDROID_BUILD_SDK_VERSION)
buildToolsVersion project.ANDROID_BUILD_TOOLS_VERSION
defaultConfig {
minSdkVersion Integer.parseInt(project.ANDROID_BUILD_MIN_SDK_VERSION)
targetSdkVersion Integer.parseInt(project.ANDROID_BUILD_TARGET_SDK_VERSION)
}
}
//...
That’s all. Just click‚ synchronise the project with the Gradle’ icon . Your library should be available in your project.
Google I/O 2013 - The New Android SDK Build System is a great presentation about building Android apps with Gradle Build System: As Xavier Ducrohet said:
Android Studio is all about editing, and debugging and profiling. It's not about building any more.
At the beginning it may be little bit confusing (especially for those, who works with Eclipse and have never seen the ant - like me ;) ), but at the end Gradle gives us some great opportunities and it worth to learn this build system.
var rad_id = document.getElementById('<%=radio_btn_lst.ClientID %>');
var radio = rad_id.getElementsByTagName("input");
radio[0].checked = true;
//this for javascript in asp.net try this in .aspx page
// if you select other radiobutton increase [0] to [1] or [2] like this
Hopefully this helps someone out there.
For platform I was specifying "Any CPU", changed it to "AnyCPU" and that fixed the problem.
msbuild C:\Users\Project\Project.publishproj /p:Platform="AnyCPU" /p:DeployOnBuild=true /p:PublishProfile=local /p:Configuration=Debug
If you look at your .csproj file you'll see the correct platform name to use.
You can skip the complex Canvas manipulation and do this entirely with Drawables, using LayerDrawable
. You have one of two choices: You can either define it in XML then simply set the image, or you can configure a LayerDrawable
dynamically in code.
Solution #1 (via XML):
Create a new Drawable XML file, let's call it layer.xml
:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/t" />
<item android:drawable="@drawable/tt" />
</layer-list>
Now set the image using that Drawable:
testimage.setImageDrawable(getResources().getDrawable(R.layout.layer));
Solution #2 (dynamic):
Resources r = getResources();
Drawable[] layers = new Drawable[2];
layers[0] = r.getDrawable(R.drawable.t);
layers[1] = r.getDrawable(R.drawable.tt);
LayerDrawable layerDrawable = new LayerDrawable(layers);
testimage.setImageDrawable(layerDrawable);
(I haven't tested this code so there may be a mistake, but this general outline should work.)
A web service endpoint is the URL that another program would use to communicate with your program. To see the WSDL you add ?wsdl
to the web service endpoint URL.
Web services are for program-to-program interaction, while web pages are for program-to-human interaction.
So:
Endpoint is: http://www.blah.com/myproject/webservice/webmethod
Therefore,
WSDL is: http://www.blah.com/myproject/webservice/webmethod?wsdl
To expand further on the elements of a WSDL, I always find it helpful to compare them to code:
A WSDL has 2 portions (physical & abstract).
Physical Portion:
Definitions - variables - ex: myVar, x, y, etc.
Types - data types - ex: int, double, String, myObjectType
Operations - methods/functions - ex: myMethod(), myFunction(), etc.
Messages - method/function input parameters & return types
Porttypes - classes (i.e. they are a container for operations) - ex: MyClass{}, etc.
Abstract Portion:
Binding - these connect to the porttypes and define the chosen protocol for communicating with this web service. - a protocol is a form of communication (so text/SMS, vs. phone vs. email, etc.).
Service - this lists the address where another program can find your web service (i.e. your endpoint).
If you want to do this via the designer you can do it by following the instructions here "Save changes is not permitted" when changing an existing column to be nullable
f.readlines() returns a list that contains each line as an item in the list
if you want eachline to be split(",") you can use list comprehensions
[ list.split(",") for line in file ]
I think you might be better off using PHP's inbuilt filters - in this particular case:
It can return a true or false when supplied with the FILTER_VALIDATE_EMAIL
param.
I want to give a shoutout for using re
module for this. Specially in the case of case sensitivity.
We use the option re.IGNORECASE while compiling the regex for use of in production environments with large amounts of data.
>>> import re
>>> m = ['isalnum','isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'ISALNUM', 'ISALPHA', 'ISDIGIT', 'ISLOWER', 'ISSPACE', 'ISTITLE', 'ISUPPER']
>>>
>>>
>>> pattern = re.compile('is')
>>>
>>> [word for word in m if pattern.match(word)]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']
However try to always use the in
operator for string comparison as detailed in this post
faster-operation-re-match-or-str
Also detailed in the one of the best books to start learning python with
In my case, mismatch of version of two libraries.
I am using angular 7.0.0 and installed
"@swimlane/ngx-dnd": "^8.0.0"
and this caused the problem. Reverting this library to
"@swimlane/ngx-dnd": "6.0.0"
worked for me.
CPython actually implements the datetime module using both a pure-Python Lib/datetime.py and a C-optimized Modules/_datetimemodule.c. The C-optimized version cannot be patched but the pure-Python version can.
At the bottom of the pure-Python implementation in Lib/datetime.py is this code:
try:
from _datetime import * # <-- Import from C-optimized module.
except ImportError:
pass
This code imports all the C-optimized definitions and effectively replaces all the pure-Python definitions. We can force CPython to use the pure-Python implementation of the datetime module by doing:
import datetime
import importlib
import sys
sys.modules["_datetime"] = None
importlib.reload(datetime)
By setting sys.modules["_datetime"] = None
, we tell Python to ignore the C-optimized module. Then we reload the module which causes the import from _datetime
to fail. Now the pure-Python definitions remain and can be patched normally.
If you're using Pytest then include the snippet above in conftest.py and you can patch datetime
objects normally.
SELECT *, COUNT(*) FROM my_table
is not what you want, and it's not really valid SQL, you have to group by all the columns that's not an aggregate.
You'd want something like
SELECT somecolumn,someothercolumn, COUNT(*)
FROM my_table
GROUP BY somecolumn,someothercolumn
const str = "abc's@thy#^g&test#s";
console.log(str.replace(/[^a-zA-Z ]/g, ""));
_x000D_
Here is another simple solution using sed.
$ sed -i 's/all.*/& anotherthing/g' filename.txt
Explanation:
all.* means all lines started with 'all'.
& represent the match (ie the complete line that starts with 'all')
then sed replace the former with the later and appends the ' anotherthing' word