$_SERVER['QUERY_STRING']
contains the data that you are looking for.
DOCUMENTATION
Following on from my comment to the answer @bobby posted, here is the code I would use:
function parseQuery(str)
{
if(typeof str != "string" || str.length == 0) return {};
var s = str.split("&");
var s_length = s.length;
var bit, query = {}, first, second;
for(var i = 0; i < s_length; i++)
{
bit = s[i].split("=");
first = decodeURIComponent(bit[0]);
if(first.length == 0) continue;
second = decodeURIComponent(bit[1]);
if(typeof query[first] == "undefined") query[first] = second;
else if(query[first] instanceof Array) query[first].push(second);
else query[first] = [query[first], second];
}
return query;
}
This code takes in the querystring provided (as 'str') and returns an object. The string is split on all occurances of &, resulting in an array. the array is then travsersed and each item in it is split by "=". This results in sub arrays wherein the 0th element is the parameter and the 1st element is the value (or undefined if no = sign). These are mapped to object properties, so for example the string "hello=1&another=2&something" is turned into:
{
hello: "1",
another: "2",
something: undefined
}
In addition, this code notices repeating reoccurances such as "hello=1&hello=2" and converts the result into an array, eg:
{
hello: ["1", "2"]
}
You'll also notice it deals with cases in whih the = sign is not used. It also ignores if there is an equal sign straight after an & symbol.
A bit overkill for the original question, but a reusable solution if you ever need to work with querystrings in javascript :)
I use regular expressions a lot, but not for that.
It seems easier and more efficient to me to read the query string once in my application, and build an object from all the key/value pairs like:
var search = function() {
var s = window.location.search.substr(1),
p = s.split(/\&/), l = p.length, kv, r = {};
if (l === 0) {return false;}
while (l--) {
kv = p[l].split(/\=/);
r[kv[0]] = decodeURIComponent(kv[1] || '') || true;
}
return r;
}();
For a URL like http://domain.com?param1=val1¶m2=val2
you can get their value later in your code as search.param1
and search.param2
.
Here is a shorter version that takes care of
Code:
var setQueryParameter = function(uri, key, value) {
var re = new RegExp("([?&])("+ key + "=)[^&#]*", "g");
if (uri.match(re))
return uri.replace(re, '$1$2' + value);
// need to add parameter to URI
var paramString = (uri.indexOf('?') < 0 ? "?" : "&") + key + "=" + value;
var hashIndex = uri.indexOf('#');
if (hashIndex < 0)
return uri + paramString;
else
return uri.substring(0, hashIndex) + paramString + uri.substring(hashIndex);
}
The regex description can be found here.
NOTE: This solution is based on @amateur answer, but with many improvements.
It's shocking how many of these upvoted/accepted answers are incomplete, so they don't answer the OP's question, after 7 years!
If you are on a page with URL like: http://example.com/directory/file.php?paramater=value
...and you would like to return just: http://example.com/directory/file.php
then use:
echo $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'];
Very Straightforward!
function parseQueryString(){
var assoc = {};
var keyValues = location.search.slice(1).split('&');
var decode = function(s){
return decodeURIComponent(s.replace(/\+/g, ' '));
};
for (var i = 0; i < keyValues.length; ++i) {
var key = keyValues[i].split('=');
if (1 < key.length) {
assoc[decode(key[0])] = decode(key[1]);
}
}
return assoc;
}
I found this article enlightening : Javascript Madness: Query String Parsing
I found it when I was trying to undersand why decodeURIComponent was not decoding '+' correctly. Here is an extract:
String: "A + B"
Expected Query String Encoding: "A+%2B+B"
escape("A + B") = "A%20+%20B" Wrong!
encodeURI("A + B") = "A%20+%20B" Wrong!
encodeURIComponent("A + B") = "A%20%2B%20B" Acceptable, but strange
Encoded String: "A+%2B+B"
Expected Decoding: "A + B"
unescape("A+%2B+B") = "A+++B" Wrong!
decodeURI("A+%2B+B") = "A+++B" Wrong!
decodeURIComponent("A+%2B+B") = "A+++B" Wrong!
I came here looking for the query string, not how to get values from the query string.
request.query_string
returns the URL parameters as raw byte string (Ref 1).
Example of using request.query_string
:
from flask import Flask, request
app = Flask(__name__)
@app.route('/data', methods=['GET'])
def get_query_string():
return request.query_string
if __name__ == '__main__':
app.run(debug=True)
Output:
References:
Parameters are key-value pairs that can appear inside URL path, and start with a semicolon character (;
).
Query string appears after the path (if any) and starts with a question mark character (?
).
Both parameters and query string contain key-value pairs.
In a GET
request, parameters appear in the URL itself:
<scheme>://<username>:<password>@<host>:<port>/<path>;<parameters>?<query>#<fragment>
In a POST
request, parameters can appear in the URL itself, but also in the datastream (as known as content).
Query string is always a part of the URL.
Parameters can be buried in form-data
datastream when using POST method so they may not appear in the URL. Yes a POST
request can define parameters as form data and in the URL, and this is not inconsistent because parameters can have several values.
I've found no explaination for this behavior so far. I guess it might be useful sometimes to "unhide" parameters from a POST
request, or even let the code handling a GET
request share some parts with the code handling a POST
. Of course this can work only with server code supporting parameters in a URL.
Until you get better insights, I suggest you to use parameters only in form-data
datastream of POST
requests.
Sources:
Modification of great John solution, solve:
space after one of piece in parameter
ALTER FUNCTION [dbo].[fn_MVParam]
(@RepParam nvarchar(4000), @Delim char(1)= ',')
RETURNS @Values TABLE (Param nvarchar(4000))AS
BEGIN
//2 quotes error
set @RepParam = replace(@RepParam,char(39)+char(39),CHAR(39))
DECLARE @chrind INT
DECLARE @Piece nvarchar(100)
SELECT @chrind = 1
WHILE @chrind > 0
BEGIN
SELECT @chrind = CHARINDEX(@Delim,@RepParam)
IF @chrind > 0
SELECT @Piece = LEFT(@RepParam,@chrind - 1)
ELSE
SELECT @Piece = @RepParam
INSERT @Values(Param) VALUES(CAST(@Piece AS VARCHAR(300)))
//space after one of piece in parameter: LEN(@RepParam + '1')-1
SELECT @RepParam = RIGHT(@RepParam,LEN(@RepParam + '1')-1 - @chrind)
IF LEN(@RepParam) = 0 BREAK
END
RETURN
END
//user113716 code is working but i altered as below. it will work if your URL contain "?" mark or not
//replace URL in browser
if(window.location.href.indexOf("?") > -1) {
var newUrl = refineUrl();
window.history.pushState("object or string", "Title", "/"+newUrl );
}
function refineUrl()
{
//get full url
var url = window.location.href;
//get url after/
var value = url = url.slice( 0, url.indexOf('?') );
//get the part after before ?
value = value.replace('@System.Web.Configuration.WebConfigurationManager.AppSettings["BaseURL"]','');
return value;
}
My solution in Python with sqlite3:
import sqlite3
import re
def match(expr, item):
return re.match(expr, item) is not None
conn = sqlite3.connect(':memory:')
conn.create_function("MATCHES", 2, match)
cursor = conn.cursor()
cursor.execute("SELECT MATCHES('^b', 'busy');")
print cursor.fetchone()[0]
cursor.close()
conn.close()
If regex matches, the output would be 1, otherwise 0.
I think it is way more safer to rely on the browser than any ingenious regex:
const parseUrl = function(url) { _x000D_
const a = document.createElement('a')_x000D_
a.href = url_x000D_
return {_x000D_
protocol: a.protocol ? a.protocol : null,_x000D_
hostname: a.hostname ? a.hostname : null,_x000D_
port: a.port ? a.port : null,_x000D_
path: a.pathname ? a.pathname : null,_x000D_
query: a.search ? a.search : null,_x000D_
hash: a.hash ? a.hash : null,_x000D_
host: a.host ? a.host : null _x000D_
}_x000D_
}_x000D_
_x000D_
console.log( parseUrl(window.location.href) ) //stacksnippet_x000D_
//to obtain a query_x000D_
console.log( parseUrl( 'https://example.com?qwery=this').query )
_x000D_
Thou shalt always encode URLs.
Here is how Ruby encodes your URL:
irb(main):008:0> CGI.escape "a.com/a+b"
=> "a.com%2Fa%2Bb"
http://localhost:9200/foo/_search/?size=1000&pretty=1
you will need to specify size query parameter as the default is 10
Something else to check: if your site is using MVC, this can happen if you added [Authorize] to your login controller class. It can't access the login method because it's not authorized so it redirects to the login method --> boom.
RFC 2616 (Hypertext Transfer Protocol — HTTP/1.1) states there is no limit to the length of a query string (section 3.2.1). RFC 3986 (Uniform Resource Identifier — URI) also states there is no limit, but indicates the hostname is limited to 255 characters because of DNS limitations (section 2.3.3).
While the specifications do not specify any maximum length, practical limits are imposed by web browser and server software. Based on research which is unfortunately no longer available on its original site (it leads to a shady seeming loan site) but which can still be found at Internet Archive Of Boutell.com:
Microsoft Internet Explorer (Browser)
Microsoft states that the maximum length of a URL in Internet Explorer is 2,083 characters, with no more than 2,048 characters in the path portion of the URL. Attempts to use URLs longer than this produced a clear error message in Internet Explorer.
Microsoft Edge (Browser)
The limit appears to be around 81578 characters. See URL Length limitation of Microsoft Edge
Chrome
It stops displaying the URL after 64k characters, but can serve more than 100k characters. No further testing was done beyond that.
Firefox (Browser)
After 65,536 characters, the location bar no longer displays the URL in Windows Firefox 1.5.x. However, longer URLs will work. No further testing was done after 100,000 characters.
Safari (Browser)
At least 80,000 characters will work. Testing was not tried beyond that.
Opera (Browser)
At least 190,000 characters will work. Stopped testing after 190,000 characters. Opera 9 for Windows continued to display a fully editable,
copyable and pasteable URL in the location bar even at 190,000 characters.
Apache (Server)
Early attempts to measure the maximum URL length in web browsers bumped into a server URL length limit of approximately 4,000 characters, after which Apache produces a "413 Entity Too Large" error. The current up to date Apache build found in Red Hat Enterprise Linux 4 was used. The official Apache documentation only mentions an 8,192-byte limit on an individual field in a request.
Microsoft Internet Information Server (Server)
The default limit is 16,384 characters (yes, Microsoft's web server accepts longer URLs than Microsoft's web browser). This is configurable.
Perl HTTP::Daemon (Server)
Up to 8,000 bytes will work. Those constructing web application servers with Perl's HTTP::Daemon module will encounter a 16,384 byte limit on the combined size of all HTTP request headers. This does not include POST-method form data, file uploads, etc., but it does include the URL. In practice this resulted in a 413 error when a URL was significantly longer than 8,000 characters. This limitation can be easily removed. Look for all occurrences of 16x1024 in Daemon.pm and replace them with a larger value. Of course, this does increase your exposure to denial of service attacks.
I would go with this small but complete library to handle urls in js:
If you want the quick and dirty way and don't worry about XSS attack, use params.merge
to keep previous parameters. e.g.
<%= link_to 'Link', params.merge({:per_page => 20}) %>
see: https://stackoverflow.com/a/4174493/445908
Otherwise , check this answer: params.merge and cross site scripting
This is a solution that will work for .NET backends out of the box. I have taken the primary answer of this thread and updated it to fit our .NET needs.
function objectToQuerystring(params) {
var result = '';
function convertJsonToQueryString(data, progress, name) {
name = name || '';
progress = progress || '';
if (typeof data === 'object') {
Object.keys(data).forEach(function (key) {
var value = data[key];
if (name == '') {
convertJsonToQueryString(value, progress, key);
} else {
if (isNaN(parseInt(key))) {
convertJsonToQueryString(value, progress, name + '.' + key);
} else {
convertJsonToQueryString(value, progress, name + '[' + key+ ']');
}
}
})
} else {
result = result ? result.concat('&') : result.concat('?');
result = result.concat(`${name}=${data}`);
}
}
convertJsonToQueryString(params);
return result;
}
Use this
file_get_contents($my_url,null,null);
I've used the following JavaScript library with great success:
https://github.com/balupton/jquery-history
It supports the HTML5 history API as well as a fallback method (using #) for older browsers.
This library is essentially a polyfill around `history.pushState'.
You can use with express ^4.15.4:
var express = require('express'),
router = express.Router();
router.get('/', function (req, res, next) {
console.log(req.query);
});
Hope this helps.
Just use which sounds better. I'd use the first approach, though, because it seems to have fewer operations.
Here is a simple solution using the query-string
library.
const qs = require('query-string')
function addQuery(key, value) {
const q = qs.parse(location.search)
const url = qs.stringifyUrl(
{
url: location.pathname,
query: {
...q,
[key]: value,
},
},
{ skipEmptyString: true }
);
window.location.href = url
// if you are using Turbolinks
// add this: Turbolinks.visit(url)
}
// Usage
addQuery('page', 2)
If you are using react
without react-router
export function useAddQuery() {
const location = window.location;
const addQuery = useCallback(
(key, value) => {
const q = qs.parse(location.search);
const url = qs.stringifyUrl(
{
url: location.pathname,
query: {
...q,
[key]: value,
},
},
{ skipEmptyString: true }
);
window.location.href = url
},
[location]
);
return { addQuery };
}
// Usage
const { addQuery } = useAddQuery()
addQuery('page', 2)
If you are using react
with react-router
export function useAddQuery() {
const location = useLocation();
const history = useHistory();
const addQuery = useCallback(
(key, value) => {
let pathname = location.pathname;
let searchParams = new URLSearchParams(location.search);
searchParams.set(key, value);
history.push({
pathname: pathname,
search: searchParams.toString()
});
},
[location, history]
);
return { addQuery };
}
// Usage
const { addQuery } = useAddQuery()
addQuery('page', 2)
PS: qs
is the import from query-string
module.
Here is a simple solution if you are using Laravel:
Str::before($request->getRequestUri(), '?')
Given this route
app.get('/hi/:param1', function(req,res){} );
and given this URL
http://www.google.com/hi/there?qs1=you&qs2=tube
You will have:
req.query
{
qs1: 'you',
qs2: 'tube'
}
req.params
{
param1: 'there'
}
Post.getInitialProps = async function(context) {_x000D_
_x000D_
const data = {}_x000D_
try{_x000D_
data.queryParam = queryString.parse(context.req.url.split('?')[1]);_x000D_
}catch(err){_x000D_
data.queryParam = queryString.parse(window.location.search);_x000D_
}_x000D_
return { data };_x000D_
};
_x000D_
Try like this.It should work
Response.Redirect(String.Format("yourpage.aspx?strId={0}&strName={1}&strDate{2}", Server.UrlEncode(strId), Server.UrlEncode(strName),Server.UrlEncode(strDate)));
Solution from 2020
We have: http://example.com?sent=yes
let searchParams = new URLSearchParams(window.location.search)
Does sent exist?
searchParams.has('sent') // true
Is it equal to "yes"?
let param = searchParams.get('sent')
and then just compare it.
Modern browsers provide URLSearchParams
interface to work with search params. Which has delete
method that removes param by name.
if (typeof URLSearchParams !== 'undefined') {_x000D_
const params = new URLSearchParams('param1=1¶m2=2¶m3=3')_x000D_
_x000D_
console.log(params.toString())_x000D_
_x000D_
params.delete('param2')_x000D_
_x000D_
console.log(params.toString())_x000D_
_x000D_
} else {_x000D_
console.log(`Your browser ${navigator.appVersion} does not support URLSearchParams`)_x000D_
}
_x000D_
You can use these functions:
function shareOnFB(){
var url = "https://www.facebook.com/sharer/sharer.php?u=https://yoururl.com&t=your message";
window.open(url, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=300,width=600');
return false;
}
function shareOntwitter(){
var url = 'https://twitter.com/intent/tweet?url=URL_HERE&via=getboldify&text=yourtext';
TwitterWindow = window.open(url, 'TwitterWindow',width=600,height=300);
return false;
}
function shareOnGoogle(){
var url = "https://plus.google.com/share?url=https://yoururl.com";
window.open(url, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=350,width=480');
return false;
}
<a onClick="shareOnFB()"> Facebook </a>
<a onClick="shareOntwitter()"> Twitter </a>
<a onClick="shareOnGoogle()"> Google </a>
You want $.param()
: http://api.jquery.com/jQuery.param/
Specifically, you want this:
var data = { one: 'first', two: 'second' };
var result = $.param(data);
When given something like this:
{a: 1, b : 23, c : "te!@#st"}
$.param
will return this:
a=1&b=23&c=te!%40%23st
I am afraid there is no way to get the query string parameters parsed separately from the post parameters. BTW the fact that such API absent may mean that probably you should check your design. Why are you using query string when sending POST? If you really want to send more data into URL use REST-like convention, e.g. instead of sending
http://mycompany.com/myapp/myservlet?first=11&second=22
say:
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(top.window.location.href);
return (results !== null) ? results[1] : 0;
}
$.urlParam("key");
So, after checking out the express reference, I found that req.query.color
would return me the value I'm looking for.
req.params refers to items with a ':' in the URL and req.query refers to items associated with the '?'
Example:
GET /something?color1=red&color2=blue
Then in express, the handler:
app.get('/something', (req, res) => {
req.query.color1 === 'red' // true
req.query.color2 === 'blue' // true
})
Try this ...
PropertyInfo isreadonly =typeof(System.Collections.Specialized.NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
isreadonly.SetValue(this.Request.QueryString, false, null);
this.Request.QueryString.Remove("foo");
This is my code, I think it's very useful:
public String GetQueryString(string ItemToRemoveOrInsert = null, string InsertValue = null )
{
System.Collections.Specialized.NameValueCollection filtered = new System.Collections.Specialized.NameValueCollection(Request.QueryString);
if (ItemToRemoveOrInsert != null)
{
filtered.Remove(ItemToRemoveOrInsert);
if (!string.IsNullOrWhiteSpace(InsertValue))
{
filtered.Add(ItemToRemoveOrInsert, InsertValue);
}
}
string StrQr = string.Join("&", filtered.AllKeys.Select(key => key + "=" + filtered[key]).ToArray());
if (!string.IsNullOrWhiteSpace(StrQr)){
StrQr="?" + StrQr;
}
return StrQr;
}
I answered a similar question a while ago. Basically, the best way would be to use the class HttpValueCollection
, which ASP.NET's Request.QueryString
property actually is, unfortunately it is internal in the .NET framework.
You could use Reflector to grab it (and place it into your Utils class). This way you could manipulate the query string like a NameValueCollection, but with all the url encoding/decoding issues taken care for you.
HttpValueCollection
extends NameValueCollection
, and has a constructor that takes an encoded query string (ampersands and question marks included), and it overrides a ToString()
method to later rebuild the query string from the underlying collection.
Example:
var coll = new HttpValueCollection();
coll["userId"] = "50";
coll["paramA"] = "A";
coll["paramB"] = "B";
string query = coll.ToString(true); // true means use urlencode
Console.WriteLine(query); // prints: userId=50¶mA=A¶mB=B
Percent encoding. Replace the hash with %23
.
No need for a 3rd party library. Use the nodejs url module to build a URL with query parameters:
const requestUrl = url.parse(url.format({
protocol: 'https',
hostname: 'yoursite.com',
pathname: '/the/path',
query: {
key: value
}
}));
Then make the request with the formatted url. requestUrl.path
will include the query parameters.
const req = https.get({
hostname: requestUrl.hostname,
path: requestUrl.path,
}, (res) => {
// ...
})
You could get a JavaScript object containing the parameters with something like this:
var regex = /[?&]([^=#]+)=([^&#]*)/g,
url = window.location.href,
params = {},
match;
while(match = regex.exec(url)) {
params[match[1]] = match[2];
}
The regular expression could quite likely be improved. It simply looks for name-value pairs, separated by =
characters, and pairs themselves separated by &
characters (or an =
character for the first one). For your example, the above would result in:
{v: "123", p: "hello"}
Here's a working example.
I've wrapped Darin's answer into a nicely reusable extension method.
public static class UriExtensions
{
/// <summary>
/// Adds the specified parameter to the Query String.
/// </summary>
/// <param name="url"></param>
/// <param name="paramName">Name of the parameter to add.</param>
/// <param name="paramValue">Value for the parameter to add.</param>
/// <returns>Url with added parameter.</returns>
public static Uri AddParameter(this Uri url, string paramName, string paramValue)
{
var uriBuilder = new UriBuilder(url);
var query = HttpUtility.ParseQueryString(uriBuilder.Query);
query[paramName] = paramValue;
uriBuilder.Query = query.ToString();
return uriBuilder.Uri;
}
}
I hope this helps!
They need to be percent-encoded:
> encodeURIComponent('&')
"%26"
So in your case, the URL would look like:
http://www.mysite.com?candy_name=M%26M
Yes, from the moment on you establish a HTTPS connection everyting is secure. The query string (GET) as the POST is sent over SSL.
A QueryString is, by definition, in the URL. You can access the URL of the request using req.URL
(doc). The URL object has a Query()
method (doc) that returns a Values
type, which is simply a map[string][]string
of the QueryString parameters.
If what you're looking for is the POST data as submitted by an HTML form, then this is (usually) a key-value pair in the request body. You're correct in your answer that you can call ParseForm()
and then use req.Form
field to get the map of key-value pairs, but you can also call FormValue(key)
to get the value of a specific key. This calls ParseForm()
if required, and gets values regardless of how they were sent (i.e. in query string or in the request body).
If you are sending this back to asp.net and need the data in request.form[] then you'll need to set the content type to "application/x-www-form-urlencoded; charset=utf-8"
Original post here
Secondly get rid of the Datatype, if your not expecting a return the POST will wait for about 4 minutes before failing. See here
Here is what I came up with. I was having major problems with this and believe I am in MVC 6 now but this may be helpful to someone even myself in the future..
//The issue was that Reqest.Form Request.Querystring and Request not working in MVC the solution is to use Context.Request.Form and also making sure the form has been submitted otherwise null reference or context issue bug will show up.
if(Context.Request.ContentLength != null)
{
String StartDate = Context.Request.Form["StartMonth"].ToString();
String EndMonth = Context.Request.Form["EndMonth"].ToString();
// Vendor
}
This works for me:
In link, to attribute has value:
to="/filter/arr?fruits=apple&fruits=banana"
Route can handle this:
path="/filter/:arr"
For Multiple arrays:
to="filter/arr?fruits=apple&fruits=banana&vegetables=potato&vegetables=onion"
Route stays same.
SCREENSHOT
We do it this way...
String.prototype.getValueByKey = function (k) {
var p = new RegExp('\\b' + k + '\\b', 'gi');
return this.search(p) != -1 ? decodeURIComponent(this.substr(this.search(p) + k.length + 1).substr(0, this.substr(this.search(p) + k.length + 1).search(/(&|;|$)/))) : "";
};
JQuery jQuery-URL-Parser plugin do the same job, for example to retrieve the value of search query string param, you can use
$.url().param('search');
This library is not actively maintained. As suggested by the author of the same plugin, you can use URI.js.
Or you can use js-url instead. Its quite similar to the one below.
So you can access the query param like $.url('?search')
ASP.NET Core will automatically bind form values
, route values
and query strings
by name. This means you can simply do this:
[HttpGet()]
public IActionResult Get(int page)
{ ... }
MVC will try to bind request data to the action parameters by name ... below is a list of the data sources in the order that model binding looks through them
Form values
: These are form values that go in the HTTP request using the POST method. (including jQuery POST requests).
Route values
: The set of route values provided by Routing
Query strings
: The query string part of the URI.
Source: Model Binding in ASP.NET Core
FYI, you can also combine the automatic and explicit approaches:
[HttpGet()]
public IActionResult Get(int page
, [FromQuery(Name = "page-size")] int pageSize)
{ ... }
if you want to pass multiple parameters then you can create model instead of passing multiple parameters.
in case you dont want to pass any parameter then you can skip as well in it, and your code will look neat and clean.
As an aside, I was in search to find the best way to implode an associative array but using my own seperators etc...
So I did this using PHP's array_walk() function to let me join an associative array into a list of parameters that could then be applied to a HTML tag....
// Create Params Array
$p = Array("id"=>"blar","class"=>"myclass","onclick"=>"myJavascriptFunc()");
// Join Params
array_walk($p, create_function('&$i,$k','$i=" $k=\"$i\"";'));
$p_string = implode($p,"");
// Now use $p_string for your html tag
Obviously, you could stick that in your own function somehow but it gives you an idea of how you can join an associative array using your own method. Hope that helps someone :)
Okay, since everyone is ignoring my actual question, heh, I'll post mine too! Here's what I have:
location.querystring = (function() {
// The return is a collection of key/value pairs
var queryStringDictionary = {};
// Gets the query string, starts with '?'
var querystring = unescape(location.search);
// document.location.search is empty if no query string
if (!querystring) {
return {};
}
// Remove the '?' via substring(1)
querystring = querystring.substring(1);
// '&' seperates key/value pairs
var pairs = querystring.split("&");
// Load the key/values of the return collection
for (var i = 0; i < pairs.length; i++) {
var keyValuePair = pairs[i].split("=");
queryStringDictionary[keyValuePair[0]] = keyValuePair[1];
}
// Return the key/value pairs concatenated
queryStringDictionary.toString = function() {
if (queryStringDictionary.length == 0) {
return "";
}
var toString = "?";
for (var key in queryStringDictionary) {
toString += key + "=" + queryStringDictionary[key];
}
return toString;
};
// Return the key/value dictionary
return queryStringDictionary;
})();
And the tests:
alert(window.location.querystring.toString());
for (var key in location.querystring) {
alert(key + "=" + location.querystring[key]);
}
Mind you thought, JavaScript isn't my native tongue.
Anyway, I'm looking for a JavaScript library (e.g. jQuery, Prototype) that already has one written. :)
If you are not using fig and ax plot objects you can do it like so:
import matplotlib.pyplot as plt
# do plot specifics
plt.legend('')
plt.show()
Try this it will work --
if($('#EventStartTimeMin').val() === " ") {
alert("Please enter start time!");
}
Questions : how to check File is empty or not?
Ans: I have slove this issue using this Jquery code
//If your file Is Empty : _x000D_
if (jQuery('#videoUploadFile').val() == '') {_x000D_
$('#message').html("Please Attach File");_x000D_
}else {_x000D_
alert('not work');_x000D_
}_x000D_
_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="file" id="videoUploadFile">_x000D_
<br>_x000D_
<br>_x000D_
<div id="message"></div>
_x000D_
It may help you.
var t0 = date.now();
doSomething();
var t1 = date.now();
console.log("Call to doSomething took approximate" + (t1 - t0)/1000 + " seconds.")
To test and see if you can access your MQTT server from outside world (outside of your VM or local machine), you can install one of the MQTT publishing and monitoring tools such as MQTT-Spy on your outside-world machine and then subscribe for '#" (meaning all the topics).
You can follow this by the method @hardillb mentioned in his answer above and test back and forth such as this:
On the machine with Mosquitto Server running,
On the outside-word machine with mqtt-spy running,
I have mainly mentioned mqtt-spy since it's multi-platform and easy to use. You can go with any other tool really.
And also to my knowledge to run the mosquitto_sub
and mosquitto_pub
you need to have mosquitto-clients installed on your Linux machine running the test (in my case Ubuntu) which can be done easily by,
sudo apt-get install mosquitto-clients
The preferred method of centering columns is to use "offsets" (ie: col-md-offset-3
)
Bootstrap 3.x centering examples
For centering elements, there is a center-block
helper class.
You can also use text-center
to center text (and inline elements).
Responsive Demo: http://bootply.com/91632
EDIT - As mentioned in the comments, center-block
works on column contents and display:block
elements, but won't work on the column itself (col-*
divs) because Bootstrap uses float
.
Now with Bootstrap 4, the centering methods have changed..
text-center
is still used for display:inline
elementsmx-auto
replaces center-block
to center display:block
elementsoffset-*
or mx-auto
can be used to center grid columnsmx-auto
(auto x-axis margins) will center display:block
or display:flex
elements that have a defined width, (%
, vw
, px
, etc..). Flexbox is used by default on grid columns, so there are also various flexbox centering methods.
Demo Bootstrap 4 Horizontal Centering
For vertical centering in BS4 see https://stackoverflow.com/a/41464397/171456
You can also use python chardet library
# install the chardet library
!pip install chardet
# import the chardet library
import chardet
# use the detect method to find the encoding
# 'rb' means read in the file as binary
with open("test.csv", 'rb') as file:
print(chardet.detect(file.read()))
I think you can do this with the hyperref
package, although I've not tried it myself. From the relevant LaTeX Wikibook section:
The
hyperref
package introduces another useful command;\autoref{}
. This command creates a reference with additional text corresponding to the targets type, all of which will be a hyperlink. For example, the command\autoref{sec:intro}
would create a hyperlink to the\label{sec:intro}
command, wherever it is. Assuming that this label is pointing to a section, the hyperlink would contain the text "section 3.4", or similar (capitalization rules will be followed, which makes this very convenient). You can customize the prefixed text by redefining\typeautorefname
to the prefix you want, as in:
\def\subsectionautorefname{section}
Update 2018-07-23
As was just pointed out in the comments, this question was about getting a screenshot from the command line. Sorry, I just read over that. So here is the correct answer:
As of Firefox 57 you can create a screenshot in headless mode like this:
firefox -screenshot https://developer.mozilla.com
Read more in the documentation.
Update 2017-06-15
As of Firefox 55 there is Firefox Screenshots as a more flexible alternative. As of Firefox 57 Screenshots can capture a full page, too.
Original answer
Since Firefox 32 there is also a full page screenshot button in the developer tools (F12). If it is not enabled go to the developer tools settings (gear button) and choose "Take a fullpage screenshot" at the "Available Toolbox Buttons" section.
source: developer.mozilla.org
By default the screenshots are saved in the download directory. This works similar to screenshot --fullpage
in the toolbar.
Its a late answer, but as I can see most of the people mentioned about "refresh" method to redirect a webpage. As per W3C, we should not use "refresh" to redirect. Because it could break the "back" button. Imagine that the user presses the "back" button, the refresh would work again, and the user would bounce forward. The user will most likely get very annoyed, and close the window, which is probably not what you, as the author of this page, want.
Use HTTP redirects instead. One can refer the complete documentation here: W3C document
psql --pset=format=FORMAT
Great for executing queries from command line, e.g.
psql --pset=format=unaligned -c "select bandanavalue from bandana where bandanakey = 'atlassian.confluence.settings';"
Yeah. Try this.. lazy evaluation should prohibit the second part of the condition from evaluating when the first part is false/null:
var someval = document.getElementById('something')
if (someval && someval.value <> '') {
Try to add
GRANT USAGE ON SCHEMA public to readonly;
You probably were not aware that one needs to have the requisite permissions to a schema, in order to use objects in the schema.
There is not official api support which means that it is not documented for the public and the libraries may change at any time. I realize you don't want to leave the application but here's how you do it with an intent for anyone else wondering.
public void sendData(int num){
String fileString = "..."; //put the location of the file here
Intent mmsIntent = new Intent(Intent.ACTION_SEND);
mmsIntent.putExtra("sms_body", "text");
mmsIntent.putExtra("address", num);
mmsIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(fileString)));
mmsIntent.setType("image/jpeg");
startActivity(Intent.createChooser(mmsIntent, "Send"));
}
I haven't completely figured out how to do things like track the delivery of the message but this should get it sent.
You can be alerted to the receipt of mms the same way as sms. The intent filter on the receiver should look like this.
<intent-filter>
<action android:name="android.provider.Telephony.WAP_PUSH_RECEIVED" />
<data android:mimeType="application/vnd.wap.mms-message" />
</intent-filter>
I extended Ronnie's answer with a fluent implementation so you can use it like so:
dm.Context.SetCommandTimeout(120).Database.SqlQuery...
public static class EF
{
public static DbContext SetCommandTimeout(this DbContext db, TimeSpan? timeout)
{
((IObjectContextAdapter)db).ObjectContext.CommandTimeout = timeout.HasValue ? (int?) timeout.Value.TotalSeconds : null;
return db;
}
public static DbContext SetCommandTimeout(this DbContext db, int seconds)
{
return db.SetCommandTimeout(TimeSpan.FromSeconds(seconds));
}
}
To ensure that your build is completely rebuild, including checking the base image for updates, use the following options when building:
--no-cache
- This will force rebuilding of layers already available
--pull
- This will trigger a pull of the base image referenced using FROM ensuring you got the latest version.
The full command will therefore look like this:
docker build --pull --no-cache --tag myimage:version .
Same options are available for docker-compose:
docker-compose build --no-cache --pull
Note that if your docker-compose file references an image, the --pull option will not actually pull the image if there is one already.
To force docker-compose to re-pull this, you can run:
docker-compose pull
You can use the contains method
var result = parent.contains(child);
or you can try to use compareDocumentPosition()
var result = nodeA.compareDocumentPosition(nodeB);
The last one is more powerful: it return a bitmask as result.
I would suggest following design :
Item Table:
Itemid, taglist1, taglist2
this will be fast and make easy saving and retrieving the data at item level.
In parallel build another table: Tags tag do not make tag unique identifier and if you run out of space in 2nd column which contains lets say 100 items create another row.
Now while searching for items for a tag it will be super fast.
I know this is 3 years old, but for everyone reading this now: Don't stick to VST, AU or any vendor's format. Steinberg has stopped supporting VST2, and people are in trouble porting their code to newer formats, because it's too tied to VST2.
These tutorials cover creating plugins that run on Win/Mac, 32/64, all plugin formats from the same code base.
Actually what Luis proposed did not work for me. I had to figure out another way. This is what helped me. Might help you too. Links:
*.getEncoded(): https://docs.oracle.com/javase/7/docs/api/java/security/Key.html
Encoder information: https://docs.oracle.com/javase/8/docs/api/java/util/Base64.Encoder.html
Decoder information: https://docs.oracle.com/javase/8/docs/api/java/util/Base64.Decoder.html
Code snippets: For encoding:
String temp = new String(Base64.getEncoder().encode(key.getEncoded()));
For decoding:
byte[] encodedKey = Base64.getDecoder().decode(temp);
SecretKey originalKey = new SecretKeySpec(encodedKey, 0, encodedKey.length, "DES");
Easy one for me ! I got it few weeks ago :
This goes in getBody()
method, not in getParams()
for a post request.
Here is mine :
@Override
/**
* Returns the raw POST or PUT body to be sent.
*
* @throws AuthFailureError in the event of auth failure
*/
public byte[] getBody() throws AuthFailureError {
// Map<String, String> params = getParams();
Map<String, String> params = new HashMap<String, String>();
params.put("id","1");
params.put("name", "myname");
if (params != null && params.size() > 0) {
return encodeParameters(params, getParamsEncoding());
}
return null;
}
(I assumed you want to POST the params you wrote in your getParams)
I gave the params to the request inside the constructor, but since you are creating the request on the fly, you can hard coded them inside your override of the getBody() method.
This is what my code looks like :
Bundle param = new Bundle();
param.putString(HttpUtils.HTTP_CALL_TAG_KEY, tag);
param.putString(HttpUtils.HTTP_CALL_PATH_KEY, url);
param.putString(HttpUtils.HTTP_CALL_PARAM_KEY, params);
switch (type) {
case RequestType.POST:
param.putInt(HttpUtils.HTTP_CALL_TYPE_KEY, RequestType.POST);
SCMainActivity.mRequestQueue.add(new SCRequestPOST(Method.POST, url, this, tag, receiver, params));
and if you want even more this last string params comes from :
param = JsonUtils.XWWWUrlEncoder.encode(new JSONObject(paramasJObj)).toString();
and the paramasJObj is something like this : {"id"="1","name"="myname"}
the usual JSON string.
I think you're going to need separate lines for each segment:
import numpy as np
import matplotlib.pyplot as plt
x, y = np.random.random(size=(2,10))
for i in range(0, len(x), 2):
plt.plot(x[i:i+2], y[i:i+2], 'ro-')
plt.show()
(The numpy
import is just to set up some random 2x10 sample data)
First Create folder same as path which you Specified. after then create File
File dir = new File("C:\\USER\\Semple_file\\");
File file = new File("C:\\USER\\Semple_file\\abc.txt");
if(!file.exists())
{
dir.mkdir();
file.createNewFile();
System.out.println("File,Folder Created.);
}
POD is the official way to do multi line comments in Perl,
From faq.perl.org[perlfaq7]
The quick-and-dirty way to comment out more than one line of Perl is to surround those lines with Pod directives. You have to put these directives at the beginning of the line and somewhere where Perl expects a new statement (so not in the middle of statements like the # comments). You end the comment with
=cut
, ending the Pod section:
=pod
my $object = NotGonnaHappen->new();
ignored_sub();
$wont_be_assigned = 37;
=cut
The quick-and-dirty method only works well when you don't plan to leave the commented code in the source. If a Pod parser comes along, your multiline comment is going to show up in the Pod translation. A better way hides it from Pod parsers as well.
The
=begin
directive can mark a section for a particular purpose. If the Pod parser doesn't want to handle it, it just ignores it. Label the comments withcomment
. End the comment using=end
with the same label. You still need the=cut
to go back to Perl code from the Pod comment:
=begin comment
my $object = NotGonnaHappen->new();
ignored_sub();
$wont_be_assigned = 37;
=end comment
=cut
I don't see any problem, unless you are not managing them using a connection pool.
If you use connection pool, these connections are re-used instead of initiating new connections. so basically, leaving open connections and re-use them it is less problematic than re-creating them each time.
You need an event handler which will fire when the button is clicked. Here is a quick way -
var button = new Button();
button.Text = "my button";
this.Controls.Add(button);
button.Click += (sender, args) =>
{
MessageBox.Show("Some stuff");
Close();
};
But it would be better to understand a bit more about buttons, events, etc.
If you use the visual studio UI to create a button and double click the button in design mode, this will create your event and hook it up for you. You can then go to the designer code (the default will be Form1.Designer.cs) where you will find the event:
this.button1.Click += new System.EventHandler(this.button1_Click);
You will also see a LOT of other information setup for the button, such as location, etc. - which will help you create one the way you want and will improve your understanding of creating UI elements. E.g. a default button gives this on my 2012 machine:
this.button1.Location = new System.Drawing.Point(128, 214);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 1;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
As for closing the Form, it is as easy as putting Close(); within your event handler:
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("some text");
Close();
}
Character.isDigit(string.charAt(index))
(JavaDoc) will return true if it's a digit
Character.isLetter(string.charAt(index))
(JavaDoc) will return true if it's a letter
This Works For me !!!
Call a Function without Parameter
$("#CourseSelect").change(function(e1) {
loadTeachers();
});
Call a Function with Parameter
$("#CourseSelect").change(function(e1) {
loadTeachers($(e1.target).val());
});
var str1 = "ABCDEFGHIJKLMNOP";
var str2 = "DEFG";
sttr1.search(str2);
it will return the position of the match, or -1 if it isn't found.
Below Codes
public static byte[] serializeObj(Object obj) throws IOException {
ByteArrayOutputStream baOStream = new ByteArrayOutputStream();
ObjectOutputStream objOStream = new ObjectOutputStream(baOStream);
objOStream.writeObject(obj);
objOStream.flush();
objOStream.close();
return baOStream.toByteArray();
}
OR
BufferedImage img = ...
ByteArrayOutputStream baos = new ByteArrayOutputStream(1000);
ImageIO.write(img, "jpeg", baos);
baos.flush();
byte[] result = baos.toByteArray();
baos.close();
While I am no Objective-C expert, I personally just define the method in the implementation of my class. Granted, it must be defined before (above) any methods calling it, but it definitely takes the least amount of work to do.
Simple example:
public function productsAction()
{
$saveFileName = 'ceneo.xml';
$filename = $this->path . $saveFileName;
if(file_exists($filename)) {
$reader = new XMLReader();
$reader->open($filename);
$countElements = 0;
while($reader->read()) {
if($reader->nodeType == XMLReader::ELEMENT) {
$nodeName = $reader->name;
}
if($reader->nodeType == XMLReader::TEXT && !empty($nodeName)) {
switch ($nodeName) {
case 'id':
var_dump($reader->value);
break;
}
}
if($reader->nodeType == XMLReader::END_ELEMENT && $reader->name == 'offer') {
$countElements++;
}
}
$reader->close();
exit(print('<pre>') . var_dump($countElements));
}
}
You can set the background color of a button using the getRed function.
Let's assume you have:
Then, place the following code in the function where you want to change the background color of your UIButton
var r:CGFloat = 0
var g:CGFloat = 0
var b:CGFloat = 0
var a:CGFloat = 0
// This will be some red-ish color
let color = UIColor(red: 200.0/255.0, green: 16.0/255.0, blue: 46.0/255.0, alpha: 1.0)
if color.getRed(&r, green: &g, blue: &b, alpha: &a){
button.backgroundColor = UIColor(red: r, green: g, blue: b, alpha: a)
}
I have tried these hash functions and got the following result. I have about 960^3 entries, each 64 bytes long, 64 chars in different order, hash value 32bit. Codes from here.
Hash function | collision rate | how many minutes to finish
==============================================================
MurmurHash3 | 6.?% | 4m15s
Jenkins One.. | 6.1% | 6m54s
Bob, 1st in link | 6.16% | 5m34s
SuperFastHash | 10% | 4m58s
bernstein | 20% | 14s only finish 1/20
one_at_a_time | 6.16% | 7m5s
crc | 6.16% | 7m56s
One strange things is that almost all the hash functions have 6% collision rate for my data.
Old question, and the posted answers work great. I'll chime in with another option though.
git reset ORIG_HEAD
ORIG_HEAD
references the commit that HEAD
previously referenced.
Collapse to definitions
CTRL + M, O
Expand all outlining
CTRL + M, X
Expand or collapse everything
CTRL + M, L
This also works with other languages like TypeScript and JavaScript
try this open source projects that might help you
This could be the possible solution
var str = 'RACK NO:Stock;PRODUCT TYPE:Stock Sale;PART N0:0035719061;INDEX NO:21A627 042;PART NAME:SPRING;';
var newstr = str.split(':')[1].split(';')[0]; // return value as 'Stock'
console.log('stringvalue',newstr)
My issue occurs when I add a PC to a domain. Restarting the service, making sure it's running, that it has the correct credentials to run, etc, as in other answers doesn't work. I don't know exactly what the problem is, but I can't even log in with the local user anymore to give the domain user access. Here's the steps that work for me:
In SSMS
pcname\sqlexpress
pcname\sqlexpress
reappears.I'm then able to log in with the local windows auth'd user again, my databases are all there and everything. I then go about my business adding the domain user to Security > Logins.
You can essentially do this 2 ways:
Add a file called .htaccess
in your root folder, and add something like this:
RewriteEngine on
RewriteRule ^/?Some-text-goes-here/([0-9]+)$ /picture.php?id=$1
This will tell Apache to enable mod_rewrite for this folder, and if it gets asked a URL matching the regular expression it rewrites it internally to what you want, without the end user seeing it. Easy, but inflexible, so if you need more power:
Put the following in your .htaccess instead: (note the leading slash)
FallbackResource /index.php
This will tell it to run your index.php
for all files it cannot normally find in your site. In there you can then for example:
$path = ltrim($_SERVER['REQUEST_URI'], '/'); // Trim leading slash(es)
$elements = explode('/', $path); // Split path on slashes
if(empty($elements[0])) { // No path elements means home
ShowHomepage();
} else switch(array_shift($elements)) // Pop off first item and switch
{
case 'Some-text-goes-here':
ShowPicture($elements); // passes rest of parameters to internal function
break;
case 'more':
...
default:
header('HTTP/1.1 404 Not Found');
Show404Error();
}
This is how big sites and CMS-systems do it, because it allows far more flexibility in parsing URLs, config and database dependent URLs etc. For sporadic usage the hardcoded rewrite rules in .htaccess
will do fine though.
This should works
$token = "YOUR_BEARER_AUTH_TOKEN";
//setup the request, you can also use CURLOPT_URL
$ch = curl_init('API_URL');
// Returns the data/output as a string instead of raw data
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//Set your auth headers
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Authorization: Bearer ' . $token
));
// get stringified data/output. See CURLOPT_RETURNTRANSFER
$data = curl_exec($ch);
// get info about the request
$info = curl_getinfo($ch);
// close curl resource to free up system resources
curl_close($ch);
You need to specify the minimum width of the field.
String.format("%" + numberOfSpaces + "s", "");
Why do you want to generate a String of spaces of a certain length.
If you want a column of this length with values then you can do:
String.format("%" + numberOfSpaces + "s", "Hello");
which gives you numberOfSpaces-5 spaces followed by Hello. If you want Hello to appear on the left then add a minus sign in before numberOfSpaces.
A lazy val is most easily understood as a "memoized (no-arg) def".
Like a def, a lazy val is not evaluated until it is invoked. But the result is saved so that subsequent invocations return the saved value. The memoized result takes up space in your data structure, like a val.
As others have mentioned, the use cases for a lazy val are to defer expensive computations until they are needed and store their results, and to solve certain circular dependencies between values.
Lazy vals are in fact implemented more or less as memoized defs. You can read about the details of their implementation here:
http://docs.scala-lang.org/sips/pending/improved-lazy-val-initialization.html
HI Jasper,
you can do this:
<?
sprintf("<a href=\"http://www.whatever.com/%s\">Click Here</a>", $param);
?>
Have you considered applying ON DELETE CASCADE
where relevant?
If you have a SOCK_STREAM
socket, recv
just gets "up to the first 3000 bytes" from the stream. There is no clear guidance on how big to make the buffer: the only time you know how big a stream is, is when it's all done;-).
If you have a SOCK_DGRAM
socket, and the datagram is larger than the buffer, recv
fills the buffer with the first part of the datagram, returns -1, and sets errno to EMSGSIZE. Unfortunately, if the protocol is UDP, this means the rest of the datagram is lost -- part of why UDP is called an unreliable protocol (I know that there are reliable datagram protocols but they aren't very popular -- I couldn't name one in the TCP/IP family, despite knowing the latter pretty well;-).
To grow a buffer dynamically, allocate it initially with malloc
and use realloc
as needed. But that won't help you with recv
from a UDP source, alas.
For converting a list of dictionaries to a pandas DataFrame, you can use "append":
We have a dictionary called dic
and dic has 30 list items (list1
, list2
,…, list30
)
total_df
)total_df
with list1
total_df
total_df=list1
nums=Series(np.arange(start=2, stop=31))
for num in nums:
total_df=total_df.append(dic['list'+str(num)])
I found that even after following all the steps above, I was still getting errors saying that my Maven dependencies (i.e. pom.xml) were pointing to jar files that didn't exist.
Viewing the errors in the Problems tab, for some reason these were still pointing to the old location of my repository. This was probably because I'd changed the location of my Maven repository since creating the workspace and project.
This can be easily solved by deleting the project from the Eclipse workspace, and re-adding it again through Package Explorer -> R/Click -> Import... -> Existing Projects.
To remove all files in folder
import os
import glob
files = glob.glob(os.path.join('path/to/folder/*'))
files = glob.glob(os.path.join('path/to/folder/*.csv')) // It will give all csv files in folder
for file in files:
os.remove(file)
To remove all folders in a directory
from shutil import rmtree
import os
// os.path.join() # current working directory.
for dirct in os.listdir(os.path.join('path/to/folder')):
rmtree(os.path.join('path/to/folder',dirct))
You want to convert it to an object first and then access normally making sure to cast it.
JObject obj = JObject.Parse(json);
string name = (string) obj["Name"];
This allows for parallel execution on all android versions with API 4+ (Android 1.6+):
@TargetApi(Build.VERSION_CODES.HONEYCOMB) // API 11
void startMyTask(AsyncTask asyncTask) {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
else
asyncTask.execute(params);
}
This is a summary of Arhimed's excellent answer.
Please make sure you use API level 11 or higher as your project build target. In Eclipse, that is Project > Properties > Android > Project Build Target
. This will not break backward compatibility to lower API levels. Don't worry, you will get Lint errors if your accidentally use features introduced later than minSdkVersion
. If you really want to use features introduced later than minSdkVersion
, you can suppress those errors using annotations, but in that case, you need take care about compatibility yourself. This is exactly what happened in the code snippet above.
Where do you want to see the output?
Messages being output via Debug.Print
will be displayed in the immediate window which you can open by pressing Ctrl+G.
You can also Activate the so called Immediate Window by clicking View -> Immediate Window on the VBE toolbar
Updated for correctness. Originally answered by @jen.
with DATES as (
select TO_DATE('20120101', 'YYYYMMDD') as Date1,
TO_DATE('20120325', 'YYYYMMDD') as Date2
from DUAL union all
select TO_DATE('20120101', 'YYYYMMDD') as Date1,
TO_DATE('20130101', 'YYYYMMDD') as Date2
from DUAL union all
select TO_DATE('20120101', 'YYYYMMDD') as Date1,
TO_DATE('20120101', 'YYYYMMDD') as Date2
from DUAL union all
select TO_DATE('20130228', 'YYYYMMDD') as Date1,
TO_DATE('20130301', 'YYYYMMDD') as Date2
from DUAL union all
select TO_DATE('20130228', 'YYYYMMDD') as Date1,
TO_DATE('20130401', 'YYYYMMDD') as Date2
from DUAL
), MONTHS_BTW as (
select Date1, Date2,
MONTHS_BETWEEN(Date2, Date1) as NumOfMonths
from DATES
)
select TO_CHAR(Date1, 'MON DD YYYY') as Date_1,
TO_CHAR(Date2, 'MON DD YYYY') as Date_2,
NumOfMonths as Num_Of_Months,
TRUNC(NumOfMonths) as "Month(s)",
ADD_MONTHS(Date2, - TRUNC(NumOfMonths)) - Date1 as "Day(s)"
from MONTHS_BTW;
SQLFiddle Demo :
+--------------+--------------+-----------------+-----------+--------+ | DATE_1 | DATE_2 | NUM_OF_MONTHS | MONTH(S) | DAY(S) | +--------------+--------------+-----------------+-----------+--------+ | JAN 01 2012 | MAR 25 2012 | 2.774193548387 | 2 | 24 | | JAN 01 2012 | JAN 01 2013 | 12 | 12 | 0 | | JAN 01 2012 | JAN 01 2012 | 0 | 0 | 0 | | FEB 28 2013 | MAR 01 2013 | 0.129032258065 | 0 | 1 | | FEB 28 2013 | APR 01 2013 | 1.129032258065 | 1 | 1 | +--------------+--------------+-----------------+-----------+--------+
Notice, how for the last two dates, Oracle reports the decimal part of months (which gives days) incorrectly. 0.1290
corresponds to exactly 4
days with Oracle considering 31
days in a month (for both March and April).
After much searching for the answer to this, I worked out this simple solution that I will share here in hopes it helps others.
I set WindowStyle=0x10000000
.
This sets the WS_VISIBLE (0x10000000)
and WS_OVERLAPPED (0x0)
values for Window Style. "Overlapped" is the necessary value to show the title bar and window border. By removing the WS_MINIMIZEBOX (0x20000)
, WS_MAXIMIZEBOX (0x10000)
, and WS_SYSMENU (0x80000)
values from my style value, all the buttons from the title bar were removed, including the Close button.
If you are storing keys/values as strings, then this will work:
HashMap<String, String> newMap = new HashMap<String, String>();
newMap.put("my_code", "shhh_secret");
String value = newMap.get("my_code");
The question is what gets populated in the HashMap (key & value)
?++11 finally resolves this providing std::to_string
.
Also boost::lexical_cast
is handy tool for older compilers.
An asynchronously loaded script is likely going to run AFTER the document has been fully parsed and closed. Thus, you can't use document.write()
from such a script (well technically you can, but it won't do what you want).
You will need to replace any document.write()
statements in that script with explicit DOM manipulations by creating the DOM elements and then inserting them into a particular parent with .appendChild()
or .insertBefore()
or setting .innerHTML
or some mechanism for direct DOM manipulation like that.
For example, instead of this type of code in an inline script:
<div id="container">
<script>
document.write('<span style="color:red;">Hello</span>');
</script>
</div>
You would use this to replace the inline script above in a dynamically loaded script:
var container = document.getElementById("container");
var content = document.createElement("span");
content.style.color = "red";
content.innerHTML = "Hello";
container.appendChild(content);
Or, if there was no other content in the container that you needed to just append to, you could simply do this:
var container = document.getElementById("container");
container.innerHTML = '<span style="color:red;">Hello</span>';
<html>
<body>
<input id="mycheck" type="checkbox">
</body>
<script language="javascript">
var=check;
document.getElementById("mycheck");
check.checked="false";
</script>
</html>
There are a few base64 encoders online to help you with this, this is probably the best I've seen:
http://www.greywyvern.com/code/php/binary2base64
As that page shows your main options for this are CSS:
div.image {
width:100px;
height:100px;
background-image:url(data:image/png;base64,iVBORwA<MoreBase64SringHere>);
}
Or the <img>
tag itself, like this:
<img alt="My Image" src="data:image/png;base64,iVBORwA<MoreBase64SringHere>" />
I solved my problem doing the following:
First of all, I am a windows user, but i have faced similar issue. So, I am posting my solution here.
There is one simple reason why sometimes the .gitignore doesn`t work like it is supposed to. It is due to the EOL conversion behavior.
Here is a quick fix for that
Edit > EOL Conversion > Windows Format > Save
You can blame your text editor settings for that.
For example:
As i am a windows developer, I typically use Notepad++ for editing my text unlike Vim users.
So what happens is, when i open my .gitignore file using Notepad++, it looks something like this:
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# See https://help.github.com/ignore-files/ for more about ignoring files.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
*.dll
*.force
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
If i open the same file using the default Notepad, this is what i get
## Ignore Visual Studio temporary files, build results, and ## files generated by popular Visual Studio add-ons. ## ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore # See https://help.github.com/ignore-files/ for more about ignoring files. # User-specific files *.suo *.user *.userosscache
So, you might have already guessed by looking at the output. Everything in the .gitignore has become a one liner, and since there is a ## in the start, it acts as if everything is commented.
The way to fix this is simple: Just open your .gitignore file with Notepad++ , then do the following
Edit > EOL Conversion > Windows Format > Save
The next time you open the same file with the windows default notepad, everything should be properly formatted. Try it and see if this works for you.
I don't know the platform you're doing this on but I assume Windows due to the .bat extension.
Also I don't have a way to check this but this seems like the batch processor skips the If lines due to some errors and then executes the one with -dev.
You could try this by chaning the two jump targets (:yes
and :no
) along with the code. If then the line without -dev is executed you know your If lines are erroneous.
If so, please check if ==
is really the right way to do a comparison in .bat
files.
Also, judging from the way bash does this stuff, %foo=="y"
might evaluate to true only if %foo
includes the quotes. So maybe "%foo"=="y"
is the way to go.
The CLR uses it when it is compiling at runtime. Here is a link to MSDN that explains further.
try this, it works. (in the example below i have 3 cells for example.)
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
let visibleRect = CGRect(origin: self.collectionView.contentOffset, size: self.collectionView.bounds.size)
let visiblePoint = CGPointMake(CGRectGetMidX(visibleRect), CGRectGetMidY(visibleRect))
let visibleIndexPath = self.collectionView.indexPathForItemAtPoint(visiblePoint)
if let v = visibleIndexPath {
switch v.item {
case 0: setImageDescription()
break
case 1: setImageConditions()
break
case 2: setImageResults()
break
default: break
}
}
This is an adaptation from my code for you. I was inspired from developpez.com (Look in the page for : "Pour insérer des données, vaut-il mieux passer par un RecordSet ou par une requête de type INSERT ?"). They explain (with a little French). This way is much faster than the one upper. In the example, this way was 37 times faster. Try it.
Const tableName As String = "InvoiceNumbers"
Const columnIdName As String = "??"
Const columnDateName As String = "date"
Dim rsTable As DAO.recordSet
Dim recordId as long
Set rsTable = CurrentDb.OpenRecordset(tableName)
Call rsTable .AddNew
recordId = CLng(rsTable (columnIdName)) ' Save your Id in a variable
rsTable (columnDateName) = Now() ' Store your data
rsTable .Update
recordSet.Close
LeCygne
As per https://android.stackexchange.com/a/78183/239063 you can run a one line command in Linux to add in an appropriate tar header to extract it.
( printf "\x1f\x8b\x08\x00\x00\x00\x00\x00" ; tail -c +25 backup.ab ) | tar xfvz -
Replace backup.ab with the path to your file.
Notice that "cex" does change things when the plot is made with text. For example, the plot of an agglomerative hierarchical clustering:
library(cluster)
data(votes.repub)
agn1 <- agnes(votes.repub, metric = "manhattan", stand = TRUE)
plot(agn1, which.plots=2)
will produce a plot with normal sized text:
and plot(agn1, which.plots=2, cex=0.5)
will produce this one:
You can customise the credits, changing the URL, text, Position etc. All the info is documented here: http://api.highcharts.com/highcharts/credits. To simply disable them altogether, use:
credits: {
enabled: false
},
window.onclick = e => {
console.dir(e.target); // use this in chrome
console.log(e.target); // use this in firefox - click on tag name to view
}
take advantage of using filter propeties
e.target.tagName
e.target.className
e.target.style.height // its not the value applied from the css style sheet, to get that values use `getComputedStyle()`
Just another way to use Git's awesomeness...
git difftool HEAD HEAD@{N} /PATH/FILE.ext
The correct way would be:
location / {
rewrite (.*) base.html last;
}
Using last
will make nginx find a new suitable location
block according to the result of rewriting.
try_files
is also a perfectly valid approach to this problem.
You can delete any QuerySet you'd like. For example, to delete all blog posts with some Post model
Post.objects.all().delete()
and to delete any Post with a future publication date
Post.objects.filter(pub_date__gt=datetime.now()).delete()
You do, however, need to come up with a way to narrow down your QuerySet. If you just want a view to delete a particular object, look into the delete generic view.
EDIT:
Sorry for the misunderstanding. I think the answer is somewhere between. To implement your own, combine ModelForm
s and generic views. Otherwise, look into 3rd party apps that provide similar functionality. In a related question, the recommendation was django-filter.
click here for full source code and learn more.
Before get permission you can check api version,
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
}
else
{
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 401);
}
}
else
{
// if version is below m then write code here,
}
Get the Result of the permission dialog,
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 401) {
if (grantResults.length == 0 || grantResults == null) {
} else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openGallery();
} else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
}
} else if (requestCode == 402) {
if (grantResults.length == 0 || grantResults == null) {
} else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
} else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
}
}
}
I simply had to add the ScriptManager to the page. Issue resolved.
You can use this:
select
table_name,column_name,referenced_table_name,referenced_column_name
from
information_schema.key_column_usage
where
referenced_table_name is not null
and table_schema = 'my_database'
and table_name = 'my_table'
Or for better formatted output use this:
select
concat(table_name, '.', column_name) as 'foreign key',
concat(referenced_table_name, '.', referenced_column_name) as 'references'
from
information_schema.key_column_usage
where
referenced_table_name is not null
and table_schema = 'my_database'
and table_name = 'my_table'
It's basically a shorthand. So instead of having to write:
this.props.dispatch(toggleTodo(id));
You would use mapDispatchToProps as shown in your example code, and then elsewhere write:
this.props.onTodoClick(id);
or more likely in this case, you'd have that as the event handler:
<MyComponent onClick={this.props.onTodoClick} />
There's a helpful video by Dan Abramov on this here: https://egghead.io/lessons/javascript-redux-generating-containers-with-connect-from-react-redux-visibletodolist
Solved, this is how your parse their html results:
table = soup.find("table", { "class" : "lineItemsTable" })
for row in table.findAll("tr"):
cells = row.findAll("td")
if len(cells) == 9:
summons = cells[1].find(text=True)
plateType = cells[2].find(text=True)
vDate = cells[3].find(text=True)
location = cells[4].find(text=True)
borough = cells[5].find(text=True)
vCode = cells[6].find(text=True)
amount = cells[7].find(text=True)
print amount
Assuming you have Files a.txt and b.txt with
cat a.txt
a
b
c
d
1
3
5
cat b.txt
a
1
2
6
7
Keep in mind NR and FNR are awk built-in variables. NR - Gives the total number of records processed. (in this case both in a.txt and b.txt) FNR - Gives the total number of records for each input file (records in either a.txt or b.txt)
awk 'NR==FNR{a[$0];}{if($0 in a)print FILENAME " " NR " " FNR " " $0}' a.txt b.txt
a.txt 1 1 a
a.txt 2 2 b
a.txt 3 3 c
a.txt 4 4 d
a.txt 5 5 1
a.txt 6 6 3
a.txt 7 7 5
b.txt 8 1 a
b.txt 9 2 1
lets Add "next" to skip the first matched with NR==FNR
in b.txt and in a.txt
awk 'NR==FNR{a[$0];next}{if($0 in a)print FILENAME " " NR " " FNR " " $0}' a.txt b.txt
b.txt 8 1 a
b.txt 9 2 1
in b.txt but not in a.txt
awk 'NR==FNR{a[$0];next}{if(!($0 in a))print FILENAME " " NR " " FNR " " $0}' a.txt b.txt
b.txt 10 3 2
b.txt 11 4 6
b.txt 12 5 7
awk 'NR==FNR{a[$0];next}!($0 in a)' a.txt b.txt
2
6
7
You can also post multiple inputs with the same name and have them save into an array by adding empty square brackets to the input name like this:
<input type="text" name="comment[]" value="comment1"/>
<input type="text" name="comment[]" value="comment2"/>
<input type="text" name="comment[]" value="comment3"/>
<input type="text" name="comment[]" value="comment4"/>
If you use php:
print_r($_POST['comment'])
you will get this:
Array ( [0] => 'comment1' [1] => 'comment2' [2] => 'comment3' [3] => 'comment4' )
Long story short, you can use the new Symbol
to create private fields.
Here's a great description: https://curiosity-driven.org/private-properties-in-javascript
Example:
var Person = (function() {
// Only Person can access nameSymbol
var nameSymbol = Symbol('name');
function Person(name) {
this[nameSymbol] = name;
}
Person.prototype.getName = function() {
return this[nameSymbol];
};
return Person;
}());
The simplest way to construct objects is to avoid prototypal inheritance altogether. Just define the private variables and public functions within the closure, and all public methods will have private access to the variables.
In JavaScript, prototypal inheritance is primarily an optimization. It allows multiple instances to share prototype methods, rather than each instance having its own methods.
The drawback is that this
is the only thing that's different each time a prototypal function is called.
Therefore, any private fields must be accessible through this
, which means they're going to be public. So we just stick to naming conventions for _private
fields.
I think you shouldn't mix closure variables with prototype methods. You should use one or the other.
When you use a closure to access a private variable, prototype methods cannot access the variable. So, you have to expose the closure onto this
, which means that you're exposing it publicly one way or another. There's very little to gain with this approach.
For really simple objects, just use a plain object with closures.
If you need prototypal inheritance -- for inheritance, performance, etc. -- then stick with the "_private" naming convention, and don't bother with closures.
I don't understand why JS developers try SO hard to make fields truly private.
Mean for each column in df
:
A B C
0 5 3 8
1 5 3 9
2 8 4 9
df.mean()
A 6.000000
B 3.333333
C 8.666667
dtype: float64
and if you want average of all columns:
df.stack().mean()
6.0
//How to start another application from the current application
Process runProg = new Process();
runProg.StartInfo.FileName = pathToFile; //the path of the application
runProg.StartInfo.Arguments = genArgs; //any arguments you want to pass
runProg.StartInfo.CreateNoWindow = true;
runProg.Start();
//How to end the same application from the current application
int IDstring = System.Convert.ToInt32(runProg.Id.ToString());
Process tempProc = Process.GetProcessById(IDstring);
tempProc.CloseMainWindow();
tempProc.WaitForExit();
This is an old post but still a problem within the Chrome dev tools. I find the best way to check mobile source locally is to open the site locally in Xcode's iOS Simulator. Then from there you open the Safari browser and enable dev tools, if you have not already done this (go to preferences -> advanced -> show develop menu in menu bar). Now you will see the develop option in the main menu and can go to develop -> iOS Simulator -> and the page you have open in Xcode's iOS Simulator will be there. Once you click on it, it will open the web inspector and you can edit as you would normally in the browser dev tools.
I'm afraid this solution will only work on a Mac though as it uses Xcode.
It sounds like you may be having trouble with SSH-Agent itself. I would try troubleshooting that.
1) Did you do ssh-add to add your key to SSH?
2) Are you closing the terminal window between uses, because if you close the window you will have to enter the password again when you reopen it.
Instead of tf.placeholder(shape=[None, 2], dtype=tf.float32)
use something like
tf.compat.v1.placeholder(shape=[None, 2], dtype=tf.float32)
if you don't want to disable v2 completely.
// Shifting bytes is more efficient // You can use this one too
public static String getHexString (String s)
{
byte[] buf = s.getBytes();
StringBuffer sb = new StringBuffer();
for (byte b:buf)
{
sb.append(String.format("%x", b));
}
return sb.toString();
}
Address already in use
means that the port
you are trying to allocate for your current execution is already occupied/allocated to some other process.
If you are a developer and if you are working on an application which require lots of testing, you might have an instance of your same application running in background (may be you forgot to stop it properly)
So if you encounter this error, just see which application/process is using the port.
In linux try using netstat -tulpn
. This command will list down a process list with all running processes.
Check if an application is using your port. If that application or process is another important one then you might want to use another port which is not used by any process/application.
Anyway you can stop the process which uses your port and let your application take it.
If you are in linux environment try,
netstat -tulpn
to display the processeskill <pid>
This will terminate the processIf you are using windows,
netstat -a -o -n
to check for the port usagestaskkill /F /PID <pid>
to kill that processI solved my problem with adding these in build gradle:
defaultConfig {
multiDexEnabled true
dependencies {
compile 'com.android.support:multidex:1.0.0'
another solution can be removing unnecessary libraries
CommonJS modules allow two ways to define exported properties. In either case you are returning an Object/Function. Because functions are first class citizens in JavaScript they to can act just like Objects (technically they are Objects). That said your question about using the new
keywords has a simple answer: Yes. I'll illustrate...
You can either use the exports
variable provided to attach properties to it. Once required in another module those assign properties become available. Or you can assign an object to the module.exports property. In either case what is returned by require()
is a reference to the value of module.exports
.
A pseudo-code example of how a module is defined:
var theModule = {
exports: {}
};
(function(module, exports, require) {
// Your module code goes here
})(theModule, theModule.exports, theRequireFunction);
In the example above module.exports
and exports
are the same object. The cool part is that you don't see any of that in your CommonJS modules as the whole system takes care of that for you all you need to know is there is a module object with an exports property and an exports variable that points to the same thing the module.exports does.
Since you can attach a function directly to module.exports
you can essentially return a function and like any function it could be managed as a constructor (That's in italics since the only difference between a function and a constructor in JavaScript is how you intend to use it. Technically there is no difference.)
So the following is perfectly good code and I personally encourage it:
// My module
function MyObject(bar) {
this.bar = bar;
}
MyObject.prototype.foo = function foo() {
console.log(this.bar);
};
module.exports = MyObject;
// In another module:
var MyObjectOrSomeCleverName = require("./my_object.js");
var my_obj_instance = new MyObjectOrSomeCleverName("foobar");
my_obj_instance.foo(); // => "foobar"
Same thing goes for non-constructor like functions:
// My Module
exports.someFunction = function someFunction(msg) {
console.log(msg);
}
// In another module
var MyModule = require("./my_module.js");
MyModule.someFunction("foobar"); // => "foobar"
the path you are using is not correct you could just open the node_module and find the path of font-awesome. use could use js or svg font but i prefer the css style.
at first use this command to install font-awesome-free
npm install --save-dev @fortawesome/fontawesome-free
after that you can do this
@import "~@fortawesome/fontawesome-free/scss/fontawesome";
@import "~@fortawesome/fontawesome-free/scss/regular";
@import "~@fortawesome/fontawesome-free/scss/solid";
@import "~@fortawesome/fontawesome-free/scss/brands";
and I copy the font path like below this is optional
.copy('node_modules/@fortawesome/fontawesome-free/webfonts', 'public/fonts');
and finally just run the script
npm run dev
or npm run watch
in laravel
Object initializers were introduced in C# 3.0, check which framework version you are targeting.
Just to help if anyone stumble on this question like me, if you want to use if in PostgreSQL, you use "CASE"
select
case
when stage = 1 then 'running'
when stage = 2 then 'done'
when stage = 3 then 'stopped'
else
'not running'
end as run_status from processes
You need to give your submit <input>
a name or it won't be available using $_POST['submit']
:
<p><input type="submit" value="Submit" name="submit" /></p>
One more way to do the same
month1 = month1.toLowerCase();
var months = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
month1 = months.indexOf(month1);
First press the Esc key to exit from edit mode.
Then,
For undo, use u key as many times you want to undo.
For redo, use Ctrl +r key
There are two types of quotes in MySQL:
'
for enclosing string literals`
for enclosing identifiers such as table and column namesAnd then there is "
which is a special case. It could be used for one of above-mentioned purposes at a time depending on MySQL server's sql_mode
:
"
character can be used to enclose string literals just like '
ANSI_QUOTES
mode the "
character can be used to enclose identifiers just like `
SELECT "column" FROM table WHERE foo = "bar"
The query will select the string literal "column"
where column foo
is equal to string "bar"
The query will select the column column
where column foo
is equal to column bar
"
so that your code becomes independent of SQL modesOne of the reasons why everyone has a slightly different definition is because Subversion implements zero support for branches and tags. Subversion basically says: We looked at full-featured branches and tags in other systems and did not found them useful, so we did not implement anything. Just make a copy into a new directory with a name convention instead. Then of course everyone is free to have slightly different conventions. To understand the difference between a real tag and a mere copy + naming convention see the Wikipedia entry Subversion tags & branches.
The best simple approach :
error: function (xhr) {
var err = JSON.parse(xhr.responseText);
alert(err.message);
}
I think you can reset the invocations using Mockito.reset(mockLog). You should call this before every test, so inside @Before would be a good place.
Simply add this
$id = '';
if( isset( $_GET['id'])) {
$id = $_GET['id'];
}
In windows, if you need the a ${PWD} env variable in your docker-compose.yml you can creat a .env file in the same directory as your docker-compose.yml file then insert manualy the location of your folder.
CMD (pwd_var.bat) :
echo PWD=%cd% >> .env
Powershell (pwd_var.ps1) :
$PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'; echo "PWD=$(get-location).path" >> .env
There is more good features hear for docker-compose .env variables:
https://docs.docker.com/compose/reference/envvars/ especially for the COMPOSE_CONVERT_WINDOWS_PATHS
env variable that allow docker compose to accept windows path with baskslash "\"
.
When you want to share a file on windows, the file must exist before sharing it with the container.
The following code solved the problem (with jQuery).
var vhHeight = $("body").height();
var chromeNavbarHeight = vhHeight - window.innerHeight;
$('body').css({ height: window.innerHeight, marginTop: chromeNavbarHeight });
And the other elements use %
as a unit to replace vh
.
How does the max function work?
It looks for the "largest" item in an iterable. I'll assume that you can look up what that is, but if not, it's something you can loop over, i.e. a list or string.
What is use of the keyword key in max function? I know it is also used in context of sort function
Key
is a lambda function that will tell max
which objects in the iterable are larger than others. Say if you were sorting some object that you created yourself, and not something obvious, like integers.
Meaning of the lambda expression? How to read them? How do they work?
That's sort of a larger question. In simple terms, a lambda is a function you can pass around, and have other pieces of code use it. Take this for example:
def sum(a, b, f):
return (f(a) + f(b))
This takes two objects, a
and b
, and a function f
.
It calls f()
on each object, then adds them together. So look at this call:
>>> sum(2, 2, lambda a: a * 2)
8
sum()
takes 2
, and calls the lambda expression on it. So f(a)
becomes 2 * 2
, which becomes 4. It then does this for b
, and adds the two together.
In not so simple terms, lambdas come from lambda calculus, which is the idea of a function that returns a function; a very cool math concept for expressing computation. You can read about that here, and then actually understand it here.
It's probably better to read about this a little more, as lambdas can be confusing, and it's not immediately obvious how useful they are. Check here.
You can do this with pure CSS but you will need to hard code the offset scroll amounts, which may not be ideal should you be changing page content- or should dimensions of your content change on say window resize.
You're likely best placed to use e.g. jQuery, specifically:
$('html, body').stop().animate({
scrollTop: element.offset().top
}, 1000);
A complete implementation may be:
$('#up, #down').on('click', function(e){
e.preventDefault();
var target= $(this).get(0).id == 'up' ? $('#down') : $('#up');
$('html, body').stop().animate({
scrollTop: target.offset().top
}, 1000);
});
Where element
is the target element to scroll to and 1000
is the delay in ms before completion.
The benefit being, no matter what changes to your content dimensions, the function will not need to be altered.
If you want to do this purely in CSS then you'd have a class that you'd assign to each alternate list item. E.g.
<ul>
<li class="alternate"><a href="link">Link 1</a></li>
<li><a href="link">Link 2</a></li>
<li class="alternate"><a href="link">Link 3</a></li>
<li><a href="link">Link 4</a></li>
<li class="alternate"><a href="link">Link 5</a></li>
</ul>
If your list is dynamically generated, this task would be much easier.
If you don't want to have to manually update this content each time, you could use the jQuery library and apply a style alternately to each <li>
item in your list:
<ul id="myList">
<li><a href="link">Link 1</a></li>
<li><a href="link">Link 2</a></li>
<li><a href="link">Link 3</a></li>
<li><a href="link">Link 4</a></li>
<li><a href="link">Link 5</a></li>
</ul>
And your jQuery code:
$(document).ready(function(){
$('#myList li:nth-child(odd)').addClass('alternate');
});
The problem is the indexing subplot
is using. Subplots are counted starting with 1!
Your code thus needs to read
fig=plt.figure(figsize=(15, 6),facecolor='w', edgecolor='k')
for i in range(10):
#this part is just arranging the data for contourf
ind2 = py.find(zz==i+1)
sfr_mass_mat = np.reshape(sfr_mass[ind2],(pixmax_x,pixmax_y))
sfr_mass_sub = sfr_mass[ind2]
zi = griddata(massloclist, sfrloclist, sfr_mass_sub,xi,yi,interp='nn')
temp = 251+i # this is to index the position of the subplot
ax=plt.subplot(temp)
ax.contourf(xi,yi,zi,5,cmap=plt.cm.Oranges)
plt.subplots_adjust(hspace = .5,wspace=.001)
#just annotating where each contour plot is being placed
ax.set_title(str(temp))
Note the change in the line where you calculate temp
Here's a one line solution to remove columns based on duplicate column names:
df = df.loc[:,~df.columns.duplicated()]
How it works:
Suppose the columns of the data frame are ['alpha','beta','alpha']
df.columns.duplicated()
returns a boolean array: a True
or False
for each column. If it is False
then the column name is unique up to that point, if it is True
then the column name is duplicated earlier. For example, using the given example, the returned value would be [False,False,True]
.
Pandas
allows one to index using boolean values whereby it selects only the True
values. Since we want to keep the unduplicated columns, we need the above boolean array to be flipped (ie [True, True, False] = ~[False,False,True]
)
Finally, df.loc[:,[True,True,False]]
selects only the non-duplicated columns using the aforementioned indexing capability.
Note: the above only checks columns names, not column values.
To add a small bit to Sydius' answer, smart pointers will often provide a more stable solution by catching many easy to make errors. Raw pointers will have some perfromance advantages and can be more flexible in certain circumstances. You may also be forced to use raw pointers when linking into certain 3rd party libraries.
In general, you're better off validating URLs using built-in library or framework functions, rather than rolling your own regular expressions to do this - see What is the best regular expression to check if a string is a valid URL for details.
If you are keen on doing this, though, check out this question:
Getting parts of a URL (Regex)
Then, once you're satisfied with the URL (by whatever means you used to validate it), you could either use a simple "endswith" type string operator to check the extension, or a simple regex like
(?i)\.(jpg|png|gif)$
Try this (but once clicked, it is not reversible):
HTML:
<a id="test"><img src="normal-image.png"/></a>
CSS:
a#test {
border: 0;
}
a#test:visited img, a#test:active img {
background-image: url(clicked-image.png);
}
It's probably easiest to create your query object directly as:
Test.find({
$and: [
{ $or: [{a: 1}, {b: 1}] },
{ $or: [{c: 1}, {d: 1}] }
]
}, function (err, results) {
...
}
But you can also use the Query#and
helper that's available in recent 3.x Mongoose releases:
Test.find()
.and([
{ $or: [{a: 1}, {b: 1}] },
{ $or: [{c: 1}, {d: 1}] }
])
.exec(function (err, results) {
...
});
Mac Cmd+Shift+\
Windows Ctrl+Shift+\
Windows with spanish keyboard Ctrl+Shift+|
Windows with german keyboard Ctrl+Shift+^
Alternatively, you can do:
Ctrl+Shift+p
And select
Preferences: Open Keyboard Shortcuts
There you will be able to see all the shortcuts, and create your own.
Haven't seen any fully-native solutions, so here's one:
return str == null || str.chars().allMatch(Character::isWhitespace);
Basically, use the native Character.isWhitespace() function. From there, you can achieve different levels of optimization, depending on how much it matters (I can assure you that in 99.99999% of use cases, no further optimization is necessary):
return str == null || str.length() == 0 || str.chars().allMatch(Character::isWhitespace);
Or, to be really optimal (but hecka ugly):
int len;
if (str == null || (len = str.length()) == 0) return true;
for (int i = 0; i < len; i++) {
if (!Character.isWhitespace(str.charAt(i))) return false;
}
return true;
One thing I like to do:
Optional<String> notBlank(String s) {
return s == null || s.chars().allMatch(Character::isWhitepace))
? Optional.empty()
: Optional.of(s);
}
...
notBlank(myStr).orElse("some default")
function removeParam(parameter)
{
var url=document.location.href;
var urlparts= url.split('?');
if (urlparts.length>=2)
{
var urlBase=urlparts.shift();
var queryString=urlparts.join("?");
var prefix = encodeURIComponent(parameter)+'=';
var pars = queryString.split(/[&;]/g);
for (var i= pars.length; i-->0;)
if (pars[i].lastIndexOf(prefix, 0)!==-1)
pars.splice(i, 1);
url = urlBase+'?'+pars.join('&');
window.history.pushState('',document.title,url); // added this line to push the new url directly to url bar .
}
return url;
}
This will resolve your problem
For CentOS:
sudo systemctl restart jenkins
sudo systemctl status Jenkins
Jenkins will be active and up and running on some PID.
if (obj instanceof C) {
//your code
}
My first post... UDF I managed quickly to compile. Usage: Select 3D range as normal and enclose is into quotation marks like below...
=CountIf3D("'StartSheet:EndSheet'!G16:G878";"Criteria")
Advisably sheets to be adjacent to avoid unanticipated results.
Public Function CountIf3D(SheetstoCount As String, CriteriaToUse As Variant)
Dim sStarSheet As String, sEndSheet As String, sAddress As String
Dim lColonPos As Long, lExclaPos As Long, cnt As Long
lColonPos = InStr(SheetstoCount, ":") 'Finding ':' separating sheets
lExclaPos = InStr(SheetstoCount, "!") 'Finding '!' separating address from the sheets
sStarSheet = Mid(SheetstoCount, 2, lColonPos - 2) 'Getting first sheet's name
sEndSheet = Mid(SheetstoCount, lColonPos + 1, lExclaPos - lColonPos - 2) 'Getting last sheet's name
sAddress = Mid(SheetstoCount, lExclaPos + 1, Len(SheetstoCount) - lExclaPos) 'Getting address
cnt = 0
For i = Sheets(sStarSheet).Index To Sheets(sEndSheet).Index
cnt = cnt + Application.CountIf(Sheets(i).Range(sAddress), CriteriaToUse)
Next
CountIf3D = cnt
End Function
The app is stored in %LocalAppData%
in your %UserProfile%
. So the full path could be:
C:\Users\username\AppData\Local\GitHub
Try starting with the Percona wizard and comparing their recommendations against your current settings one by one. Don't worry there aren't as many applicable settings as you might think.
https://tools.percona.com/wizard
Update circa 2020: Sorry, this tool reached it's end of life: https://www.percona.com/blog/2019/04/22/end-of-life-query-analyzer-and-mysql-configuration-generator/
Everyone points to key_buffer_size
first which you have addressed. With 96GB memory I'd be wary of any tiny default value (likely to be only 96M!).
Launch4j works on both Windows and Linux/Mac. But if you're running Linux/Mac, there is a way to embed your jar into a shell script that performs the autolaunch for you, so you have only one runnable file:
exestub.sh:
#!/bin/sh
MYSELF=`which "$0" 2>/dev/null`
[ $? -gt 0 -a -f "$0" ] && MYSELF="./$0"
JAVA_OPT=""
PROG_OPT=""
# Parse options to determine which ones are for Java and which ones are for the Program
while [ $# -gt 0 ] ; do
case $1 in
-Xm*) JAVA_OPT="$JAVA_OPT $1" ;;
-D*) JAVA_OPT="$JAVA_OPT $1" ;;
*) PROG_OPT="$PROG_OPT $1" ;;
esac
shift
done
exec java $JAVA_OPT -jar $MYSELF $PROG_OPT
Then you create your runnable file from your jar:
$ cat exestub.sh myrunnablejar.jar > myrunnable
$ chmod +x myrunnable
It works the same way launch4j works: because a jar has a zip format, which header is located at the end of the file. You can have any header you want (either binary executable or, like here, shell script) and run java -jar <myexe>
, as <myexe>
is a valid zip/jar file.
The more safe method is to run pip though a python module:
python -m pip install -U pip
On windows there seem to be a problem with binaries that try to replace themselves, this method works around that limitation.
Angular have a built-in function called arrayRemove
, in your case the method can simply be:
arrayRemove($scope.persons, person)
Here's a way to do this using TPL. No need to create/dispose of a timer, etc:
void ScheduleSomething()
{
var runAt = DateTime.Today + TimeSpan.FromHours(16);
if (runAt <= DateTime.Now)
{
DoSomething();
}
else
{
var delay = runAt - DateTime.Now;
System.Threading.Tasks.Task.Delay(delay).ContinueWith(_ => DoSomething());
}
}
void DoSomething()
{
// do somethig
}
Instead of
Player[PlayerCount] thePlayers;
you want
Player[] thePlayers = new Player[PlayerCount];
and
for(int i = 0; i < PlayerCount ; i++)
{
thePlayers[i] = new Player(i);
}
return thePlayers;
should return the array initialized with Player instances.
EDIT:
Do check out this table on wikipedia on naming conventions for java that is widely used.
Ever want to know what the hell that python script is doing? Enter the Inspect Shell. Inspect Shell lets you print/alter globals and run functions without interrupting the running script. Now with auto-complete and command history (only on linux).
Inspect Shell is not a pdb-style debugger.
https://github.com/amoffat/Inspect-Shell
You could use that (and your wristwatch).
SerialPort (RS-232 Serial COM Port) in C# .NET
This article explains how to use the SerialPort
class in .NET to read and write data, determine what serial ports are available on your machine, and how to send files. It even covers the pin assignments on the port itself.
Example Code:
using System;
using System.IO.Ports;
using System.Windows.Forms;
namespace SerialPortExample
{
class SerialPortProgram
{
// Create the serial port with basic settings
private SerialPort port = new SerialPort("COM1",
9600, Parity.None, 8, StopBits.One);
[STAThread]
static void Main(string[] args)
{
// Instatiate this class
new SerialPortProgram();
}
private SerialPortProgram()
{
Console.WriteLine("Incoming Data:");
// Attach a method to be called when there
// is data waiting in the port's buffer
port.DataReceived += new
SerialDataReceivedEventHandler(port_DataReceived);
// Begin communications
port.Open();
// Enter an application loop to keep this thread alive
Application.Run();
}
private void port_DataReceived(object sender,
SerialDataReceivedEventArgs e)
{
// Show all the incoming data in the port's buffer
Console.WriteLine(port.ReadExisting());
}
}
}
While a set
may be what you want structure-wise, the question is what is faster. A list is faster. Your example code doesn't accurately compare set
vs list
because you're converting from a list to a set in set_loop
, and then you're creating the list
you'll be looping through in list_loop
. The set and list you iterate through should be constructed and in memory ahead of time, and simply looped through to see which data structure is faster at iterating:
ids_list = range(1000000)
ids_set = set(ids)
def f(x):
for i in x:
pass
%timeit f(ids_set)
#1 loops, best of 3: 214 ms per loop
%timeit f(ids_list)
#1 loops, best of 3: 176 ms per loop
You were missing a few important sonar properties, Here is a sample from one of my builds:
sonar.jdbc.dialect=mssql
sonar.projectKey=projectname
sonar.projectName=Project Name
sonar.projectVersion=1.0
sonar.sources=src
sonar.language=java
sonar.binaries=build/classes
sonar.tests=junit
sonar.dynamicAnalysis=reuseReports
sonar.junit.reportsPath=build/test-reports
sonar.java.coveragePlugin=jacoco
sonar.jacoco.reportPath=build/test-reports/jacoco.exec
The error in Jenkins console output can be pretty useful for getting code coverage to work.
Project coverage is set to 0% since there is no directories with classes.
Indicates that you have not set the Sonar.Binaries property correctly
No information about coverage per test
Indicates you have not set the Sonar.Tests property properly
Coverage information was not collected. Perhaps you forget to include debug information into compiled classes? Indicates that the sonar.binaries property was set correctly, but those files were not compiled in debug mode, and they need to be
There are a series of inbuilt functions for coloring the console log:
//For pink background and red text
console.error("Hello World");
//For yellow background and brown text
console.warn("Hello World");
//For just a INFO symbol at the beginning of the text
console.info("Hello World");
//for custom colored text
console.log('%cHello World','color:blue');
//here blue could be replaced by any color code
//for custom colored text with custom background text
console.log('%cHello World','background:red;color:#fff')
You can add security provider by editing java.security with using following code with creating static block:
static {
Security.addProvider(new BouncyCastleProvider());
}
If you are using maven project, then you will have to add dependency for BouncyCastleProvider as follows in pom.xml file of your project.
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.47</version>
</dependency>
If you are using normal java project, then you can add download bcprov-jdk15on-147.jar from the link given below and edit your classpath.
http://www.java2s.com/Code/Jar/b/Downloadbcprovextjdk15on147jar.htm
Try javax.net.ssl.keyStorePassword
instead of javax.net.ssl.keyPassword
: the latter isn't mentioned in the JSSE ref guide.
The algorithms you mention should be there by default using the default security providers. NoSuchAlgorithmException
s are often cause by other underlying exceptions (file not found, wrong password, wrong keystore type, ...). It's useful to look at the full stack trace.
You could also use -Djavax.net.debug=ssl
, or at least -Djavax.net.debug=ssl,keymanager
, to get more debugging information, if the information in the stack trace isn't sufficient.
Try this one
$('<div></div>').appendTo('body')
.html('<div><h6>Yes or No?</h6></div>')
.dialog({
modal: true, title: 'message', zIndex: 10000, autoOpen: true,
width: 'auto', resizable: false,
buttons: {
Yes: function () {
doFunctionForYes();
$(this).dialog("close");
},
No: function () {
doFunctionForNo();
$(this).dialog("close");
}
},
close: function (event, ui) {
$(this).remove();
}
});
/**
* Loads data asynchronously via JSONP.
*/
const load = (() => {
let index = 0;
const timeout = 5000;
return url => new Promise((resolve, reject) => {
const callback = '__callback' + index++;
const timeoutID = window.setTimeout(() => {
reject(new Error('Request timeout.'));
}, timeout);
window[callback] = response => {
window.clearTimeout(timeoutID);
resolve(response.data);
};
const script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.src = url + (url.indexOf('?') === -1 ? '?' : '&') + 'callback=' + callback;
document.getElementsByTagName('head')[0].appendChild(script);
});
})();
const data = await load('http://api.github.com/orgs/kriasoft');
As this question comes up again and again, here is one more answer. I hope to add something for beginners wondering about "best practice" here.
SELECT COUNT(*) FROM something
counts records which is an easy task.
SELECT COUNT(1) FROM something
retrieves a 1 per record and than counts the 1s that are not null, which is essentially counting records, only more complicated.
Having said this: Good dbms notice that the second statement will result in the same count as the first statement and re-interprete it accordingly, as not to do unnecessary work. So usually both statements will result in the same execution plan and take the same amount of time.
However from the point of readability you should use the first statement. You want to count records, so count records, not expressions. Use COUNT(expression) only when you want to count non-null occurences of something.
If it's just a single character 0-9 in ASCII, then subtracting the the value of the ASCII zero character from ASCII value should work fine.
If you want to convert larger numbers then the following will do:
char *string = "24";
int value;
int assigned = sscanf(string, "%d", &value);
** don't forget to check the status (which should be 1 if it worked in the above case).
Paul.
Actually, a new technique came out recently. This article will answer your questions: http://www.zeldman.com/2012/03/01/replacing-the-9999px-hack-new-image-replacement
.hide-text {
text-indent: 100%;
white-space: nowrap;
overflow: hidden;
}
It is accessible, an has better performance than -99999px.
Update: As @deathlock mentions in the comment area, the author of the fix above (Scott Kellum), has suggested using a transparent font: http://scottkellum.com/2013/10/25/the-new-kellum-method.html.
(i, j, n + 1) = k * b_xyt(xi, yi, tn) / (4 * hx * hy) * U_matrix(i + 1, j + 1, n) + _
(k * (a_xyt(xi, yi, tn) / hx ^ 2 + d_xyt(xi, yi, tn) / (2 * hx)))
To continue a statement from one line to the next, type a space followed by the line-continuation character [the underscore character on your keyboard (_)].
You can break a line at an operator, list separator, or period.
Use display: inline-block;
Explanation:
The label
is an inline element, meaning it is only as big as it needs to be.
Set the display
property to either inline-block
or block
in order for the width
property to take effect.
Example:
#report-upload-form {_x000D_
background-color: #316091;_x000D_
color: #ddeff1;_x000D_
font-weight: bold;_x000D_
margin: 23px auto 0 auto;_x000D_
border-radius: 10px;_x000D_
width: 650px;_x000D_
box-shadow: 0 0 2px 2px #d9d9d9;_x000D_
_x000D_
}_x000D_
_x000D_
#report-upload-form label {_x000D_
padding-left: 26px;_x000D_
width: 125px;_x000D_
text-transform: uppercase;_x000D_
display: inline-block;_x000D_
}_x000D_
_x000D_
#report-upload-form input[type=text], _x000D_
#report-upload-form input[type=file],_x000D_
#report-upload-form textarea {_x000D_
width: 305px;_x000D_
}
_x000D_
<form id="report-upload-form" method="POST" action="" enctype="multipart/form-data">_x000D_
<p><label for="id_title">Title:</label> <input id="id_title" type="text" class="input-text" name="title"></p>_x000D_
<p><label for="id_description">Description:</label> <textarea id="id_description" rows="10" cols="40" name="description"></textarea></p>_x000D_
<p><label for="id_report">Upload Report:</label> <input id="id_report" type="file" class="input-file" name="report"></p>_x000D_
</form>
_x000D_
link_to "+ Service", controller_action_path(:account_id => acct.id)
If it is still not working check the path:
$ rake routes
Try
isSubstring = first in theOther
This is a modified version of the Nibble to Hex method
void hexArrayToStr(unsigned char* info, unsigned int infoLength, char **buffer) {
const char* pszNibbleToHex = {"0123456789ABCDEF"};
int nNibble, i;
if (infoLength > 0) {
if (info != NULL) {
*buffer = (char *) malloc((infoLength * 2) + 1);
buffer[0][(infoLength * 2)] = 0;
for (i = 0; i < infoLength; i++) {
nNibble = info[i] >> 4;
buffer[0][2 * i] = pszNibbleToHex[nNibble];
nNibble = info[i] & 0x0F;
buffer[0][2 * i + 1] = pszNibbleToHex[nNibble];
}
} else {
*buffer = NULL;
}
} else {
*buffer = NULL;
}
}
I had a slightly different requirement, to parse an encoded dictionary/hashtable with escaped commas, like this:
"1=This is something, 2=This is something,,with an escaped comma, 3=This is something else"
I think this is an elegant solution, with a trick that avoids a lot of regex complexity:
if (string.IsNullOrEmpty(encodedValues))
{
return null;
}
else
{
var retVal = new Dictionary<int, string>();
var reFields = new Regex(@"([0-9]+)\=(([A-Za-z0-9\s]|(,,))+),");
foreach (Match match in reFields.Matches(encodedValues + ","))
{
var id = match.Groups[1].Value;
var value = match.Groups[2].Value;
retVal[int.Parse(id)] = value.Replace(",,", ",");
}
return retVal;
}
I think it can be adapted to the original question with an expression like @"([0-9]+),\s?"
and parse on Groups[0]
.
I hope it's helpful to somebody and thanks for the tips on getting it close to there, especially Asaph!
Another way to find public IP would be to use uri
module:
- name: Find my public ip
uri:
url: http://ifconfig.me/ip
return_content: yes
register: ip_response
Your IP will be in ip_response.content
You are trying to add an integer into an ArrayList
that takes an array of integers Integer[]
. It should be
ArrayList<Integer> list = new ArrayList<>();
or better
List<Integer> list = new ArrayList<>();
ulimit -c unlimited
made the core file correctly appear in the current directory after a "core dumped".
The question comes down to what you're going to do with the files.
Under Windows, any directory with more than 2k files tends to open slowly for me in Explorer. If they're all image files, more than 1k tend to open very slowly in thumbnail view.
At one time, the system-imposed limit was 32,767. It's higher now, but even that is way too many files to handle at one time under most circumstances.
You can install the Open Folder Context Menus for VS Code extension from Chris Dias
https://marketplace.visualstudio.com/items?itemName=chrisdias.vscode-opennewinstance
Please check the sample code for the Google Maps Android API v2. Using this will solve your problem.
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
mMap.setMyLocationEnabled(true);
// Check if we were successful in obtaining the map.
if (mMap != null) {
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
@Override
public void onMyLocationChange(Location arg0) {
mMap.addMarker(new MarkerOptions().position(new LatLng(arg0.getLatitude(), arg0.getLongitude())).title("It's Me!"));
}
});
}
}
}
Call this function in onCreate
function.
Many ways to do this. ismember is the first that comes to mind, since it is a set membership action you wish to take. Thus
X = primes(20);
ismember([15 17],X)
ans =
0 1
Since 15 is not prime, but 17 is, ismember has done its job well here.
Of course, find (or any) will also work. But these are not vectorized in the sense that ismember was. We can test to see if 15 is in the set represented by X, but to test both of those numbers will take a loop, or successive tests.
~isempty(find(X == 15))
~isempty(find(X == 17))
or,
any(X == 15)
any(X == 17)
Finally, I would point out that tests for exact values are dangerous if the numbers may be true floats. Tests against integer values as I have shown are easy. But tests against floating point numbers should usually employ a tolerance.
tol = 10*eps;
any(abs(X - 3.1415926535897932384) <= tol)
try some thing like blow:
SString otherParametersUrServiceNeed = "Company=acompany&Lng=test&MainPeriod=test&UserID=123&CourseDate=8:10:10";
String request = "http://android.schoolportal.gr/Service.svc/SaveValues";
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(otherParametersUrServiceNeed.getBytes().length));
connection.setUseCaches (false);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(otherParametersUrServiceNeed);
JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");
wr.writeBytes(jsonParam.toString());
wr.flush();
wr.close();
References :
You guys are forgetting that the colon is also used in the ternary operator (though I don't know if jquery uses it for this purpose).
the ternary operator is an expression form (expressions return a value) of an if/then statement. it's used like this:
var result = (condition) ? (value1) : (value2) ;
A ternary operator could also be used to produce side effects just like if/then, but this is profoundly bad practice.
I had the same problem. I found solution here http://jakob.engbloms.se/archives/1403
c:\msysgit\bin>rebase.exe -b 0x50000000 msys-1.0.dll
For me solution was slightly different. It was
C:\Program Files (x86)\Git\bin>rebase.exe -b 0x50000000 msys-1.0.dll
Before you rebase dlls, you should make sure it is not in use:
tasklist /m msys-1.0.dll
And make a backup:
copy msys-1.0.dll msys-1.0.dll.bak
If the rebase command fails with something like:
ReBaseImage (msys-1.0.dll) failed with last error = 6
You will need to perform the following steps in order:
If any issue run the commands as Administrator
I believe best practice these days is H/5 * * * *
, which means every 5 minutes with a hashing factor to avoid all jobs starting at EXACTLY the same time.
Just for the sake of completeness, we can use the operators [
and [[
:
set.seed(1)
df <- data.frame(v1 = runif(10), v2 = letters[1:10])
Several options
df[df[1] < 0.5 | df[2] == "g", ]
df[df[[1]] < 0.5 | df[[2]] == "g", ]
df[df["v1"] < 0.5 | df["v2"] == "g", ]
df$name is equivalent to df[["name", exact = FALSE]]
Using dplyr
:
library(dplyr)
filter(df, v1 < 0.5 | v2 == "g")
Using sqldf
:
library(sqldf)
sqldf('SELECT *
FROM df
WHERE v1 < 0.5 OR v2 = "g"')
Output for the above options:
v1 v2
1 0.26550866 a
2 0.37212390 b
3 0.20168193 e
4 0.94467527 g
5 0.06178627 j
you should android sdk manager install 4.2 api 17 -> ARM EABI v7a System Image
if not installed ARM EABI v7a System Image, you should install all.
It's AddHeader, not AppendHeader.
<%@ Language=VBScript %>
<% Option Explicit
Response.ContentType = "application/vnd.ms-excel"
Response.AddHeader "Content-Disposition", "attachment; filename=excelTest.xls"
%>
<table>
<tr>
<td>Test</td>
</tr>
</table>
Update: I've written a blog post about how to generate Excel files in ASP Classic. It contains a rather useful piece of code to generate both xls and csv files.
A bit offtopic but might help someone. If you need to pass password and port I suggest using sshpass
package. Command line command would look like this:
sshpass -p "password" rsync -avzh -e 'ssh -p PORT312' [email protected]:/dir_on_host/
From a button in view call .click(call some java script). From there call controller method by window.location.href = 'Controller/Method';
In controller either do the database call and get the datatable or call some method get the data from database table to a datatable and then do following,
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
//Build the CSV file data as a Comma separated string.
string csv = string.Empty;
foreach (DataColumn column in dt.Columns)
{
//Add the Header row for CSV file.
csv += column.ColumnName + ',';
}
//Add new line.
csv += "\r\n";
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn column in dt.Columns)
{
//Add the Data rows.
csv += row[column.ColumnName].ToString().Replace(",", ";") + ',';
}
//Add new line.
csv += "\r\n";
}
//Download the CSV file.
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=SqlExport"+DateTime.Now+".csv");
Response.Charset = "";
//Response.ContentType = "application/text";
Response.ContentType = "application/x-msexcel";
Response.Output.Write(csv);
Response.Flush();
Response.End();
}
The following configs works on Cent OS 6 or earlier
As stated above first have to disable selinux.
Step 1 nano /etc/sysconfig/selinux
Make sure the file has this configurations
SELINUX=disabled
SELINUXTYPE=targeted
Then restart the system
Step 2
iptables -A INPUT -m state --state NEW -p tcp --dport 8080 -j ACCEPT
Step 3
sudo service iptables save
For Cent OS 7
step 1
firewall-cmd --zone=public --permanent --add-port=8080/tcp
Step 2
firewall-cmd --reload
This one helped me,
res.format({
json:function(){
var responseData = {};
responseData['status'] = 200;
responseData['outputPath'] = outputDirectoryPath;
responseData['sourcePath'] = url;
responseData['message'] = 'Scraping of requested resource initiated.';
responseData['logfile'] = logFileName;
res.json(JSON.stringify(responseData));
}
});
No fancy shiz required:
HTML:
<form method="post" action="/api/admin/image" enctype="multipart/form-data">
<input type="hidden" name="url" value="<%= boxes[i].url %>" />
<input class="image-file-chosen" type="text" />
<br />
<input class="btn image-file-button" value="Choose Image" />
<input class="image-file hide" type="file" name="image"/> <!-- Hidden -->
<br />
<br />
<input class="btn" type="submit" name="image" value="Upload" />
<br />
</form>
JS:
$('.image-file-button').each(function() {
$(this).off('click').on('click', function() {
$(this).siblings('.image-file').trigger('click');
});
});
$('.image-file').each(function() {
$(this).change(function () {
$(this).siblings('.image-file-chosen').val(this.files[0].name);
});
});
CAUTION: The three form elements in question MUST be siblings of each other (.image-file-chosen, .image-file-button, .image-file)
When using the MVVM Command pattern for Button function (recommended practice), a simple way to trigger the effect of the Button is as follows:
someButton.Command.Execute(someButton.CommandParameter);
This will use the Command object which the button triggers and pass the CommandParameter defined by the XAML.
I have created a module for anuglar2 autocomplete In this module you can use array, or url npm link : ang2-autocomplete
Create an attribute that contains a list of the parameters, like so:
<script src="http://path/to/widget.js" data-params="1, 3"></script>
Then, in your JavaScript, get the parameters as an array:
var script = document.currentScript ||
/*Polyfill*/ Array.prototype.slice.call(document.getElementsByTagName('script')).pop();
var params = (script.getAttribute('data-params') || '').split(/, */);
params[0]; // -> 1
params[1]; // -> 3
At runtime, no, you can't.
However via reflection the type parameters are accessible. Try
for(Field field : this.getDeclaredFields()) {
System.out.println(field.getGenericType())
}
The method getGenericType()
returns a Type object. In this case, it will be an instance of ParametrizedType
, which in turn has methods getRawType()
(which will contain List.class
, in this case) and getActualTypeArguments()
, which will return an array (in this case, of length one, containing either String.class
or Integer.class
).
You can run Rundll32.exe for IE Options control panel applet and achieve following tasks.
Deletes ALL History - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 255
Deletes History Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 1
Deletes Cookies Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 2
Deletes Temporary Internet Files Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8
Deletes Form Data Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 16
Deletes Password History Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 32
Yes, you can use @ResponseBody with void
return type:
@RequestMapping(value = "/updateSomeData" method = RequestMethod.POST)
@ResponseBody
public void updateDataThatDoesntRequireClientToBeNotified(...) {
...
}
None of the suggestions worked for me until I ran the command "gradle cleanIdeaModule ideaModule" info here: https://docs.gradle.org/current/userguide/idea_plugin.html
The angular way is shown in the angular docs :)
https://docs.angularjs.org/api/ng/directive/ngReadonly
Here is the example they use:
<body>
Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/>
<input type="text" ng-readonly="checked" value="I'm Angular"/>
</body>
Basically the angular way is to create a model object that will hold whether or not the input should be readonly and then set that model object accordingly. The beauty of angular is that most of the time you don't need to do any dom manipulation. You just have angular render the view they way your model is set (let angular do the dom manipulation for you and keep your code clean).
So basically in your case you would want to do something like below or check out this working example.
<button ng-click="isInput1ReadOnly = !isInput1ReadOnly">Click Me</button>
<input type="text" ng-readonly="isInput1ReadOnly" value="Angular Rules!"/>
You should use DateTime.TryParseExcact
if you know the format, or if not and want to use the system settings DateTime.TryParse
. And to print the date,DateTime.ToString
with the right format in the argument. To get the year, month or day you have DateTime.Year
, DateTime.Month
or DateTime.Day
.
See DateTime Structures in MSDN for additional references.
Try this:
<select>
<option value="">
<option>Option 1
<option>Option 2
<option>Option 3
</select>
Validates in HTML5. Works with required
attribute in select element. Can be re-selected. Works in Google Chrome 45, Internet Explorer 11, Edge, Firefox 41.
Use the noinline
attribute:
int func(int arg) __attribute__((noinline))
{
}
You should probably use it both when you declare the function for external use and when you write the function.
Alternative to @MinhKha's answer:
It can be much cleaner with useReducer
:
const [, forceUpdate] = useReducer(x => x + 1, 0);
Usage:
forceUpdate()
- cleaner without params
The same way Boston came up with its street plan. They followed the cow paths already there, and built houses where the streets weren't, and after a while it was too much trouble to change.
Try this for a friendly representation of time differences (in milliseconds):
String friendlyTimeDiff(long timeDifferenceMilliseconds) {
long diffSeconds = timeDifferenceMilliseconds / 1000;
long diffMinutes = timeDifferenceMilliseconds / (60 * 1000);
long diffHours = timeDifferenceMilliseconds / (60 * 60 * 1000);
long diffDays = timeDifferenceMilliseconds / (60 * 60 * 1000 * 24);
long diffWeeks = timeDifferenceMilliseconds / (60 * 60 * 1000 * 24 * 7);
long diffMonths = (long) (timeDifferenceMilliseconds / (60 * 60 * 1000 * 24 * 30.41666666));
long diffYears = timeDifferenceMilliseconds / ((long)60 * 60 * 1000 * 24 * 365);
if (diffSeconds < 1) {
return "less than a second";
} else if (diffMinutes < 1) {
return diffSeconds + " seconds";
} else if (diffHours < 1) {
return diffMinutes + " minutes";
} else if (diffDays < 1) {
return diffHours + " hours";
} else if (diffWeeks < 1) {
return diffDays + " days";
} else if (diffMonths < 1) {
return diffWeeks + " weeks";
} else if (diffYears < 1) {
return diffMonths + " months";
} else {
return diffYears + " years";
}
}
You could try setInterval() instead:
var i = setInterval(function(){
//Call ajax here
},10000)
$emit
It dispatches an event name upwards through the scope hierarchy and notify to the registered $rootScope.Scope
listeners. The event life cycle starts at the scope on which $emit
was called. The event traverses upwards toward the root scope and calls all registered listeners along the way. The event will stop propagating if one of the listeners cancels it.
$broadcast
It dispatches an event name downwards to all child scopes (and their children) and notify to the registered $rootScope.Scope
listeners. The event life cycle starts at the scope on which $broadcast
was called. All listeners for the event on this scope get notified. Afterwards, the event traverses downwards toward the child scopes and calls all registered listeners along the way. The event cannot be canceled.
$on
It listen on events of a given type. It can catch the event dispatched by $broadcast
and $emit
.
Visual demo:
Demo working code, visually showing scope tree (parent/child relationship):
http://plnkr.co/edit/am6IDw?p=preview
Demonstrates the method calls:
$scope.$on('eventEmitedName', function(event, data) ...
$scope.broadcastEvent
$scope.emitEvent
If you want a fairly advanced tool to do some serious poking around, look at the Memory Analyzer project at Eclipse, contributed to them by SAP.
Some of what you can do is mind-blowingly good for finding memory leaks etc -- including running a form of limited SQL (OQL) against the in-memory objects, i.e.
SELECT toString(firstName) FROM com.yourcompany.somepackage.User
Totally brilliant.
Scenario:
1) client-service-1.0-SNAPSHOT.jar
has dependency read-classpath-resource-1.0-SNAPSHOT.jar
2) we want to read content of class path resources (sample.txt
) of read-classpath-resource-1.0-SNAPSHOT.jar
through client-service-1.0-SNAPSHOT.jar
.
3) read-classpath-resource-1.0-SNAPSHOT.jar
has src/main/resources/sample.txt
Here is working sample code I prepared, after 2-3days wasting my development time, I found the complete end-to-end solution, hope this helps to save your time
1.pom.xml
of read-classpath-resource-1.0-SNAPSHOT.jar
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>jar-classpath-resource</groupId>
<artifactId>read-classpath-resource</artifactId>
<version>1.0-SNAPSHOT</version>
<name>classpath-test</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<org.springframework.version>4.3.3.RELEASE</org.springframework.version>
<mvn.release.plugin>2.5.1</mvn.release.plugin>
<output.path>${project.artifactId}</output.path>
<io.dropwizard.version>1.0.3</io.dropwizard.version>
<commons-io.verion>2.4</commons-io.verion>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.verion}</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
<version>${mvn.release.plugin}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>2.5</version>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<useUniqueVersions>false</useUniqueVersions>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<mainClass>demo.read.classpath.resources.ClassPathResourceReadTest</mainClass>
</manifest>
<manifestEntries>
<Implementation-Artifact-Id>${project.artifactId}</Implementation-Artifact-Id>
<Class-Path>sample.txt</Class-Path>
</manifestEntries>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.2</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>demo.read.classpath.resources.ClassPathResourceReadTest</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
2.ClassPathResourceReadTest.java
class in read-classpath-resource-1.0-SNAPSHOT.jar
that loads the class path resources file content.
package demo.read.classpath.resources;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public final class ClassPathResourceReadTest {
public ClassPathResourceReadTest() throws IOException {
InputStream inputStream = getClass().getResourceAsStream("/sample.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
List<Object> list = new ArrayList<>();
String line;
while ((line = reader.readLine()) != null) {
list.add(line);
}
for (Object s1: list) {
System.out.println("@@@ " +s1);
}
System.out.println("getClass().getResourceAsStream('/sample.txt') lines: "+list.size());
}
}
3.pom.xml
of client-service-1.0-SNAPSHOT.jar
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>client-service</groupId>
<artifactId>client-service</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>jar-classpath-resource</groupId>
<artifactId>read-classpath-resource</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>2.5</version>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<useUniqueVersions>false</useUniqueVersions>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<mainClass>com.crazy.issue.client.AccessClassPathResource</mainClass>
</manifest>
<manifestEntries>
<Implementation-Artifact-Id>${project.artifactId}</Implementation-Artifact-Id>
<Implementation-Source-SHA>${buildNumber}</Implementation-Source-SHA>
<Class-Path>sample.txt</Class-Path>
</manifestEntries>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.2</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>com.crazy.issue.client.AccessClassPathResource</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
4.AccessClassPathResource.java
instantiate ClassPathResourceReadTest.java
class where, it is going to load sample.txt
and prints its content also.
package com.crazy.issue.client;
import demo.read.classpath.resources.ClassPathResourceReadTest;
import java.io.IOException;
public class AccessClassPathResource {
public static void main(String[] args) throws IOException {
ClassPathResourceReadTest test = new ClassPathResourceReadTest();
}
}
5.Run Executable jar as follows:
[ravibeli@localhost lib]$ java -jar client-service-1.0-SNAPSHOT.jar
****************************************
I am in resources directory of read-classpath-resource-1.0-SNAPSHOT.jar
****************************************
3) getClass().getResourceAsStream('/sample.txt'): 3
Declaring variables inside or outside of a loop, It's the result of JVM specifications But in the name of best coding practice it is recommended to declare the variable in the smallest possible scope (in this example it is inside the loop, as this is the only place where the variable is used). Declaring objects in the smallest scope improve readability. The scope of local variables should always be the smallest possible. In your example I presume str is not used outside of the while loop, otherwise you would not be asking the question, because declaring it inside the while loop would not be an option, since it would not compile.
Does it make a difference if I declare variables inside or outside a , Does it make a difference if I declare variables inside or outside a loop in Java? Is this for(int i = 0; i < 1000; i++) { int At the level of the individual variable there is no significant difference in effeciency, but if you had a function with 1000 loops and 1000 variables (never mind the bad style implied) there could be systemic differences because all the lives of all the variables would be the same instead of overlapped.
Declaring Loop Control Variables Inside the for Loop, When you declare a variable inside a for loop, there is one important point to remember: the scope of that variable ends when the for statement does. (That is, the scope of the variable is limited to the for loop.) This Java Example shows how to declare multiple variables in Java For loop using declaration block.
Using text/csv
is the most appropriate type.
You should also consider adding a Content-Disposition
header to the response. Often a text/csv will be loaded by a Internet Explorer directly into a hosted instance of Excel. This may or may not be a desirable result.
Response.AddHeader("Content-Disposition", "attachment;filename=myfilename.csv");
The above will cause a file "Save as" dialog to appear which may be what you intend.
You need to name the file in both directory paths.
scp [email protected]:/dir/of/file.txt \local\dir\file.txt
I'm using EasyPHP in making my Thesis about Content Management System. So far, this tool is very good and easy to use.
Try this process -
Open the Query Analyzer
Start --> Programs --> MS SQL Server --> Query Analyzer
Once opened, connect to the database that you are wish running the script on.
Next, open the SQL file using File --> Open option. Select .sql file.
Once it is open, you can execute the file by pressing F5.
If you are using react's templates, where the end of your react file looks like this: export default SomeComponent
you need to use the higher-order component (often referred to as an "HOC"), withRouter
.
First, you'll need to import withRouter
like so:
import {withRouter} from 'react-router-dom';
Next, you'll want to use withRouter
. You can do this by change your component's export. It's likely you want to change from export default ComponentName
to export default withRouter(ComponentName)
.
Then you can get the route (and other information) from props. Specifically, location
, match
, and history
. The code to spit out the pathname would be:
console.log(this.props.location.pathname);
A good writeup with additional information is available here: https://reacttraining.com/react-router/core/guides/philosophy
Adding ->getContents()
doesn't return jSON response, instead it returns as text.
You can simply use json_decode
Add the below code
input[type="submit"]:hover {
border: 1px solid #999;
color: #000;
}
If you need only for these button then you can add id name
#paginate input[type="submit"]:hover {
border: 1px solid #999;
color: #000;
}
SQL
SQL is used to communicate with a database, it is the standard language for relational database management systems.
In detail Structured Query Language is a special-purpose programming language designed for managing data held in a relational database management system (RDBMS), or for stream processing in a relational data stream management system (RDSMS).
Originally based upon relational algebra and tuple relational calculus, SQL consists of a data definition language and a data manipulation language. The scope of SQL includes data insert, query, update and delete, schema creation and modification, and data access control. Although SQL is often described as, and to a great extent is, a declarative language (4GL), it also includes procedural elements.
PL/SQL
PL/SQL is a combination of SQL along with the procedural features of programming languages. It was developed by Oracle Corporation
Specialities of PL/SQL
T-SQL
Short for Transaction-SQL, an extended form of SQL that adds declared variables, transaction control, error and exceptionhandling and row processing to SQL
The Structured Query Language or SQL is a programming language that focuses on managing relational databases. SQL has its own limitations which spurred the software giant Microsoft to build on top of SQL with their own extensions to enhance the functionality of SQL. Microsoft added code to SQL and called it Transact-SQL or T-SQL. Keep in mind that T-SQL is proprietary and is under the control of Microsoft while SQL, although developed by IBM, is already an open format.
T-SQL adds a number of features that are not available in SQL.
This includes procedural programming elements and a local variable to provide more flexible control of how the application flows. A number of functions were also added to T-SQL to make it more powerful; functions for mathematical operations, string operations, date and time processing, and the like. These additions make T-SQL comply with the Turing completeness test, a test that determines the universality of a computing language. SQL is not Turing complete and is very limited in the scope of what it can do.
Another significant difference between T-SQL and SQL is the changes done to the DELETE and UPDATE commands that are already available in SQL. With T-SQL, the DELETE and UPDATE commands both allow the inclusion of a FROM clause which allows the use of JOINs. This simplifies the filtering of records to easily pick out the entries that match a certain criteria unlike with SQL where it can be a bit more complicated.
Choosing between T-SQL and SQL is all up to the user. Still, using T-SQL is still better when you are dealing with Microsoft SQL Server installations. This is because T-SQL is also from Microsoft, and using the two together maximizes compatibility. SQL is preferred by people who have multiple backends.
References , Wikipedea , Tutorial Points :www.differencebetween.com
java.sql.Timestamp.from (
LocalDate.of ( 2007 , 9 , 23 )
.atStartOfDay( ZoneId.of ( "America/Montreal" ) )
.toInstant()
)
Let’s update this page by showing code using the java.time framework built into Java 8 and later.
These new classes are inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project. They supplant the notoriously troublesome old date-time classes bundled with early versions of Java.
In java.time, an Instant
is a moment on the timeline in UTC. A ZonedDateTime
is an Instant adjusted into a time zone (ZoneId
).
Time zone is crucial here. A date of September 23, 2007
cannot be translated to a moment on the timeline without applying a time zone. Consider that a new day dawns earlier in Paris than in Montréal where it is still “yesterday”.
Also, a java.sql.Timestamp represents both a date and time-of-day. So we must inject a time-of-day to go along with the date. We assume you want the first moment of the day as the time-of-day. Note that this is not always the time 00:00:00.0
because of Daylight Saving Time and possibly other anomalies.
Note that unlike the old java.util.Date class, and unlike Joda-Time, the java.time types have a resolution of nanoseconds rather than milliseconds. This matches the resolution of java.sql.Timestamp.
Note that the java.sql.Timestamp has a nasty habit of implicitly applying your JVM’s current default time zone to its date-time value when generating a string representation via its toString
method. Here you see my America/Los_Angeles
time zone applied. In contrast, the java.time classes are more sane, using standard ISO 8601 formats.
LocalDate d = LocalDate.of ( 2007 , 9 , 23 ) ;
ZoneId z = ZoneId.of ( "America/Montreal" ) ;
ZonedDateTime zdt = d.atStartOfDay( z ) ;
Instant instant = zdt.toInstant() ;
java.sql.Timestamp ts = java.sql.Timestamp.from ( instant ) ;
Dump to console.
System.out.println ( "d: " + d + " = zdt: " + zdt + " = instant: " + instant + " = ts: " + ts );
When run.
d: 2007-09-23 = zdt: 2007-09-23T00:00-04:00[America/Montreal] = instant: 2007-09-23T04:00:00Z = ts: 2007-09-22 21:00:00.0
By the way, as of JDBC 4.2, you can use the java.time types directly. No need for java.sql.Timestamp
.
PreparedStatement.setObject
ResultSet.getObject
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
The docs show you are now able to add:
"env": {
"jest/globals": true
}
To your .eslintrc
which will add all the jest related things to your environment, eliminating the linter errors/warnings.
Use default method name() as given bellows
public enum Category {
ONE("one"),
TWO ("two"),
THREE("three");
private final String name;
Category(String s) {
name = s;
}
}
public class Main {
public static void main(String[] args) throws Exception {
System.out.println(Category.ONE.name());
}
}
Other solutions for Git Bash provided by others didn't work for me. Apparently there is currently a bug/limitation in Git for Windows. See this and this.
I finally managed to get it working after finding this GitHub thread (which provides some additional solutions if you're interested, which might work for you, but didn't for me).
I ended up using the following syntax:
MSYS_NO_PATHCONV=1 docker run --rm -it -v $(pwd):/usr/src/project gcc:4.9
Note the MSYS_NO_PATHCONV=1
in front of the docker
command and $(pwd)
- round brackets, lower-case pwd, no quotes, no backslashes.
Also, I'm using Linux containers on Windows if that matters..
I tested this in the new Windows Terminal, ConEmu and GitBash, and all of them worked for me.
Adding more options to the answer.
You could use npm i sweetalert2
Don't forget to add the style to your angular.json
"styles": [
...
"node_modules/sweetalert2/src/sweetalert2.scss"
]
Then just import,
// ES6 Modules or TypeScript
import Swal from 'sweetalert2'
// CommonJS
const Swal = require('sweetalert2')
Boom, you are ready to go.
Swal.fire({
title: 'Are you sure?',
text: 'You will not be able to recover this imaginary file!',
icon: 'warning',
showCancelButton: true,
confirmButtonText: 'Yes, delete it!',
cancelButtonText: 'No, keep it'
}).then((result) => {
if (result.value) {
Swal.fire(
'Deleted!',
'Your imaginary file has been deleted.',
'success'
)
// For more information about handling dismissals please visit
// https://sweetalert2.github.io/#handling-dismissals
} else if (result.dismiss === Swal.DismissReason.cancel) {
Swal.fire(
'Cancelled',
'Your imaginary file is safe :)',
'error'
)
}
})
More on this:- https://www.npmjs.com/package/sweetalert2
I do hope this helps someone.
Thanks.
On windows if you just did a clean install and you get this you need blow away your npm cache in \AppData\Roaming
Try to upgrade and install new packages
sudo apt-get update && sudo apt-get upgrade -y
The main problem is that operator [] is used to insert and read a value into and from the map, so it cannot be const. If the key does not exist, it will create a new entry with a default value in it, incrementing the size of the map, that will contain a new key with an empty string ,in this particular case, as a value if the key does not exist yet. You should avoid operator[] when reading from a map and use, as was mention before, "map.at(key)" to ensure bound checking. This is one of the most common mistakes people often do with maps. You should use "insert" and "at" unless your code is aware of this fact. Check this talk about common bugs Curiously Recurring C++ Bugs at Facebook
if you're doing a lot of this kind of thing you should consider using numpy
.
In [56]: import random, numpy
In [57]: lst = numpy.array([random.uniform(0, 5) for _ in range(1000)]) # example list
In [58]: a, b = 1, 3
In [59]: numpy.flatnonzero((lst > a) & (lst < b))[:10]
Out[59]: array([ 0, 12, 13, 15, 18, 19, 23, 24, 26, 29])
In response to Seanny123's question, I used this timing code:
import numpy, timeit, random
a, b = 1, 3
lst = numpy.array([random.uniform(0, 5) for _ in range(1000)])
def numpy_way():
numpy.flatnonzero((lst > 1) & (lst < 3))[:10]
def list_comprehension():
[e for e in lst if 1 < e < 3][:10]
print timeit.timeit(numpy_way)
print timeit.timeit(list_comprehension)
The numpy version is over 60 times faster.
I managed to install php54w according to Simon's suggestion, but then my sites stopped working perhaps because of an incompatibility with php-mysql or some other module. Even frantically restoring the old situation was not amusing: for anyone in my own situation the sequence is:
sudo yum remove php54w
sudo yum remove php54w-common
sudo yum install php-common
sudo yum install php-mysql
sudo yum install php
It would be nice if someone submitted the full procedure to update all the php packet. That was my production server and my heart is still rapidly beating.