I run into a similar issue the other day. Say, I want to pass data from client side to server and write the data into a log file. Here is my solution:
My simple client side code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<title>Test Page</title>
<script>
function passVal(){
var data = {
fn: "filename",
str: "this_is_a_dummy_test_string"
};
$.post("test.php", data);
}
passVal();
</script>
</head>
<body>
</body>
</html>
And php code on server side:
<?php
$fn = $_POST['fn'];
$str = $_POST['str'];
$file = fopen("/opt/lampp/htdocs/passVal/".$fn.".record","w");
echo fwrite($file,$str);
fclose($file);
?>
Hope this works for you and future readers!
FormData
to submit an AJAX request<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge, chrome=1"/>
<script>
"use strict";
function submitForm(oFormElement)
{
var xhr = new XMLHttpRequest();
xhr.onload = function(){ alert (xhr.responseText); } // success case
xhr.onerror = function(){ alert (xhr.responseText); } // failure case
xhr.open (oFormElement.method, oFormElement.action, true);
xhr.send (new FormData (oFormElement));
return false;
}
</script>
</head>
<body>
<form method="post" action="somewhere" onsubmit="return submitForm(this);">
<input type="hidden" value="person" name="user" />
<input type="hidden" value="password" name="pwd" />
<input type="hidden" value="place" name="organization" />
<input type="hidden" value="key" name="requiredkey" />
<input type="submit" value="post request"/>
</form>
</body>
</html>
This does not fully answer the OP question because it requires the user to click in order to submit the request. But this may be useful to people searching for this kind of simple solution.
This example is very simple and does not support the GET
method. If you are interesting by more sophisticated examples, please have a look at the excellent MDN documentation. See also similar answer about XMLHttpRequest to Post HTML Form.
Limitation of this solution: As pointed out by Justin Blank and Thomas Munk (see their comments), FormData
is not supported by IE9 and lower, and default browser on Android 2.3.
You can rename/remove master on remote, but this will be an issue if lots of people have based their work on the remote master branch and have pulled that branch in their local repo.
That might not be the case here since everyone seems to be working on branch 'seotweaks
'.
In that case you can:
git remote --show may not work.
(Make a git remote show
to check how your remote is declared within your local repo. I will assume 'origin
')
(Regarding GitHub, house9 comments: "I had to do one additional step, click the 'Admin
' button on GitHub and set the 'Default Branch
' to something other than 'master
', then put it back afterwards")
git branch -m master master-old # rename master on local
git push origin :master # delete master on remote
git push origin master-old # create master-old on remote
git checkout -b master seotweaks # create a new local master on top of seotweaks
git push origin master # create master on remote
But again:
reset --hard
their local master to the remote/master branch they will fetch, and forget about their current master.If you have multiple versions installed on your machine, add the following in bash profile:
export JAVA_HOME_7=$(/usr/libexec/java_home -v1.7)
export JAVA_HOME_8=$(/usr/libexec/java_home -v1.8)
export JAVA_HOME_9=$(/usr/libexec/java_home -v9)
And add the following aliases:
alias java7='export JAVA_HOME=$JAVA_HOME_7'
alias java8='export JAVA_HOME=$JAVA_HOME_8'
alias java9='export JAVA_HOME=$JAVA_HOME_9'
And can switch to required version by using the alias:
In terminal:
~ >> java7
export JAVA_HOME=$JAVA_7_HOME
I version control the create script, and I use the svn version tag within it. Then, whenever I get a version that is going to be used, I create a script in a dbpatches/ directory named as the version to roll up to. The job of that script is to modify a current database without destroying the data. dbpatches/, for example, might have files named 201, 220, and 240. If the database is currently at level 201, apply patch 220, then patch 240.
DROP TABLE IF EXISTS `meta`;
CREATE TABLE `meta` (
`property` varchar(255),
`value` varchar(255),
PRIMARY KEY (`property`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `meta` VALUES ('version', '$Rev: 240 $');
Don't forget to test your code before considering a patch good. Caveat emptor!
Short answers:
Q1: Yes.
Q2: Doesn't matter which you use.
Long answer:
A select ... for update
will (as it implies) select certain rows but also lock them as if they have already been updated by the current transaction (or as if the identity update had been performed). This allows you to update them again in the current transaction and then commit, without another transaction being able to modify these rows in any way.
Another way of looking at it, it is as if the following two statements are executed atomically:
select * from my_table where my_condition;
update my_table set my_column = my_column where my_condition;
Since the rows affected by my_condition
are locked, no other transaction can modify them in any way, and hence, transaction isolation level makes no difference here.
Note also that transaction isolation level is independent of locking: setting a different isolation level doesn't allow you to get around locking and update rows in a different transaction that are locked by your transaction.
What transaction isolation levels do guarantee (at different levels) is the consistency of data while transactions are in progress.
It is a pointer to a pointer, so yes, in a way it's a 2D character array. In the same way that a char*
could indicate an array of char
s, a char**
could indicate that it points to and array of char*
s.
Some of more advanced Oracle database features such as session trace do not work properly in Oracle 11g XE 32-bit if installed on Windows 64-bit system. I needed session trace on Windows 7 64-bit.
Apart from that it works well for me in multiple production MS Windows 64-bit systems: Windows Server 2008 R2 and Windows Server 2003 R2.
If it has to be "nested", this would be one way, to get your job done:
SELECT o.name AS country, o.headofstate
FROM country o
WHERE o.headofstate like 'A%'
AND (
SELECT i.population
FROM city i
WHERE i.id = o.capital
) > 100000
A JOIN
would be more efficient than a correlated subquery, though. Can it be, that who ever gave you that task is not up to speed himself?
Create an Extension Method most likely you will want to use this more than once and this prevents duplicate code.
Implementation:
public static void AddRange<T, S>(this Dictionary<T, S> source, Dictionary<T, S> collection)
{
if (collection == null)
{
throw new ArgumentNullException("Collection is null");
}
foreach (var item in collection)
{
if(!source.ContainsKey(item.Key)){
source.Add(item.Key, item.Value);
}
else
{
// handle duplicate key issue here
}
}
}
Usage:
Dictionary<string,string> animals = new Dictionary<string,string>();
Dictionary<string,string> newanimals = new Dictionary<string,string>();
animals.AddRange(newanimals);
From answer that was removed due to being written in Spanish:
All of the above fixes may not work in android studio. If you are using ANDROID STUDIO please use the following fix.
Use
xmlns: compat = "http://schemas.android.com/tools"
on the menu label instead of
xmlns: compat = "http://schemas.android.com/apk/res-auto"
Focus is for selecting UI components when you are using something besides touch (ie, a d-pad, a keyboard, etc.). Any view can receive focus, though some are not focusable by default. (You can make a view focusable with setFocusable(true)
and force it to be focused with requestFocus()
.)
However, it is important to note that when you are in touch mode, focus is disabled. So if you are using your fingers, changing the focus programmatically doesn't do anything. The exception to this is for views that receive input from an input editor. An EditText
is such an example. For this special situation setFocusableInTouchMode(true)
is used to let the soft keyboard know where to send input. An EditText
has this setting by default. The soft keyboard will automatically pop up.
If you don't want the soft keyboard popping up automatically then you can temporarily suppress it as @abeljus noted:
InputMethodManager inputManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
When a user clicks on the EditText
, it should still show the keyboard, though.
If you know what class the field is on you can access it using reflection. This example (it's in Groovy but the method calls are identical) gets a Field object for the class Foo and gets its value for the object b
. It shows that you don't have to care about the exact concrete class of the object, what matters is that you know the class the field is on and that that class is either the concrete class or a superclass of the object.
groovy:000> class Foo { def stuff = "asdf"}
===> true
groovy:000> class Bar extends Foo {}
===> true
groovy:000> b = new Bar()
===> Bar@1f2be27
groovy:000> f = Foo.class.getDeclaredField('stuff')
===> private java.lang.Object Foo.stuff
groovy:000> f.getClass()
===> class java.lang.reflect.Field
groovy:000> f.setAccessible(true)
===> null
groovy:000> f.get(b)
===> asdf
As an alternative to the other answers, django-devserver outputs SQL to the console.
This is correct formula to find integers from i
to j
where i <= R <= j
FLOOR(min+RAND()*(max-min))
According to the man page the -P flag is:
-P prefix --directory-prefix=prefix Set directory prefix to prefix. The directory prefix is the directory where all other files and subdirectories will be saved to, i.e. the top of the retrieval tree. The default is . (the current directory).
This mean that it only specifies the destination but where to save the directory tree. It does not flatten the tree into just one directory. As mentioned before the -nd flag actually does that.
@Jon in the future it would be beneficial to describe what the flag does so we understand how something works.
str_replace('"', "", $string);
str_replace("'", "", $string);
I assume you mean quotation marks?
Otherwise, go for some regex, this will work for html quotes for example:
preg_replace("/<!--.*?-->/", "", $string);
C-style quotes:
preg_replace("/\/\/.*?\n/", "\n", $string);
CSS-style quotes:
preg_replace("/\/*.*?\*\//", "", $string);
bash-style quotes:
preg-replace("/#.*?\n/", "\n", $string);
Etc etc...
Try /*string with {}*/ string.trim().equalsIgnoreCase("{}"))
, maybe there is some extra spaces or something
In general, an alternative to case when ...
is coalesce(nullif(x,bad_value),y)
(that cannot be used in OP's case). For example,
select coalesce(nullif(y,''),x), coalesce(nullif(x,''),y), *
from ( (select 'abc' as x, '' as y)
union all (select 'def' as x, 'ghi' as y)
union all (select '' as x, 'jkl' as y)
union all (select null as x, 'mno' as y)
union all (select 'pqr' as x, null as y)
) q
gives:
coalesce | coalesce | x | y
----------+----------+-----+-----
abc | abc | abc |
ghi | def | def | ghi
jkl | jkl | | jkl
mno | mno | | mno
pqr | pqr | pqr |
(5 rows)
Replace '+' with '000'. For example, 'U+1F600' will become 'U0001F600' and prepend the Unicode code with "\" and print. Example:
>>> print("Learning : ", "\U0001F40D")
Learning :
>>>
Check this maybe it will help python unicode emoji
Using relative instead of absolute file path solved the problem for me.
I had the same issue and setting allow_url_fopen=on
did not help. This means for instance :
use
$file="folder/file.ext";
instead of
$file="https://website.com/folder/file.ext";
in
$f=fopen($file,"r+");
In my opinion, to answer this question, you need to think in terms of project life cycle and version control. In other words, does the parent pom have its own life cycle i.e. can it be released separately of the other modules or not?
If the answer is yes (and this is the case of most projects that have been mentioned in the question or in comments), then the parent pom needs his own module from a VCS and from a Maven point of view and you'll end up with something like this at the VCS level:
root
|-- parent-pom
| |-- branches
| |-- tags
| `-- trunk
| `-- pom.xml
`-- projectA
|-- branches
|-- tags
`-- trunk
|-- module1
| `-- pom.xml
|-- moduleN
| `-- pom.xml
`-- pom.xml
This makes the checkout a bit painful and a common way to deal with that is to use svn:externals
. For example, add a trunks
directory:
root
|-- parent-pom
| |-- branches
| |-- tags
| `-- trunk
| `-- pom.xml
|-- projectA
| |-- branches
| |-- tags
| `-- trunk
| |-- module1
| | `-- pom.xml
| |-- moduleN
| | `-- pom.xml
| `-- pom.xml
`-- trunks
With the following externals definition:
parent-pom http://host/svn/parent-pom/trunk
projectA http://host/svn/projectA/trunk
A checkout of trunks
would then result in the following local structure (pattern #2):
root/
parent-pom/
pom.xml
projectA/
Optionally, you can even add a pom.xml
in the trunks
directory:
root
|-- parent-pom
| |-- branches
| |-- tags
| `-- trunk
| `-- pom.xml
|-- projectA
| |-- branches
| |-- tags
| `-- trunk
| |-- module1
| | `-- pom.xml
| |-- moduleN
| | `-- pom.xml
| `-- pom.xml
`-- trunks
`-- pom.xml
This pom.xml
is a kind of "fake" pom: it is never released, it doesn't contain a real version since this file is never released, it only contains a list of modules. With this file, a checkout would result in this structure (pattern #3):
root/
parent-pom/
pom.xml
projectA/
pom.xml
This "hack" allows to launch of a reactor build from the root after a checkout and make things even more handy. Actually, this is how I like to setup maven projects and a VCS repository for large builds: it just works, it scales well, it gives all the flexibility you may need.
If the answer is no (back to the initial question), then I think you can live with pattern #1 (do the simplest thing that could possibly work).
Now, about the bonus questions:
- Where is the best place to define the various shared configuration as in source control, deployment directories, common plugins etc. (I'm assuming the parent but I've often been bitten by this and they've ended up in each project rather than a common one).
Honestly, I don't know how to not give a general answer here (like "use the level at which you think it makes sense to mutualize things"). And anyway, child poms can always override inherited settings.
- How do the maven-release plugin, hudson and nexus deal with how you set up your multi-projects (possibly a giant question, it's more if anyone has been caught out when by how a multi-project build has been set up)?
The setup I use works well, nothing particular to mention.
Actually, I wonder how the maven-release-plugin deals with pattern #1 (especially with the <parent>
section since you can't have SNAPSHOT dependencies at release time). This sounds like a chicken or egg problem but I just can't remember if it works and was too lazy to test it.
Rails / ruby frameworks are able to do some templating ... it's frequently used to load env variables ...
# fooz.yml
foo:
bar: <%= $ENV[:some_var] %>
No idea if this works for javascript frameworks as I think that YML format is superset of json and it depends on what reads the yml file for you.
If you can use the template like that or the << >>
or the {{ }}
styles depending on your reader, after that you just ...
In another yml file ...
# boo.yml
development:
fooz: foo
Which allows you to basically insert a variable as your reference that original file each time which is dynamically set. When reading I was also seeing you can create or open YML files as objects on the fly for several languages which allows you to create a file & chain write a series of YML files or just have them all statically pointing to the dynamically created one.
You can use the terms aggregation.
{
"size": 0,
"aggs" : {
"langs" : {
"terms" : { "field" : "language", "size" : 500 }
}
}}
The size
parameter within the aggregation specifies the maximum number of terms to include in the aggregation result. If you need all results, set this to a value that is larger than the number of unique terms in your data.
A search will return something like:
{
"took" : 16,
"timed_out" : false,
"_shards" : {
"total" : 2,
"successful" : 2,
"failed" : 0
},
"hits" : {
"total" : 1000000,
"max_score" : 0.0,
"hits" : [ ]
},
"aggregations" : {
"langs" : {
"buckets" : [ {
"key" : "10",
"doc_count" : 244812
}, {
"key" : "11",
"doc_count" : 136794
}, {
"key" : "12",
"doc_count" : 32312
} ]
}
}
}
Since C# version 6 you can simply call:
string currentMethodName = nameof(MyMethod);
In C# version 5 and .NET 4.5 you can use the [CallerMemberName] attribute to have the compiler auto-generate the name of the calling method in a string argument. Other useful attributes are [CallerFilePath] to have the compiler generate the source code file path and [CallerLineNumber] to get the line number in the source code file for the statement that made the call.
Before that there were still some more convoluted ways of getting the method name, but much simpler:
void MyMethod() {
string currentMethodName = "MyMethod";
//etc...
}
Albeit that a refactoring probably won't fix it automatically.
If you completely don't care about the (considerable) cost of using Reflection
then this helper method should be useful:
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Reflection;
//...
[MethodImpl(MethodImplOptions.NoInlining)]
public static string GetMyMethodName() {
var st = new StackTrace(new StackFrame(1));
return st.GetFrame(0).GetMethod().Name;
}
Inline styling does not support pseudos or at-rules (e.g., @media). Recommendations range from reimplement CSS features in JavaScript for CSS states like :hover
via onMouseEnter
and onMouseLeave
to using more elements to reproduce pseudo-elements like :after
and :before
to just use an external stylesheet.
Personally dislike all of those solutions. Reimplementing CSS features via JavaScript does not scale well -- neither does adding superfluous markup.
Imagine a large team wherein each developer is recreating CSS features like :hover
. Each developer will do it differently, as teams grow in size, if it can be done, it will be done. Fact is with JavaScript there are about n ways to reimplement CSS features, and over time you can bet on every one of those ways being implemented with the end result being spaghetti code.
So what to do? Use CSS. Granted you asked about inline styling going to assume you're likely in the CSS-in-JS camp (me too!). Have found colocating HTML and CSS to be as valuable as colocating JS and HTML, lots of folks just don't realise it yet (JS-HTML colocation had lots of resistance too at first).
Made a solution in this space called Style It that simply lets your write plaintext CSS in your React components. No need to waste cycles reinventing CSS in JS. Right tool for the right job, here is an example using :after
:
npm install style-it --save
Functional Syntax (JSFIDDLE)
import React from 'react';
import Style from 'style-it';
class Intro extends React.Component {
render() {
return Style.it(`
#heart {
position: relative;
width: 100px;
height: 90px;
}
#heart:before,
#heart:after {
position: absolute;
content: "";
left: 50px;
top: 0;
width: 50px;
height: 80px;
background: red;
-moz-border-radius: 50px 50px 0 0;
border-radius: 50px 50px 0 0;
-webkit-transform: rotate(-45deg);
-moz-transform: rotate(-45deg);
-ms-transform: rotate(-45deg);
-o-transform: rotate(-45deg);
transform: rotate(-45deg);
-webkit-transform-origin: 0 100%;
-moz-transform-origin: 0 100%;
-ms-transform-origin: 0 100%;
-o-transform-origin: 0 100%;
transform-origin: 0 100%;
}
#heart:after {
left: 0;
-webkit-transform: rotate(45deg);
-moz-transform: rotate(45deg);
-ms-transform: rotate(45deg);
-o-transform: rotate(45deg);
transform: rotate(45deg);
-webkit-transform-origin: 100% 100%;
-moz-transform-origin: 100% 100%;
-ms-transform-origin: 100% 100%;
-o-transform-origin: 100% 100%;
transform-origin :100% 100%;
}
`,
<div id="heart" />
);
}
}
export default Intro;
JSX Syntax (JSFIDDLE)
import React from 'react';
import Style from 'style-it';
class Intro extends React.Component {
render() {
return (
<Style>
{`
#heart {
position: relative;
width: 100px;
height: 90px;
}
#heart:before,
#heart:after {
position: absolute;
content: "";
left: 50px;
top: 0;
width: 50px;
height: 80px;
background: red;
-moz-border-radius: 50px 50px 0 0;
border-radius: 50px 50px 0 0;
-webkit-transform: rotate(-45deg);
-moz-transform: rotate(-45deg);
-ms-transform: rotate(-45deg);
-o-transform: rotate(-45deg);
transform: rotate(-45deg);
-webkit-transform-origin: 0 100%;
-moz-transform-origin: 0 100%;
-ms-transform-origin: 0 100%;
-o-transform-origin: 0 100%;
transform-origin: 0 100%;
}
#heart:after {
left: 0;
-webkit-transform: rotate(45deg);
-moz-transform: rotate(45deg);
-ms-transform: rotate(45deg);
-o-transform: rotate(45deg);
transform: rotate(45deg);
-webkit-transform-origin: 100% 100%;
-moz-transform-origin: 100% 100%;
-ms-transform-origin: 100% 100%;
-o-transform-origin: 100% 100%;
transform-origin :100% 100%;
}
`}
<div id="heart" />
</Style>
}
}
export default Intro;
Heart example pulled from CSS-Tricks
As a contemporary alternative, there is a standard now for client side cryptography. This has the advantage of being optimised by the browser itself.
Taken from the example in the documentation:
async function sha256(message) {
// encode as UTF-8
const msgBuffer = new TextEncoder('utf-8').encode(message);
// hash the message
const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
// convert ArrayBuffer to Array
const hashArray = Array.from(new Uint8Array(hashBuffer));
// convert bytes to hex string
const hashHex = hashArray.map(b => ('00' + b.toString(16)).slice(-2)).join('');
return hashHex;
}
sha256('abc').then(hash => console.log(hash));
(async function() {
const hash = await sha256('abc');
}());
MD5 is likely unsupported, however the likes of SHA-256, SHA-384, and SHA-512 are.
And those will likely be able to be calculated server side also.
Here's some documentation on usage: https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest
And cross browser compatibility: https://caniuse.com/#feat=cryptography
This will work i have tested myself.
It gives difference between sysdate and date fetched from column admitdate
TABLE SCHEMA:
CREATE TABLE "ADMIN"."DUESTESTING"
(
"TOTAL" NUMBER(*,0),
"DUES" NUMBER(*,0),
"ADMITDATE" TIMESTAMP (6),
"DISCHARGEDATE" TIMESTAMP (6)
)
EXAMPLE:
select TO_NUMBER(trunc(sysdate) - to_date(to_char(admitdate, 'yyyy-mm-dd'),'yyyy-mm-dd')) from admin.duestesting where total=300
strRequest = "<soap:Envelope xmlns:soap=""http://www.w3.org/2003/05/soap-envelope"" " &_
"xmlns:tem=""http://tempuri.org/"">" &_
"<soap:Header/>" &_
"<soap:Body>" &_
"<tem:Authorization>" &_
"<tem:strCC>"&1234123412341234&"</tem:strCC>" &_
"<tem:strEXPMNTH>"&11&"</tem:strEXPMNTH>" &_
"<tem:CVV2>"&123&"</tem:CVV2>" &_
"<tem:strYR>"&23&"</tem:strYR>" &_
"<tem:dblAmount>"&1235&"</tem:dblAmount>" &_
"</tem:Authorization>" &_
"</soap:Body>" &_
"</soap:Envelope>"
EndPointLink = "http://www.trainingrite.net/trainingrite_epaysystem" &_
"/trainingrite_epaysystem/tr_epaysys.asmx"
dim http
set http=createObject("Microsoft.XMLHTTP")
http.open "POST",EndPointLink,false
http.setRequestHeader "Content-Type","text/xml"
msgbox "REQUEST : " & strRequest
http.send strRequest
If http.Status = 200 Then
'msgbox "RESPONSE : " & http.responseXML.xml
msgbox "RESPONSE : " & http.responseText
responseText=http.responseText
else
msgbox "ERRCODE : " & http.status
End If
Call ParseTag(responseText,"AuthorizationResult")
Call CreateXMLEvidence(responseText,strRequest)
'Function to fetch the required message from a TAG
Function ParseTag(ResponseXML,SearchTag)
ResponseMessage=split(split(split(ResponseXML,SearchTag)(1),"</")(0),">")(1)
Msgbox ResponseMessage
End Function
'Function to create XML test evidence files
Function CreateXMLEvidence(ResponseXML,strRequest)
Set fso=createobject("Scripting.FileSystemObject")
Set qfile=fso.CreateTextFile("C:\Users\RajkumarJoshua\Desktop\DCIM\SampleResponse.xml",2)
Set qfile1=fso.CreateTextFile("C:\Users\RajkumarJoshua\Desktop\DCIM\SampleReuest.xml",2)
qfile.write ResponseXML
qfile.close
qfile1.write strRequest
qfile1.close
End Function
No, if you do:
array = {}
IN your example you are using array
as a dictionary, not an array. If you need an array, in Python you use lists:
array = []
Then, to add items you do:
array.append('a')
For div refreshing without creating div inside yours with same id, you should use this inside your function
$("#yourDiv").load(" #yourDiv > *");
I had this error when I had specified fromGroupName instead of formArrayName.
Make sure you correctly specify if it is a form array or form group.
<div formGroupName="formInfo"/>
<div formArrayName="formInfo"/>
This is bit tricky. I did in this way and it worked.
1.At first call to hide the soft Input from the window. This will hide the soft input if the soft keyboard is visible or do nothing if it is not.
2.Show your dialog
3.Then simply call to toggle soft input.
code:
InputMethodManager inputManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
//hiding soft input
inputManager.hideSoftInputFromWindow(findViewById(android.R.id.content).getWind??owToken(), 0);
//show dialog
yourDialog.show();
//toggle soft input
inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,InputMethodManager.SHOW_IMPLICIT);
I like, with git log
, to do:
git log --graph --oneline --branches
(also with --all, for viewing remote branches as well)
Works with recent Git releases: introduced since 1.6.3 (Thu, 7 May 2009)
"
--pretty=<style>
" option to the log family of commands can now be spelled as "--format=<style>
".
In addition,--format=%formatstring
is a short-hand for--pretty=tformat:%formatstring
."
--oneline
" is a synonym for "--pretty=oneline --abbrev-commit
".
PS D:\git\tests\finalRepo> git log --graph --oneline --branches --all
* 4919b68 a second bug10 fix
* 3469e13 a first bug10 fix
* dbcc7aa a first legacy evolution
| * 55aac85 another main evol
| | * 47e6ee1 a second bug10 fix
| | * 8183707 a first bug10 fix
| |/
| * e727105 a second evol for 2.0
| * 473d44e a main evol
|/
* b68c1f5 first evol, for making 1.0
You can also limit the span of the log display (number of commits):
PS D:\git\tests\finalRepo> git log --graph --oneline --branches --all -5
* 4919b68 a second bug10 fix
* 3469e13 a first bug10 fix
* dbcc7aa a first legacy evolution
| * 55aac85 another main evol
| | * 47e6ee1 a second bug10 fix
(show only the last 5 commits)
What I do not like about the current selected solution is:
git log --graph
It displayed way too much info (when I want only to look at a quick summary):
PS D:\git\tests\finalRepo> git log --graph
* commit 4919b681db93df82ead7ba6190eca6a49a9d82e7
| Author: VonC <[email protected]>
| Date: Sat Nov 14 13:42:20 2009 +0100
|
| a second bug10 fix
|
* commit 3469e13f8d0fadeac5fcb6f388aca69497fd08a9
| Author: VonC <[email protected]>
| Date: Sat Nov 14 13:41:50 2009 +0100
|
| a first bug10 fix
|
gitk
is great, but forces me to leave the shell session for another window, whereas displaying the last n commits quickly is often enough.
model.update({"_id": 1, "items.id": "2"},
{$set: {"items.$.name": "yourValue","items.$.value": "yourvalue"}})
$ls -l `which sh`
/bin/sh -> dash
$sudo dpkg-reconfigure dash #Select "no" when you're asked
[...]
$ls -l `which sh`
/bin/sh -> bash
Then it will be OK
You could do it using an Exchanger object shared between the two threads:
private Exchanger<String> myDataExchanger = new Exchanger<String>();
// Wait for thread's output
String data;
try {
data = myDataExchanger.exchange("");
} catch (InterruptedException e1) {
// Handle Exceptions
}
And in the second thread:
try {
myDataExchanger.exchange(data)
} catch (InterruptedException e) {
}
As others have said, do not take this light-hearted and just copy-paste code. Do some reading first.
Here is the functions;
canvas.width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
canvas.height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
Check this out
Here is the resize method for the resize event;
function resizeCanvas() {
canvas.width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
canvas.height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
WIDTH = canvas.width;
HEIGHT = canvas.height;
clearScreen();
}
Simply;
<style>
html, body {
overflow: hidden;
}
</style>
<html>_x000D_
<head>_x000D_
<title>Full Screen Canvas Example</title>_x000D_
<style>_x000D_
html, body {_x000D_
overflow: hidden;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
<body onresize="resizeCanvas()">_x000D_
<canvas id="mainCanvas">_x000D_
</canvas>_x000D_
<script>_x000D_
(function () {_x000D_
canvas = document.getElementById('mainCanvas');_x000D_
ctx = canvas.getContext("2d");_x000D_
_x000D_
canvas.width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;_x000D_
canvas.height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;_x000D_
WIDTH = canvas.width;_x000D_
HEIGHT = canvas.height;_x000D_
_x000D_
clearScreen();_x000D_
})();_x000D_
_x000D_
function resizeCanvas() {_x000D_
canvas.width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;_x000D_
canvas.height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;_x000D_
_x000D_
WIDTH = canvas.width;_x000D_
HEIGHT = canvas.height;_x000D_
_x000D_
clearScreen();_x000D_
}_x000D_
_x000D_
function clearScreen() {_x000D_
var grd = ctx.createLinearGradient(0,0,0,180);_x000D_
grd.addColorStop(0,"#6666ff");_x000D_
grd.addColorStop(1,"#aaaacc");_x000D_
_x000D_
ctx.fillStyle = grd;_x000D_
ctx.fillRect( 0, 0, WIDTH, HEIGHT );_x000D_
}_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
Excellent answers - here's the D3 version for anyone looking:
<select id="sel">
<option>Cat</option>
<option>Dog</option>
<option>Fish</option>
</select>
<script>
d3.select('#sel').property('value', 'Fish');
</script>
Steps for adding external jars in IntelliJ IDEA:
I am joining the choir recommending that you skip the now long outdated classes Date
, Calendar
, SimpleDateFormat
and friends. In particular I would warn against using the deprecated methods and constructors of the Date
class, like the Date(String)
constructor you used. They were deprecated because they don’t work reliably across time zones, so don’t use them. And yes, most of the constructors and methods of that class are deprecated.
While at the time you asked the question, Joda-Time was (from all I know) a clearly better alternative, time has moved on again. Today Joda-Time is a largely finished project, and its developers recommend you use java.time
, the modern Java date and time API, instead. I will show you how.
ZonedDateTime localTime = ZonedDateTime.now(ZoneId.systemDefault());
// Convert Local Time to UTC
OffsetDateTime gmtTime
= localTime.toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC);
System.out.println("Local:" + localTime.toString()
+ " --> UTC time:" + gmtTime.toString());
// Reverse Convert UTC Time to Local time
localTime = gmtTime.atZoneSameInstant(ZoneId.systemDefault());
System.out.println("Local Time " + localTime.toString());
For starters, note that not only is the code only half as long as yours, it is also clearer to read.
On my computer the code prints:
Local:2017-09-02T07:25:46.211+02:00[Europe/Berlin] --> UTC time:2017-09-02T05:25:46.211Z
Local Time 2017-09-02T07:25:46.211+02:00[Europe/Berlin]
I left out the milliseconds from the epoch. You can always get them from System.currentTimeMillis();
as in your question, and they are independent of time zone, so I didn’t find them intersting here.
I hesitatingly kept your variable name localTime
. I think it’s a good name. The modern API has a class called LocalTime
, so using that name, only not capitalized, for an object that hasn’t got type LocalTime
might confuse some (a LocalTime
doesn’t hold time zone information, which we need to keep here to be able to make the right conversion; it also only holds the time-of-day, not the date).
Your conversion from local time to UTC was incorrect and impossible
The outdated Date
class doesn’t hold any time zone information (you may say that internally it always uses UTC), so there is no such thing as converting a Date
from one time zone to another. When I just ran your code on my computer, the first line it printed, was:
Local:Sat Sep 02 07:25:45 CEST 2017,1504329945967 --> UTC time:Sat Sep 02 05:25:45 CEST 2017-1504322745000
07:25:45 CEST
is correct, of course. The correct UTC time would have been 05:25:45 UTC
, but it says CEST
again, which is incorrect.
Now you will never need the Date
class again, :-) but if you were ever going to, the must-read would be All about java.util.Date on Jon Skeet’s coding blog.
Question: Can I use the modern API with my Java version?
If using at least Java 6, you can.
May be a little late but the following solution happened very useful in my case.
In a way all you need to do is add to your ListView a Footer
and create for it addOnLayoutChangeListener
.
http://developer.android.com/reference/android/widget/ListView.html#addFooterView(android.view.View)
For example:
ListView listView1 = (ListView) v.findViewById(R.id.dialogsList); // Your listView
View loadMoreView = getActivity().getLayoutInflater().inflate(R.layout.list_load_more, null); // Getting your layout of FooterView, which will always be at the bottom of your listview. E.g. you may place on it the ProgressBar or leave it empty-layout.
listView1.addFooterView(loadMoreView); // Adding your View to your listview
...
loadMoreView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
Log.d("Hey!", "Your list has reached bottom");
}
});
This event fires once when a footer becomes visible and works like a charm.
On Windows:-
Go to File -> Settings.
And open the 'Build,Execution,Deployment'
. Then open the
Build Tools -> Gradle
Then uncheck -> Offline work on the right.
Click the OK button.
Then Rebuild the Project.
On Mac OS:-
go to Android Studio -> Preferences, and the rest is the same. OR follow steps given in the image
[
SELECT column1 FROM table WHERE ISNUMERIC(column1) = 1
Note, as Damien_The_Unbeliever has pointed out, this will include any valid numeric type.
To filter out columns containing non-digit characters (and empty strings), you could use
SELECT column1 FROM table WHERE column1 not like '%[^0-9]%' and column1 != ''
See Apple’s Info.plist reference for full details (thanks @gnasher729).
You can add exceptions for specific domains in your Info.plist:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>testdomain.com</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSExceptionRequiresForwardSecrecy</key>
<true/>
<key>NSExceptionMinimumTLSVersion</key>
<string>TLSv1.2</string>
<key>NSThirdPartyExceptionAllowsInsecureHTTPLoads</key>
<false/>
<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
<true/>
<key>NSThirdPartyExceptionMinimumTLSVersion</key>
<string>TLSv1.2</string>
<key>NSRequiresCertificateTransparency</key>
<false/>
</dict>
</dict>
</dict>
All the keys for each excepted domain are optional. The speaker did not elaborate on any of the keys, but I think they’re all reasonably obvious.
(Source: WWDC 2015 session 703, “Privacy and Your App”, 30:18)
You can also ignore all app transport security restrictions with a single key, if your app has a good reason to do so:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
If your app does not have a good reason, you may risk rejection:
Setting NSAllowsArbitraryLoads to true will allow it to work, but Apple was very clear in that they intend to reject apps who use this flag without a specific reason. The main reason to use NSAllowsArbitraryLoads I can think of would be user created content (link sharing, custom web browser, etc). And in this case, Apple still expects you to include exceptions that enforce the ATS for the URLs you are in control of.
If you do need access to specific URLs that are not served over TLS 1.2, you need to write specific exceptions for those domains, not use NSAllowsArbitraryLoads set to yes. You can find more info in the NSURLSesssion WWDC session.
Please be careful in sharing the NSAllowsArbitraryLoads solution. It is not the recommended fix from Apple.
— kcharwood (thanks @marco-tolman)
I was having the same problem.
There is a difference between a Bar chart
and a Stacked Bar chart
As there is a difference between a Line chart
and a Stacked Line chart
.
The stacked one, will not ignore the 0 or blank values, but will show a cumulative value according with the other legends.
Simply right click the graph, click Change Chart Type
and pick a non-stacked chart.
Try adding "allowSyntheticDefaultImports": true
to your tsconfig.json
.
This basically tells the TypeScript compiler that it's okay to use an ES6 import statement, i. e.
import * as moment from 'moment/moment';
on a CommonJS module like Moment.js which doesn't declare a default export. The flag only affects type checking, not the generated code.
It is necessary if you use SystemJS as your module loader. The flag will be automatically turned on if you tell your TS compiler that you use SystemJS:
"module": "system"
This will also remove any errors thrown by IDEs if they are configured to make use of the tsconfig.json
.
Hope this helps
/* Hide scrollbar for Chrome, Safari and Opera */
::-webkit-scrollbar {
display: none;
}
/* Hide scrollbar for IE, Edge and Firefox */
html {
-ms-overflow-style: none; /* IE and Edge */
scrollbar-width: none; /* Firefox */
}
I'd suggest you store the result of the lookup in a temp variable, test if the temp variable is nil and then use it. That way you don't look the same object up twice:
id obj = [dict objectForKey:@"blah"];
if (obj) {
// use obj
} else {
// Do something else
}
lets say you have a model called Book and on it a field called 'cover_pic', in that case, you can do the following to compress the image:
from PIL import Image
b = Book.objects.get(title='Into the wild')
image = Image.open(b.cover_pic.path)
image.save(b.image.path,quality=20,optimize=True)
hope it helps to anyone stumbling upon it.
You can completely handle it in the MySQL query:
SELECT SUM(column_name) FROM table_name;
Using PDO (mysql_query
is deprecated)
$stmt = $handler->prepare('SELECT SUM(value) AS value_sum FROM codes');
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$sum = $row['value_sum'];
Or using mysqli:
$result = mysqli_query($conn, 'SELECT SUM(value) AS value_sum FROM codes');
$row = mysqli_fetch_assoc($result);
$sum = $row['value_sum'];
Using just awk you could do (I also shortened some of your piping):
strings -a libAddressDoctor5.so | awk '/EngineVersion/ { if(NR==2) { gsub("\"",""); print $2 } }'
I can't verify it for you because I don't know your exact input, but the following works:
echo "Blah EngineVersion=\"123\"" | awk '/EngineVersion/ { gsub("\"",""); print $2 }'
See also this question on removing single quotes.
You can't.
You can only return object
, or container of objects, e.g. IEnumerable<object>
, IList<object>
, etc.
If you pass only vectors to cbind()
it creates a matrix, not a dataframe. Read ?data.frame
.
Add the following code in the parent div
display: grid;
place-items: center;
I like eTicket Support, is very simple to use and install.
You are calling:
JSON.parse(scatterSeries)
But when you defined scatterSeries
, you said:
var scatterSeries = [];
When you try to parse it as JSON it is converted to a string (""
), which is empty, so you reach the end of the string before having any of the possible content of a JSON text.
scatterSeries
is not JSON. Do not try to parse it as JSON.
data
is not JSON either (getJSON
will parse it as JSON automatically).
ch
is JSON … but shouldn't be. You should just create a plain object in the first place:
var ch = {
"name": "graphe1",
"items": data.results[1]
};
scatterSeries.push(ch);
In short, for what you are doing, you shouldn't have JSON.parse
anywhere in your code. The only place it should be is in the jQuery library itself.
If you want to get the count of records then you have to apply the group by on some field or apply the below query.
db.rawQuery("select count(field) as count_record from tablename where field =" + condition, null);
I tried the suggested solutions by everyone, but I had to improvise code myself to actually make it work. Following is my improvised code:
import signal
import sys
import time
def signal_handler(signal, frame):
print('You pressed Ctrl+C!')
print(signal) # Value is 2 for CTRL + C
print(frame) # Where your execution of program is at moment - the Line Number
sys.exit(0)
#Assign Handler Function
signal.signal(signal.SIGINT, signal_handler)
# Simple Time Loop of 5 Seconds
secondsCount = 5
print('Press Ctrl+C in next '+str(secondsCount))
timeLoopRun = True
while timeLoopRun:
time.sleep(1)
if secondsCount < 1:
timeLoopRun = False
print('Closing in '+ str(secondsCount)+ ' seconds')
secondsCount = secondsCount - 1
Am I missing something? You can just convert offer_date in the comparison:
SELECT *
FROM offers
WHERE to_char(offer_date, 'YYYYMM') = (SELECT to_date(create_date, 'YYYYMM') FROM customers where id = '12345678') AND
offer_rate > 0
To solve this for an expo 'ejected' app, I went to the capabilities tab, enabled push, then disabled it again. This removed the APNS 'entitlements' setting from the .entitlements file.
If you are running two commands at once just to change the directory the command prompt runs in, there is an overload for the Runtime.exec method that lets you specify the current working directory. Like,
Runtime rt = Runtime.getRuntime();
rt.exec("cmd.exe /c start command", null, new File(newDir));
This will open command prompt in the directory at newDir. I think your solution works as well, but this keeps your command string or array a little cleaner.
There is an overload for having the command as a string and having the command as a String array.
You may find it even easier, though, to use the ProcessBuilder, which has a directory
method to set your current working directory.
Hope this helps.
There are two ways to use this variable:
passing it as a command line argument just like Job mentioned:
cmake -DCMAKE_INSTALL_PREFIX=< install_path > ..
assigning value to it in CMakeLists.txt
:
SET(CMAKE_INSTALL_PREFIX < install_path >)
But do remember to place it BEFORE PROJECT(< project_name>)
command, otherwise it will not work!
This code sends array of integer values
Initialize array List
List<Integer> test = new ArrayList<Integer>();
Add values to array List
test.add(1);
test.add(2);
test.add(3);
Intent intent=new Intent(this, targetActivty.class);
Send the array list values to target activity
intent.putIntegerArrayListExtra("test", (ArrayList<Integer>) test);
startActivity(intent);
here you get values on targetActivty
Intent intent=getIntent();
ArrayList<String> test = intent.getStringArrayListExtra("test");
On MacOS, can try:
brew tap let-us-go/zkcli
brew install zkcli
zkcli ls /brokers/ids
zkcli get /brokers/ids/1
If you encounter this apparent index corruption in a running system, you can work around it by deleting all files called segments.gen. It is advisory only, and Lucene can recover correctly without it.
From ElasticSearch Blog
With two capturing groups would have been also possible; I would have also included two dashes, as additional left and right boundaries, before and after the digits, and the modified expression would have looked like:
(.*name=".+_)\d+(_[^"]+".*)
const regex = /(.*name=".+_)\d+(_[^"]+".*)/g;_x000D_
const str = `some_data_before name="some_text_0_some_text" and then some_data after`;_x000D_
const subst = `$1!NEW_ID!$2`;_x000D_
const result = str.replace(regex, subst);_x000D_
console.log(result);
_x000D_
If you wish to explore/simplify/modify the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.
jex.im visualizes regular expressions:
grid.getStore().reload({
callback: function(){
grid.getView().refresh();
}
});
Have you seen the Algorithm for finding similar images question? Check it out to see suggestions.
I would suggest a wavelet transformation of your frames (I've written a C extension for that using Haar transformation); then, comparing the indexes of the largest (proportionally) wavelet factors between the two pictures, you should get a numerical similarity approximation.
I had the same error.
I am using Jboss 7.1 AS. In the configuration file - standalone.xml edit the following tag. (stop your server and edit)
<root-logger>
<level name="ALL"/>
<handlers>
<handler name="CONSOLE"/>
<handler name="FILE"/>
</handlers>
</root-logger>
The ALL has the lowest possible rank and is intended to turn on all logging.
The count()
function in plyr
does what you want:
library(plyr)
count(mydf, "MONTH-YEAR")
That error also shows when the video has played fine and the script will finish but that error always throws because the imshow() will get empty frames after all frames have been consumed.
That is especially the case if you are playing a short (few sec) video file and you don't notice that the video actually played on the background (behind your code editor) and after that the script ends with that error.
This is my solution to scroll to the top on a button click.
$(".btn").click(function () {
if ($(this).text() == "Show options") {
$(".tabs").animate(
{
scrollTop: $(window).scrollTop(0)
},
"slow"
);
}
});
The SOAP WS supports both remote procedure call (i.e. RPC) and message oriented middle-ware (MOM) integration styles. The Restful Web Service supports only RPC integration style.
The SOAP WS is transport protocol neutral. Supports multiple protocols like HTTP(S), Messaging, TCP, UDP SMTP, etc. The REST is transport protocol specific. Supports only HTTP or HTTPS protocols.
The SOAP WS permits only XML data format.You define operations, which tunnels through the POST. The focus is on accessing the named operations and exposing the application logic as a service. The REST permits multiple data formats like XML, JSON data, text, HTML, etc. Any browser can be used because the REST approach uses the standard GET, PUT, POST, and DELETE Web operations. The focus is on accessing the named resources and exposing the data as a service. REST has AJAX support. It can use the XMLHttpRequest object. Good for stateless CRUD (Create, Read, Update, and Delete) operations. GET - represent() POST - acceptRepresention() PUT - storeRepresention() DELETE - removeRepresention()
SOAP based reads cannot be cached. REST based reads can be cached. Performs and scales better. SOAP WS supports both SSL security and WS-security, which adds some enterprise security features like maintaining security right up to the point where it is needed, maintaining identities through intermediaries and not just point to point SSL only, securing different parts of the message with different security algorithms, etc. The REST supports only point-to-point SSL security. The SSL encrypts the whole message, whether all of it is sensitive or not. The SOAP has comprehensive support for both ACID based transaction management for short-lived transactions and compensation based transaction management for long-running transactions. It also supports two-phase commit across distributed resources. The REST supports transactions, but it is neither ACID compliant nor can provide two phase commit across distributed transactional resources as it is limited by its HTTP protocol.
The SOAP has success or retry logic built in and provides end-to-end reliability even through SOAP intermediaries. REST does not have a standard messaging system, and expects clients invoking the service to deal with communication failures by retrying.
source http://java-success.blogspot.in/2012/02/java-web-services-interview-questions.html
In order to get "the current date" (as in today's date), you can use LocalDate.now()
and pass that into the java.sql.Date
method valueOf(LocalDate)
.
import java.sql.Date;
...
Date date = Date.valueOf(LocalDate.now());
Somewhere in your initialisation put this code.
Array.prototype.contains = function contains(obj) {
for (var i = 0; i < this.length; i++) {
if (this[i] === obj) {
return true;
}
}
return false;
};
Then, you can use it this way:
<li ng-class="{approved: selectedForApproval.contains(jobSet)}"></li>
Funny the answer is hidden in among the answers.
str.replace("•", "something")
would work if you use the right semantics.
str.replace(u"\u2022","something")
works wonders ;) , thnx to RParadox for the hint.
java.util.MissingResourceException: Can't find bundle for base name org.jfree.chart.LocalizationBundle, locale en_US
To the point, the exception message tells in detail that you need to have either of the following files in the classpath:
/org/jfree/chart/LocalizationBundle.properties
or
/org/jfree/chart/LocalizationBundle_en.properties
or
/org/jfree/chart/LocalizationBundle_en_US.properties
Also see the official Java tutorial about resourcebundles for more information.
But as this is actually a 3rd party managed properties file, you shouldn't create one yourself. It should be already available in the JFreeChart JAR file. So ensure that you have it available in the classpath during runtime. Also ensure that you're using the right version, the location of the propertiesfile inside the package tree might have changed per JFreeChart version.
When executing a JAR file, you can use the -cp
argument to specify the classpath. E.g.:
java -jar -cp c:/path/to/jfreechart.jar yourfile.jar
Alternatively you can specify the classpath as class-path
entry in the JAR's manifest file. You can use in there relative paths which are relative to the JAR file itself. Do not use the %CLASSPATH%
environment variable, it's ignored by JAR's and everything else which aren't executed with java.exe
without -cp
, -classpath
and -jar
arguments.
First install pyyaml using pip3.
Then import yaml module and load the file into a dictionary called 'my_dict':
import yaml
with open('filename.yaml') as f:
my_dict = yaml.safe_load(f)
That's all you need. Now the entire yaml file is in 'my_dict' dictionary.
AssertionError is an Unchecked Exception which rises explicitly by programmer or by API Developer to indicate that assert statement fails.
assert(x>10);
Output:
AssertionError
If x is not greater than 10 then you will get runtime exception saying AssertionError.
Just specify max-width: 100%
alone, that should do it.
Instructions as of Dec 2018:
Now when you open the shortcut it will open in a window without toolbar.
Java IO using stream oriented APIs is performed using a buffer as temporary storage of data within user space. Data read from disk by DMA is first copied to buffers in kernel space, which is then transfer to buffer in user space. Hence there is overhead. Avoiding it can achieve considerable gain in performance.
We could skip this temporary buffer in user space, if there was a way directly to access the buffer in kernel space. Java NIO provides a way to do so.
ByteBuffer
is among several buffers provided by Java NIO. Its just a container or holding tank to read data from or write data to. Above behavior is achieved by allocating a direct buffer using allocateDirect()
API on Buffer.
Based on the work of Bas Brekelmans above, I have also created two derivations -> "input" dialogs that allow you to receive from the user both a text value and a boolean (TextBox and CheckBox):
public static class PromptForTextAndBoolean
{
public static string ShowDialog(string caption, string text, string boolStr)
{
Form prompt = new Form();
prompt.Width = 280;
prompt.Height = 160;
prompt.Text = caption;
Label textLabel = new Label() { Left = 16, Top = 20, Width = 240, Text = text };
TextBox textBox = new TextBox() { Left = 16, Top = 40, Width = 240, TabIndex = 0, TabStop = true };
CheckBox ckbx = new CheckBox() { Left = 16, Top = 60, Width = 240, Text = boolStr };
Button confirmation = new Button() { Text = "Okay!", Left = 16, Width = 80, Top = 88, TabIndex = 1, TabStop = true };
confirmation.Click += (sender, e) => { prompt.Close(); };
prompt.Controls.Add(textLabel);
prompt.Controls.Add(textBox);
prompt.Controls.Add(ckbx);
prompt.Controls.Add(confirmation);
prompt.AcceptButton = confirmation;
prompt.StartPosition = FormStartPosition.CenterScreen;
prompt.ShowDialog();
return string.Format("{0};{1}", textBox.Text, ckbx.Checked.ToString());
}
}
...and text along with a selection of one of multiple options (TextBox and ComboBox):
public static class PromptForTextAndSelection
{
public static string ShowDialog(string caption, string text, string selStr)
{
Form prompt = new Form();
prompt.Width = 280;
prompt.Height = 160;
prompt.Text = caption;
Label textLabel = new Label() { Left = 16, Top = 20, Width = 240, Text = text };
TextBox textBox = new TextBox() { Left = 16, Top = 40, Width = 240, TabIndex = 0, TabStop = true };
Label selLabel = new Label() { Left = 16, Top = 66, Width = 88, Text = selStr };
ComboBox cmbx = new ComboBox() { Left = 112, Top = 64, Width = 144 };
cmbx.Items.Add("Dark Grey");
cmbx.Items.Add("Orange");
cmbx.Items.Add("None");
Button confirmation = new Button() { Text = "In Ordnung!", Left = 16, Width = 80, Top = 88, TabIndex = 1, TabStop = true };
confirmation.Click += (sender, e) => { prompt.Close(); };
prompt.Controls.Add(textLabel);
prompt.Controls.Add(textBox);
prompt.Controls.Add(selLabel);
prompt.Controls.Add(cmbx);
prompt.Controls.Add(confirmation);
prompt.AcceptButton = confirmation;
prompt.StartPosition = FormStartPosition.CenterScreen;
prompt.ShowDialog();
return string.Format("{0};{1}", textBox.Text, cmbx.SelectedItem.ToString());
}
}
Both require the same usings:
using System;
using System.Windows.Forms;
Call them like so:
Call them like so:
PromptForTextAndBoolean.ShowDialog("Jazz", "What text should accompany the checkbox?", "Allow Scat Singing");
PromptForTextAndSelection.ShowDialog("Rock", "What should the name of the band be?", "Beret color to wear");
react-router
v4 introduces a new way to block navigation using Prompt
. Just add this to the component that you would like to block:
import { Prompt } from 'react-router'
const MyComponent = () => (
<React.Fragment>
<Prompt
when={shouldBlockNavigation}
message='You have unsaved changes, are you sure you want to leave?'
/>
{/* Component JSX */}
</React.Fragment>
)
This will block any routing, but not page refresh or closing. To block that, you'll need to add this (updating as needed with the appropriate React lifecycle):
componentDidUpdate = () => {
if (shouldBlockNavigation) {
window.onbeforeunload = () => true
} else {
window.onbeforeunload = undefined
}
}
onbeforeunload has various support by browsers.
Using an empty string is perfectly fine and actually much safer than simply using $_SERVER['PHP_SELF']
.
When using $_SERVER['PHP_SELF']
it is very easy to inject malicious data by simply appending /<script>...
after the whatever.php
part of the URL so you should not use this method and stop using any PHP tutorial that suggests it.
I had the same problem in reading the pdf file in which data is in tabular format. After regular parse using PDFBox each row were extracted with comma as a separator... losing the columnar position. To resolve this I used PDFTextStripperByArea and using coordinates I extracted the data column by column for each row. This is provided that you have a fixed format pdf.
File file = new File("fileName.pdf");
PDDocument document = PDDocument.load(file);
PDFTextStripperByArea stripper = new PDFTextStripperByArea();
stripper.setSortByPosition( true );
Rectangle rect1 = new Rectangle( 50, 140, 60, 20 );
Rectangle rect2 = new Rectangle( 110, 140, 20, 20 );
stripper.addRegion( "row1column1", rect1 );
stripper.addRegion( "row1column2", rect2 );
List allPages = document.getDocumentCatalog().getAllPages();
PDPage firstPage = (PDPage)allPages.get( 2 );
stripper.extractRegions( firstPage );
System.out.println(stripper.getTextForRegion( "row1column1" ));
System.out.println(stripper.getTextForRegion( "row1column2" ));
Then row 2 and so on...
The Path class is very useful here.
You get two methods called
that could solve your issue
So for example you could write: (if you don't mind the exact file name)
using(StreamWriter sw = new StreamWriter(Path.GetTempFileName()))
{
sw.WriteLine("Your error message");
}
Or if you need to set your file name
string myTempFile = Path.Combine(Path.GetTempPath(), "SaveFile.txt");
using(StreamWriter sw = new StreamWriter(myTempFile))
{
sw.WriteLine("Your error message");
}
Ok here is my two cents.
If you are planning to seriously get into the game industry I recommend you learn both languages. Starting off with C++ then moving into a managed language like C#. C++ has it's advantages over C#, but C# also has advantages over C++.
Personally I prefer C# over C++ any day. This is because many reasons:, just a few:
Now...there are many things that I miss about C++. I miss being able to (completely) manage my own memory. I can't tell you how many times I caught myself trying to 'delete' an instance/reference. Another thing I dislike about C# is the inability to use multiple-inheritance, but then again it has forced me to think more about how to structure my code.
There has been more discussions on this topic than there are stars in the known universe and they all close at a dead end. Neither language is better than the other and refusing either one for the other will just hurt you in the long run. Times change and so do the standards for computer programming.
Whatever language you choose to keep at the top of your list, always keep your options open and don't set your mind to any one single language. You say you already know C++, why not learn C#, it can't hurt and I 'promise' you, it will make you a better C++ programmer.
It seems in general you're just looking for a join:
> dat1 = pd.DataFrame({'dat1': [9,5]})
> dat2 = pd.DataFrame({'dat2': [7,6]})
> dat1.join(dat2)
dat1 dat2
0 9 7
1 5 6
I used astyle
to re-indent all my C/C++ code after finding mixed tabs and spaces. It also has options to force a particular brace style if you'd like.
actually , this has turned out to be couple of javascript changes in the code. calling of javascript method with ; at the end. placing script tags in body instead of head. and interestingly even change the text displayed (please "click") to something that is not an event. so Please rate etc.
turned debugger on safari, it didnot give much information or even errors at times.
Use 'Smalldatetime' data type
select convert(smalldatetime, getdate())
will fetch
2015-01-08 15:27:00
You can go to LESS CSS website http://lesscss.org/
Their dockable menu is light and performs well. The only caveat is that the effect takes place after the scroll is complete. Just do a view source to see the js.
If your filenames contain no whitepace and you don't have any subdirectories, you can use a simple for
loop:
$ for FILENAME in *; do mv $FILENAME Unix_$FILENAME; done
Otherwise use the convenient rename
command (which is a perl script) - although it might not be available out of the box on every Unix (e.g. OS X doesn't come with rename
).
A short overview at debian-administration.org:
If your filenames contain whitespace it's easier to use find
, on Linux the following should work:
$ find . -type f -name '*' -printf "echo mv '%h/%f' '%h/Unix_%f\n'" | sh
On BSD systems, there is no -printf
option, unfortunately. But GNU findutils should be installable (on e.g. Mac OS X with brew install findutils
).
$ gfind . -type f -name '*' -printf "mv \"%h/%f\" \"%h/Unix_%f\"\n" | sh
Since ID is auto increment, you can also specify ID=NULL as,
LOAD XML LOCAL INFILE '/pathtofile/file.xml' INTO TABLE my_tablename SET ID=NULL;
I found an excellent Chart.js
plugin that does exactly what you want:
https://github.com/emn178/Chart.PieceLabel.js
The JSON Ruby Gem is bundled with a shell script to prettify JSON:
sudo gem install json
echo '{ "foo": "bar" }' | prettify_json.rb
Script download: gist.github.com/3738968
Hm, I am surprised that among the answers I do not see the easiest solution.
Suppose, item_id
is an integer identity column in items
table and you update rows with the following statement:
UPDATE items
SET qwe = 'qwe'
WHERE asd = 'asd';
Then, to know the latest affected row right after the statement, you should slightly update the statement into the following:
UPDATE items
SET qwe = 'qwe',
item_id=LAST_INSERT_ID(item_id)
WHERE asd = 'asd';
SELECT LAST_INSERT_ID();
If you need to update only really changed row, you would need to add a conditional update of the item_id through the LAST_INSERT_ID checking if the data is going to change in the row.
Despite much effort, I have not found a built-in or plugin-assisted way to do what you're trying to do. I completely agree that it should be possible, as the program can distinguish foo
from buffoon
when you first highlight it, but no one seems to know a way of doing it.
However, here are some useful key combos for selecting words in Sublime Text 2:
Ctrl?G - selects all occurrences of the current word (AltF3 on Windows/Linux)
?D - selects the next instance of the current word (CtrlD)
?E, ?H - uses the current selection as the "Find" field in Find and Replace (CtrlE,CtrlH)
I had the exact same problem, this - "meta http-equiv="X-UA-Compatible" content="IE=7">" works great in IE8 and IE9, but not in IE10. There is a bug in the server browser definition files that shipped with .NET 2.0 and .NET 4, namely that they contain definitions for a certain range of browser versions. But the versions for some browsers (like IE 10) aren't within those ranges any more. Therefore, ASP.NET sees them as unknown browsers and defaults to a down-level definition, which has certain inconveniences, like that it does not support features like JavaScript.
My thanks to Scott Hanselman for this fix.
Here is the link -
This MS KP fix just adds missing files to the asp.net on your server. I installed it and rebooted my server and it now works perfectly. I would have thought that MS would have given this fix a wider distribution.
Rick
String start_dt = "2011-01-01"; // Input String
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); // Existing Pattern
Date getStartDt = formatter.parse(start_dt); //Returns Date Format according to existing pattern
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM-dd-yyyy");// New Pattern
String formattedDate = simpleDateFormat.format(getStartDt); // Format given String to new pattern
System.out.println(formattedDate); //outputs: 01-01-2011
Consider the case in which a service worker acts as an agnostic cache. Your only goal is serve the same resources that you would get from the network, but faster. Of course you can't ensure all the resources will be part of your origin (consider libraries served from CDNs, for instance). As the service worker has the potential of altering network responses, you need to guarantee you are not interested in the contents of the response, nor on its headers, nor even on the result. You're only interested on the response as a black box to possibly cache it and serve it faster.
This is what { mode: 'no-cors' }
was made for.
To remove a timezone (tzinfo) from a datetime object:
# dt_tz is a datetime.datetime object
dt = dt_tz.replace(tzinfo=None)
If you are using a library like arrow, then you can remove timezone by simply converting an arrow object to to a datetime object, then doing the same thing as the example above.
# <Arrow [2014-10-09T10:56:09.347444-07:00]>
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')
# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444, tzinfo=tzoffset(None, -25200))
tmpDatetime = arrowObj.datetime
# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444)
tmpDatetime = tmpDatetime.replace(tzinfo=None)
Why would you do this? One example is that mysql does not support timezones with its DATETIME type. So using ORM's like sqlalchemy will simply remove the timezone when you give it a datetime.datetime
object to insert into the database. The solution is to convert your datetime.datetime
object to UTC (so everything in your database is UTC since it can't specify timezone) then either insert it into the database (where the timezone is removed anyway) or remove it yourself. Also note that you cannot compare datetime.datetime
objects where one is timezone aware and another is timezone naive.
##############################################################################
# MySQL example! where MySQL doesn't support timezones with its DATETIME type!
##############################################################################
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')
arrowDt = arrowObj.to("utc").datetime
# inserts datetime.datetime(2014, 10, 9, 17, 56, 9, 347444, tzinfo=tzutc())
insertIntoMysqlDatabase(arrowDt)
# returns datetime.datetime(2014, 10, 9, 17, 56, 9, 347444)
dbDatetimeNoTz = getFromMysqlDatabase()
# cannot compare timzeone aware and timezone naive
dbDatetimeNoTz == arrowDt # False, or TypeError on python versions before 3.3
# compare datetimes that are both aware or both naive work however
dbDatetimeNoTz == arrowDt.replace(tzinfo=None) # True
For the sake of completeness, there is also a data.table
solution:
library(data.table)
result <- setDT(df)[, paste0(names(df), "_length") := lapply(.SD, stringr::str_length)]
result
# col1 col2 col1_length col2_length
#1: abc adf qqwe 3 8
#2: abcd d 4 1
#3: a e 1 1
#4: abcdefg f 7 1
An option that has not been touched on before is:
This has the added bonus of being able to correctly match escaped open tags.
Lets say you had the following string; String \"this "should" NOT match\" and "this \"should\" match"
Here, \"this "should" NOT match\"
should not be matched and "should"
should be.
On top of that this \"should\" match
should be matched and \"should\"
should not.
First an example.
// The input string.
const myString = 'String \\"this "should" NOT match\\" and "this \\"should\\" match"';
// The RegExp.
const regExp = new RegExp(
// Match close
'([\'"])(?!(?:[\\\\]{2})*[\\\\](?![\\\\]))' +
'((?:' +
// Match escaped close quote
'(?:\\1(?=(?:[\\\\]{2})*[\\\\](?![\\\\])))|' +
// Match everything thats not the close quote
'(?:(?!\\1).)' +
'){0,})' +
// Match open
'(\\1)(?!(?:[\\\\]{2})*[\\\\](?![\\\\]))',
'g'
);
// Reverse the matched strings.
matches = myString
// Reverse the string.
.split('').reverse().join('')
// '"hctam "\dluohs"\ siht" dna "\hctam TON "dluohs" siht"\ gnirtS'
// Match the quoted
.match(regExp)
// ['"hctam "\dluohs"\ siht"', '"dluohs"']
// Reverse the matches
.map(x => x.split('').reverse().join(''))
// ['"this \"should\" match"', '"should"']
// Re order the matches
.reverse();
// ['"should"', '"this \"should\" match"']
Okay, now to explain the RegExp. This is the regexp can be easily broken into three pieces. As follows:
# Part 1
(['"]) # Match a closing quotation mark " or '
(?! # As long as it's not followed by
(?:[\\]{2})* # A pair of escape characters
[\\] # and a single escape
(?![\\]) # As long as that's not followed by an escape
)
# Part 2
((?: # Match inside the quotes
(?: # Match option 1:
\1 # Match the closing quote
(?= # As long as it's followed by
(?:\\\\)* # A pair of escape characters
\\ #
(?![\\]) # As long as that's not followed by an escape
) # and a single escape
)| # OR
(?: # Match option 2:
(?!\1). # Any character that isn't the closing quote
)
)*) # Match the group 0 or more times
# Part 3
(\1) # Match an open quotation mark that is the same as the closing one
(?! # As long as it's not followed by
(?:[\\]{2})* # A pair of escape characters
[\\] # and a single escape
(?![\\]) # As long as that's not followed by an escape
)
This is probably a lot clearer in image form: generated using Jex's Regulex
Image on github (JavaScript Regular Expression Visualizer.) Sorry, I don't have a high enough reputation to include images, so, it's just a link for now.
Here is a gist of an example function using this concept that's a little more advanced: https://gist.github.com/scagood/bd99371c072d49a4fee29d193252f5fc#file-matchquotes-js
Dispatcher Controller are displayed in the figure all the incoming request is in intercepted by the dispatcher servlet that works as front controller. The dispatcher servlet gets an entry to handler mapping from the XML file and forwords the request to the Controller.
This tool might be useful, it's a pure PHP based export utility: https://github.com/2createStudio/shuttle-export
public static String padLeft(String in, int size, char padChar) {
if (in.length() <= size) {
char[] temp = new char[size];
/* Llenado Array con el padChar*/
for(int i =0;i<size;i++){
temp[i]= padChar;
}
int posIniTemp = size-in.length();
for(int i=0;i<in.length();i++){
temp[posIniTemp]=in.charAt(i);
posIniTemp++;
}
return new String(temp);
}
return "";
}
I figured it out from the PostgreSQL docs, the exact syntax is:
ALTER TABLE the_table ADD CONSTRAINT constraint_name UNIQUE (thecolumn);
Thanks Fred.
Something like
select *
from foo
where regexp_like( col1, '[^[:alpha:]]' ) ;
should work
SQL> create table foo( col1 varchar2(100) );
Table created.
SQL> insert into foo values( 'abc' );
1 row created.
SQL> insert into foo values( 'abc123' );
1 row created.
SQL> insert into foo values( 'def' );
1 row created.
SQL> select *
2 from foo
3 where regexp_like( col1, '[^[:alpha:]]' ) ;
COL1
--------------------------------------------------------------------------------
abc123
...and to prepend (add the beginning of) each line with *,
%s/^/*/g
The best answer here is to use all()
, which is the builtin for this situation. We combine this with a generator expression to produce the result you want cleanly and efficiently. For example:
>>> items = [[1, 2, 0], [1, 2, 0], [1, 2, 0]]
>>> all(flag == 0 for (_, _, flag) in items)
True
>>> items = [[1, 2, 0], [1, 2, 1], [1, 2, 0]]
>>> all(flag == 0 for (_, _, flag) in items)
False
Note that all(flag == 0 for (_, _, flag) in items)
is directly equivalent to all(item[2] == 0 for item in items)
, it's just a little nicer to read in this case.
And, for the filter example, a list comprehension (of course, you could use a generator expression where appropriate):
>>> [x for x in items if x[2] == 0]
[[1, 2, 0], [1, 2, 0]]
If you want to check at least one element is 0, the better option is to use any()
which is more readable:
>>> any(flag == 0 for (_, _, flag) in items)
True
1- To modify current URL and add / inject it (the new modified URL) as a new URL entry to history list, use pushState
:
window.history.pushState({}, document.title, "/" + "my-new-url.html");
2- To replace current URL without adding it to history entries, use replaceState
:
window.history.replaceState({}, document.title, "/" + "my-new-url.html");
3- Depending on your business logic, pushState
will be useful in cases such as:
you want to support the browser's back button
you want to create a new URL, add/insert/push the new URL to history entries, and make it current URL
allowing users to bookmark the page with the same parameters (to show the same contents)
to programmatically access the data through the stateObj
then parse from the anchor
As I understood from your comment, you want to clean your URL without redirecting again.
Note that you cannot change the whole URL. You can just change what comes after the domain's name. This means that you cannot change www.example.com/
but you can change what comes after .com/
www.example.com/old-page-name => can become => www.example.com/myNewPaage20180322.php
We can use:
1- The pushState() method if you want to add a new modified URL to history entries.
2- The replaceState() method if you want to update/replace current history entry.
.replaceState()
operates exactly like.pushState()
except that.replaceState()
modifies the current history entry instead of creating a new one. Note that this doesn't prevent the creation of a new entry in the global browser history.
.replaceState()
is particularly useful when you want to update the state object or URL of the current history entry in response to some user action.
To do that I will use The pushState() method for this example which works similarly to the following format:
var myNewURL = "my-new-URL.php";//the new URL
window.history.pushState("object or string", "Title", "/" + myNewURL );
Feel free to replace pushState
with replaceState
based on your requirements.
You can substitute the paramter "object or string"
with {}
and "Title"
with document.title
so the final statment will become:
window.history.pushState({}, document.title, "/" + myNewURL );
The previous two lines of code will make a URL such as:
https://domain.tld/some/randome/url/which/will/be/deleted/
To become:
https://domain.tld/my-new-url.php
Now let's try a different approach. Say you need to keep the file's name. The file name comes after the last /
and before the query string ?
.
http://www.someDomain.com/really/long/address/keepThisLastOne.php?name=john
Will be:
http://www.someDomain.com/keepThisLastOne.php
Something like this will get it working:
//fetch new URL
//refineURL() gives you the freedom to alter the URL string based on your needs.
var myNewURL = refineURL();
//here you pass the new URL extension you want to appear after the domains '/'. Note that the previous identifiers or "query string" will be replaced.
window.history.pushState("object or string", "Title", "/" + myNewURL );
//Helper function to extract the URL between the last '/' and before '?'
//If URL is www.example.com/one/two/file.php?user=55 this function will return 'file.php'
//pseudo code: edit to match your URL settings
function refineURL()
{
//get full URL
var currURL= window.location.href; //get current address
//Get the URL between what's after '/' and befor '?'
//1- get URL after'/'
var afterDomain= currURL.substring(currURL.lastIndexOf('/') + 1);
//2- get the part before '?'
var beforeQueryString= afterDomain.split("?")[0];
return beforeQueryString;
}
For one liner fans, try this out in your console/firebug and this page URL will change:
window.history.pushState("object or string", "Title", "/"+window.location.href.substring(window.location.href.lastIndexOf('/') + 1).split("?")[0]);
This page URL will change from:
http://stackoverflow.com/questions/22753052/remove-url-parameters-without-refreshing-page/22753103#22753103
To
http://stackoverflow.com/22753103#22753103
Note: as Samuel Liew indicated in the comments below, this feature has been introduced only for HTML5
.
An alternative approach would be to actually redirect your page (but you will lose the query string `?', is it still needed or the data has been processed?).
window.location.href = window.location.href.split("?")[0]; //"http://www.newurl.com";
Note 2:
Firefox seems to ignore window.history.pushState({}, document.title, '');
when the last argument is an empty string. Adding a slash ('/'
) worked as expected and removed the whole query part of the url string.
Chrome seems to be fine with an empty string.
You can use the
re
library
Assuming that you are able to load your full txt-file. You then define a list of unwanted nicknames and then substitute them with an empty string "".
# Delete unwanted characters
import re
# Read, then decode for py2 compat.
path_to_file = 'data/nicknames.txt'
text = open(path_to_file, 'rb').read().decode(encoding='utf-8')
# Define unwanted nicknames and substitute them
unwanted_nickname_list = ['SourDough']
text = re.sub("|".join(unwanted_nickname_list), "", text)
You can use the transpose
function from the data.table
library. Simple and fast solution that keeps numeric
values as numeric
.
library(data.table)
# get data
data("mtcars")
# transpose
t_mtcars <- transpose(mtcars)
# get row and colnames in order
colnames(t_mtcars) <- rownames(mtcars)
rownames(t_mtcars) <- colnames(mtcars)
To create a group of inputs you can create a custom html element
window.customElements.define('radio-group', RadioGroup);
https://gist.github.com/robdodson/85deb2f821f9beb2ed1ce049f6a6ed47
to keep selected option in each group, you need to add name attribute to inputs in group, if you not add it then all is one group.
Command works only if "use" -command has been first used to define the database where working in. Table column renaming syntax using DATABASE.TABLE throws error and does not work. Version: HIVE 0.12.
EXAMPLE:
hive> ALTER TABLE databasename.tablename CHANGE old_column_name new_column_name;
MismatchedTokenException(49!=90)
at org.antlr.runtime.BaseRecognizer.recoverFromMismatchedToken(BaseRecognizer.java:617)
at org.antlr.runtime.BaseRecognizer.match(BaseRecognizer.java:115)
at org.apache.hadoop.hive.ql.parse.HiveParser.alterStatementSuffixExchangePartition(HiveParser.java:11492)
...
hive> use databasename;
hive> ALTER TABLE tablename CHANGE old_column_name new_column_name;
OK
Where you have written the code
public class Main {
public static void main(String args[])
{
Calculate obj = new Calculate(1,2,'+');
obj.getAnswer();
}
}
Here you have to run the class "Main" instead of the class you created at the start of the program. To do so pls go to Run Configuration and search for this class name"Main" which is having the main method inside this(public static void main(String args[])). And you will get your output.
Use trim and val.
var value=$.trim($("#spa").val());
if(value.length>0)
{
//do some stuffs.
}
val()
: return the value of the input.
trim()
: will trim the white spaces.
This is how I understood it:
In Object oriented programming, we have something called classes. What are they for? They are to store some state and to store some methods to change that state i.e., they are encapsulating state and its methods.
It(class) does not care about the visibility of its own or of its contents. If we choose to hide the state or some methods, it is information hiding.
Now, take the scenario of an inheritance. We have a base class and a couple of derived (inherited) classes. So, what is the base class doing here? It is abstracting out some things from the derived classes.
All of them are different, right? But, we mix them up to write good object oriented programs. Hope it helps :)
For mysql 5.7.21 I use the following and works fine:
CREATE TABLE Posts
(
modified_at
timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
created_at
timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
)
Note: When using the System scope (as mentioned on this page), Maven needs absolute paths.
If your jars are under your project's root, you'll want to prefix your systemPath values with ${basedir}.
I believe using --no-index
is what you're looking for:
git diff [<options>] --no-index [--] <path> <path>
as mentioned in the git manual:
This form is to compare the given two paths on the filesystem. You can omit the
--no-index
option when running the command in a working tree controlled by Git and at least one of the paths points outside the working tree, or when running the command outside a working tree controlled by Git.
This is a very obscure fault that WCF services throw. The issue is that WCF is unable to verify the security of the message that was passed to the service.
This is almost always because of a server time skew. The remote server and the client's system time must be within (typically) 10 minutes of each other. If they are not, security validation will fail.
I'd call eloqua.com and find out what their server time is, and compare that to your server time.
The above solutions did not work for me. I fix the issue by the following steps:
You can pass your component as a prop and use the same way you would use a component.
function General(props) {
...
return (<props.substitute a={A} b={B} />);
}
function SpecificA(props) { ... }
function SpecificB(props) { ... }
<General substitute=SpecificA />
<General substitute=SpecificB />
for /F "eol= delims=~" %%d in ('CD') do set curdir=%%d
pushd %curdir%
Detect:
Debug CRT
Avoid:
Smart pointers, boehm GC
In java you can do some thing like:
if(driver.getTitle().contains("some expected text"))
//Pass
System.out.println("Page title contains \"some expected text\" ");
else
//Fail
System.out.println("Page title doesn't contains \"some expected text\" ");
For any Solaris users (am using 5.10, may apply to newer versions too, as well as other unix systems):
dos2unix doesn't default to overwriting the file, it will just print the updated version to stdout, so you will have to specify the source and target, i.e. the same name twice:
find . -type f -exec dos2unix {} {} \;
You can try this code:
cur.execute( "SELECT * FROM records WHERE email LIKE %s", (search,) )
You can see the documentation
You can check how this query works following this link.
IF OBJECT_ID('tempdb..#spacetable') IS NOT NULL
DROP TABLE tempdb..#spacetable
create table #spacetable
(
database_name varchar(50) ,
total_size_data int,
space_util_data int,
space_data_left int,
percent_fill_data float,
total_size_data_log int,
space_util_log int,
space_log_left int,
percent_fill_log char(50),
[total db size] int,
[total size used] int,
[total size left] int
)
insert into #spacetable
EXECUTE master.sys.sp_MSforeachdb 'USE [?];
select x.[DATABASE NAME],x.[total size data],x.[space util],x.[total size data]-x.[space util] [space left data],
x.[percent fill],y.[total size log],y.[space util],
y.[total size log]-y.[space util] [space left log],y.[percent fill],
y.[total size log]+x.[total size data] ''total db size''
,x.[space util]+y.[space util] ''total size used'',
(y.[total size log]+x.[total size data])-(y.[space util]+x.[space util]) ''total size left''
from (select DB_NAME() ''DATABASE NAME'',
sum(size*8/1024) ''total size data'',sum(FILEPROPERTY(name,''SpaceUsed'')*8/1024) ''space util''
,case when sum(size*8/1024)=0 then ''divide by zero'' else
substring(cast((sum(FILEPROPERTY(name,''SpaceUsed''))*1.0*100/sum(size)) as CHAR(50)),1,6) end ''percent fill''
from sys.master_files where database_id=DB_ID(DB_NAME()) and type=0
group by type_desc ) as x ,
(select
sum(size*8/1024) ''total size log'',sum(FILEPROPERTY(name,''SpaceUsed'')*8/1024) ''space util''
,case when sum(size*8/1024)=0 then ''divide by zero'' else
substring(cast((sum(FILEPROPERTY(name,''SpaceUsed''))*1.0*100/sum(size)) as CHAR(50)),1,6) end ''percent fill''
from sys.master_files where database_id=DB_ID(DB_NAME()) and type=1
group by type_desc )y'
select * from #spacetable
order by database_name
drop table #spacetable
In my case, I was using a dependency scoped as <scope>test</scope>
. This made the class available at development time but, by at compile time, I got this message.
Turn the class scope for <scope>provided</scope>
solved the problem.
Python dictionaries have a key and a value, what you are asking for is what key(s) point to a given value.
You can only do this in a loop:
[k for (k, v) in i.iteritems() if v == 0]
Note that there can be more than one key per value in a dict; {'a': 0, 'b': 0}
is perfectly legal.
If you want ordering you either need to use a list or a OrderedDict instance instead:
items = ['a', 'b', 'c']
items.index('a') # gives 0
items[0] # gives 'a'
The entire transmission, including the query string, the whole URL, and even the type of request (GET, POST, etc.) is encrypted when using HTTPS.
The c++ inline
keyword is misleading, it doesn't mean "inline this function". If a function is defined as inline, it simply means that it can be defined multiple times as long as all definitions are equal. It's perfectly legal for a function marked inline
to be a real function that is called instead of getting code inlined at the point where it's called.
Defining a function in a header file is needed for templates, since e.g. a templated class isn't really a class, it's a template for a class which you can make multiple variations of. In order for the compiler to be able to e.g. make a Foo<int>::bar()
function when you use the Foo template to create a Foo class, the actual definition of Foo<T>::bar()
must be visible.
CURDATE()
will give current date while NOW()
will give full date time.
Run the queries, and you will find out whats the difference between them.
SELECT NOW(); -- You will get 2010-12-09 17:10:18
SELECT CURDATE(); -- You will get 2010-12-09
There are severals ways to communicate between activities, fragments, services etc. The obvious one is to communicate using interfaces. However, it is not a productive way to communicate. You have to implement the listeners etc.
My suggestion is to use an event bus. Event bus is a publish/subscribe pattern implementation.
You can subscribe to events in your activity and then you can post that events in your fragments etc.
Here on my blog post you can find more detail about this pattern and also an example project to show the usage.
Use as.integer
:
set.seed(1)
x <- runif(5, 0, 100)
x
[1] 26.55087 37.21239 57.28534 90.82078 20.16819
as.integer(x)
[1] 26 37 57 90 20
Test for class:
xx <- as.integer(x)
str(xx)
int [1:5] 26 37 57 90 20
<input type="checkbox" id="something" />
$("#something").click( function(){
if( $(this).is(':checked') ) alert("checked");
});
Edit: Doing this will not catch when the checkbox changes for other reasons than a click, like using the keyboard. To avoid this problem, listen to change
instead of click
.
For checking/unchecking programmatically, take a look at Why isn't my checkbox change event triggered?
The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:
ffmpeg -i input.mov -qscale 0 output.mp4
Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0
):
ffmpeg -i input.mov -q:v 0 output.mp4
If u want to set background of the list then place the image before the < Textview>
< ImageView
android:background="@drawable/image_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
and if u want to change color then put color code on above textbox like this
android:textColor="#ffffff"
Use the command dir
to list all the directories and files in a directory; ls
is a unix command.
If you are using Visual Studio 2017 or later which ships with MSBuild 15 or later, and your .csproj files are in the new PackageReference
format, the simplest method is to use the new MSBuild Restore
target.
No-one has actually answered the original question, which is "how do I get NuGet packages to auto-restore when building from the command-line with MSBuild?" The answer is: unless you are using the "Enable NuGet package restore" option (which is now deprecated as per this reference), you can't (but see below). If you are trying to do e.g. automated builds on a CI server, this sucks.
However there is a slightly roundabout way to get the desired behaviour:
nuget restore
which will auto-download all the missing packages.msbuild
to build your solution.Aside: while the new and recommended way to do auto package restore involves less clutter in your version control, it also makes command-line package restore impossible unless you jump through the extra hoop of downloading and running nuget.exe
. Progress?
In cases where the name attribute is different it is easiest to control the radio group via JQuery. When an option is selected use JQuery to un-select the other options.
Both
-Djavax.net.ssl.trustStore=path/to/trustStore.jks
and
System.setProperty("javax.net.ssl.trustStore", "cacerts.jks");
do the same thing and have no difference working wise. In your case you just have a typo. You have misspelled trustStore
in javax.net.ssl.trustStore.
I wanted to do exactly this so I could access Jenkins from the root domain.
I found I had to disable the default site to get this to work. Here's exactly what I did.
$ sudo vi /etc/apache2/sites-available/jenkins
And insert this into file:
<VirtualHost *:80>
ProxyPreserveHost On
ProxyRequests Off
ServerName mydomain.com
ServerAlias mydomain
ProxyPass / http://localhost:8080/
ProxyPassReverse / http://localhost:8080/
<Proxy *>
Order deny,allow
Allow from all
</Proxy>
</VirtualHost>
Next you need to enable/disable the appropriate sites:
$ sudo a2ensite jenkins
$ sudo a2dissite default
$ sudo service apache2 reload
Hope it helps someone.
UUID is similar in notion to port numbers in Internet. However, the difference between Bluetooth and the Internet is that, in Bluetooth, port numbers are assigned dynamically by the SDP (service discovery protocol) server during runtime where each UUID is given a port number. Other devices will ask the SDP server, who is registered under a reserved port number, about the available services on the device and it will reply with different services distinguishable from each other by being registered under different UUIDs.
Yes, on the server side $_SERVER['DOCUMENT_ROOT']
is equivalent to /
on the client side.
For example: the value of "{$_SERVER['DOCUMENT_ROOT']}/images/thumbnail.png"
will be the string /var/www/html/images/thumbnail.png
on a server where it's local file at that path can be reached from the client side at the url http://example.com/images/thumbnail.png
No, in other words the value of $_SERVER['DOCUMENT_ROOT']
is not /
rather it is the server's local path to what the server shows the client at example.com/
note: $_SERVER['DOCUMENT_ROOT']
does not include a trailing /
Notice that another issue that might be causing this is that, the "FollowSymLinks" option of a parent directory might have been mistakenly overwritten by the options of your project's directory. This was the case for me and made me pull my hair until I found out the cause!
Here's an example of such a mistake:
<Directory />
Options FollowSymLinks
AllowOverride all
Require all denied
</Directory>
<Directory /var/www/>
Options Indexes # <--- NOT OK! It's overwriting the above option of the "/" directory.
AllowOverride all
Require all granted
</Directory>
So now if you check the Apache's log message(tail -n 50 -f /var/www/html/{the_error_log_file_of_your_site}
) you'll see such an error:
Options FollowSymLinks and SymLinksIfOwnerMatch are both off, so the RewriteRule directive
is also forbidden due to its similar ability to circumvent directory restrictions
That's because Indexes
in the above rules for /var/www
directory is overwriting the FolowSymLinks
of the /
directory. So now that you know the cause, in order to fix it, you can do many things depending on your need. For instance:
<Directory />
Options FollowSymLinks
AllowOverride all
Require all denied
</Directory>
<Directory /var/www/>
Options FollowSymLinks Indexes # <--- OK.
AllowOverride all
Require all granted
</Directory>
Or even this:
<Directory />
Options FollowSymLinks
AllowOverride all
Require all denied
</Directory>
<Directory /var/www/>
Options -Indexes # <--- OK as well! It will NOT cause an overwrite.
AllowOverride all
Require all granted
</Directory>
The example above will not cause the overwrite issue, because in Apache, if an option is "+" it will overwrite the "+"s only, and if it's a "-", it will overwrite the "-"s... (Don't ask me for a reference on that though, it's just my interpretation of an Apache's error message(checked through journalctl -xe
) which says: Either all Options must start with + or -, or no Option may.
when an option has a sign, but another one doesn't(E.g., FollowSymLinks -Indexes). So it's my personal conclusion -thus should be taken with a grain of salt- that if I've used -Indexes
as the option, that will be considered as a whole distinct set of options by the Apache from the other option in the "/" which doesn't have any signs on it, and so no annoying rewrites will occur in the end, which I could successfully confirm by the above rules in a project directory of my own).
Hope that this will help you pull much less of your hair! :)
For something really basic use this:
<a href="#middle">Go To Middle</a>
Or for something simple in javascript check out this jQuery plugin ScrollTo. Quite useful for scrolling smoothly.
Yes, you can do it by specifying the comparison method. The advantage is the sorted object don't have to be IComparable
aListOfObjects.Sort((x, y) =>
{
int result = x.A.CompareTo(y.A);
return result != 0 ? result : x.B.CompareTo(y.B);
});
Look into the XMLSerializer
class.
If you want to save the state of objects and be able to recreate them easily at another time, serialization is your best bet.
Serialize it so you are returned the fully-formed XML. Write this to a file using the StreamWriter
class.
Later, you can read in the contents of your file, and pass it to the serializer class along with an instance of the object you want to populate, and the serializer will take care of deserializing as well.
Here's a code snippet taken from Microsoft Support:
using System;
public class clsPerson
{
public string FirstName;
public string MI;
public string LastName;
}
class class1
{
static void Main(string[] args)
{
clsPerson p=new clsPerson();
p.FirstName = "Jeff";
p.MI = "A";
p.LastName = "Price";
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(p.GetType());
// at this step, instead of passing Console.Out, you can pass in a
// Streamwriter to write the contents to a file of your choosing.
x.Serialize(Console.Out, p);
Console.WriteLine();
Console.ReadLine();
}
}
To delete all objects in a list, you can directly write list = []
Here is example:
>>> a = [1, 2, 3]
>>> a
[1, 2, 3]
>>> a = []
>>> a
[]
A simple way:
objs.sort(function(a,b) {
return b.last_nom.toLowerCase() < a.last_nom.toLowerCase();
});
See that '.toLowerCase()'
is necessary to prevent erros
in comparing strings.
If you use maven, you can add this in pom.xml:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<configuration>
<argLine>-Dspring.profiles.active=test</argLine>
</configuration>
</plugin>
...
Then, maven should run your integration tests (*IT.java) using this arugument, and also IntelliJ will start with this profile activated - so you can then specify all properties inside
application-test.yml
and you should not need "-default" properties.
Read Kernighan and Ritchie
#include <string.h>
void reverse(char s[])
{
int length = strlen(s) ;
int c, i, j;
for (i = 0, j = length - 1; i < j; i++, j--)
{
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
Put for div same name as in href target.
ex: <div name="link">
and <a href="#link">
NOTE in recent VS versions (2015+) it seems this extension no longer exists/has this feature.
You can also download VSCommands for VS2012 by Squared Infinity which has a feature to change it to run as admin (as well as some other cool bits and pieces)
Update
One can install the commands from the Visual Studio menu bar using Tools
->Extensions and Updates
selecting Online
and searching for vscommands
where then one selects VSCommands for Visual Studio 20XX
depending on whether using 2012 or 2013 (or greater going forward) and download and install.
You can just do this:
git remote add origin ssh://user@host:1234/srv/git/example
1234
is the ssh port being used
If you are on SQL Server 2008 or later version, you can use the ROLLUP()
GROUP BY function:
SELECT
Type = ISNULL(Type, 'Total'),
TotalSales = SUM(TotalSales)
FROM atable
GROUP BY ROLLUP(Type)
;
This assumes that the Type
column cannot have NULLs and so the NULL in this query would indicate the rollup row, the one with the grand total. However, if the Type
column can have NULLs of its own, the more proper type of accounting for the total row would be like in @Declan_K's answer, i.e. using the GROUPING()
function:
SELECT
Type = CASE GROUPING(Type) WHEN 1 THEN 'Total' ELSE Type END,
TotalSales = SUM(TotalSales)
FROM atable
GROUP BY ROLLUP(Type)
;
I just restarted the adb (Android Debug Bridge) this way:
and it works again!
You can use getRawValue()
this.formGroup.getRawValue().attribute
This gets parent if it is a div. Then it gets class.
var div = $(this).parent("div");
var _class = div.attr("class");
I resolved this issue in my project by deleting a library:
Reason: I included a library-project in my project, and mistakenly did not removed the previous lib from my project, so when I was running the project then same library dex files were generating twice, when I removed the same-library from lib folder of my project, the error gone away and build was created successfully, I hope others may face the same issue.
You could do this:
var timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("someSelector"), userInfo: nil, repeats: false)
func someSelector() {
// Something after a delay
}
let timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(someSelector), userInfo: nil, repeats: false)
func someSelector() {
// Something after a delay
}
When an activity is created it's onCreate() method is called.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
savedInstanceState is an object of Bundle class which is null for the first time, but it contains values when it is recreated. To save Activity's state you have to override onSaveInstanceState().
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putString("key","Welcome Back")
super.onSaveInstanceState(outState); //save state
}
put your values in "outState" Bundle object like outState.putString("key","Welcome Back") and save by calling super. When activity will be destroyed it's state get saved in Bundle object and can be restored after recreation in onCreate() or onRestoreInstanceState(). Bundle received in onCreate() and onRestoreInstanceState() are same.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//restore activity's state
if(savedInstanceState!=null){
String reStoredString=savedInstanceState.getString("key");
}
}
or
//restores activity's saved state
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
String restoredMessage=savedInstanceState.getString("key");
}
<!DOCTYPE html>
<html>
<head>
<title>float object center</title>
<style type="text/css">
#warp{
width:500px;
margin:auto;
}
.ser{
width: 200px;
background-color: #ffffff;
display: block;
float: left;
margin-right: 50px;
}
.inim{
width: 120px;
margin-left: 40px;
}
</style>
</head>
<body>
<div id="warp">
<div class="ser">
<img class="inim" src="http://123greetingsquotes.com/wp-content/uploads/2015/01/republic-day-parade-india-images-120x120.jpg">
</div>
<div class="ser">
<img class="inim" sr`enter code here`c="http://123greetingsquotes.com/wp-content/uploads/2015/01/republic-day-parade-india-images-120x120.jpg">
</div>
</div>
</body>
</html>
create two or more div's you want and give them a definite width like 100px for each then float it left or right
then warp these two div's in another div and give it the width of 200px. to this div apply margin auto. boom it works pretty well. check the above example.
Since Java 5 you can use Arrays.toString(arr)
or Arrays.deepToString(arr)
for arrays within arrays. Note that the Object[]
version calls .toString()
on each object in the array. The output is even decorated in the exact way you're asking.
Examples:
String[] array = new String[] {"John", "Mary", "Bob"};
System.out.println(Arrays.toString(array));
Output:
[John, Mary, Bob]
String[][] deepArray = new String[][] {{"John", "Mary"}, {"Alice", "Bob"}};
System.out.println(Arrays.toString(deepArray));
//output: [[Ljava.lang.String;@106d69c, [Ljava.lang.String;@52e922]
System.out.println(Arrays.deepToString(deepArray));
Output:
[[John, Mary], [Alice, Bob]]
double
Array:double[] doubleArray = { 7.0, 9.0, 5.0, 1.0, 3.0 };
System.out.println(Arrays.toString(doubleArray));
Output:
[7.0, 9.0, 5.0, 1.0, 3.0 ]
int
Array:int[] intArray = { 7, 9, 5, 1, 3 };
System.out.println(Arrays.toString(intArray));
Output:
[7, 9, 5, 1, 3 ]
You can try something like below
$($.parseHTML(<<table html string variable here>>)).find("td:contains('<<some text to find>>')").first().prev().text();
app.get('/fruit/:fruitName/:fruitColor', function(req, res) {
var data = {
"fruit": {
"apple": req.params.fruitName,
"color": req.params.fruitColor
}
};
send.json(data);
});
If that doesn't work, try using console.log(req.params) to see what it is giving you.
There is actually a truly invisible character: U+FEFF
.
This character is called the Byte Order Mark and is related to the Unicode 8 system. It is a really confusing concept that can be explained HERE The Byte Order Mark or BOM
for short is an invisible character that doesn't take up any space. You can copy the character bellow between the >
and <
.
Here is the character:
> <
How to catch this character in action:
>
and <
,You will notice that when your caret gets to the place you pasted the character, it will briefly stop for around half a second. This is becuase the caret is passing over the invisible character. Even though you can't see it doesn't mean it isn't there. The caret still sees that there is a character in that area that you pasted the BOM and will pass through it. Since the BOM is invisble, the caret will look like it has paused for a brief moment. You can past the BOM multiple times in an area and redo the steps above to really show the affect. Good luck!
EDIT: Sadly, Stackoverflow doesn't like the character. Here is an example from w3.org: https://www.w3.org/International/questions/examples/phpbomtest.php
In addition to the Haack post, Hanselman also has a similar post. BIN Delploying ASP.NET MVC 3 with Razor to a Windows Server without MVC installed
For me, the "Copy Local = true" solution was insufficient because my Website's project references did not include all the dlls that were missing. As Scott mentions in his post, I also needed to get additional dlls from the following folder on my development box: C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\Assemblies. The error message informed me which dll was missing (System.Web.Infrastructure, System.Web.Razor, etc.) I continued to add each missing dll, one by one, until it worked.
In simple terms
It is better to have more coarse-grained service operations, which are composed by fine-grained operations
Let's consider this scenario. You have App.jsx
as the root file for you ReactJS SPA. In it your render()
looks similar to this:
<Switch>
<Route path="/comp" component={MyComponent} />
</Switch>
then, you should be able to use this.props.history
inside MyComponent
without a problem. Let's say you are rendering MySecondComponent
inside MyComponent
, in that case you need to call it in such manner:
<MySecondComponent {...props} />
which will pass the props from MyComponent
down to MySecondComponent
, thus making this.props.history
available in MySecondComponent
Here is one version that works with filenames that may contain spaces, newlines, and glob characters as well:
find . -type f -printf "%T@ %p\0" | sort -zk1nr
find ... -printf
prints the file modification time (Epoch value) followed by a space and \0
terminated filenames.sort -zk1nr
reads NUL terminated data and sorts it reverse numericallyAs the question is tagged with Linux, I am assuming GNU Core Utilities are available.
You can pipe the above with:
xargs -0 printf "%s\n"
to print the modification time and filenames sorted by modification time (most recent first) terminated by newlines.
strstr(request, "favicon") != NULL
Just had that problem in a production system in the company where I live... A webpage that made a LDAP bind stopped working after an IP changed.
The solution... ... I installed Basic Authentication to perform the troubleshooting indicated here: https://support.microsoft.com/en-us/kb/329986
And after that, things just started to work. Even after I re-disabled Basic Authentication in the page I was testing, all other pages started working again with Windows Authentication.
Regards, Acácio
I am using node version manager. I was getting this error message because I had switched to a different version of node. When I switched back to the version of node where I installed bower, this error went away. In my case, the command was nvm use stable
Png files can handle transparency.
So you could use this question Save plot to image file instead of displaying it using Matplotlib so as to save you graph as a png
file.
And if you want to turn all white pixel transparent, there's this other question : Using PIL to make all white pixels transparent?
If you want to turn an entire area to transparent, then there's this question: And then use the PIL library like in this question Python PIL: how to make area transparent in PNG? so as to make your graph transparent.
Python's standard library has json
and urllib2
modules.
import json
import urllib2
data = json.load(urllib2.urlopen('http://someurl/path/to/json'))
Using variable notation, you can do it without a temporary file:
${C:\file.txt} = ${C:\file.txt} | select -skip 1
function Remove-Topline ( [string[]]$path, [int]$skip=1 ) {
if ( -not (Test-Path $path -PathType Leaf) ) {
throw "invalid filename"
}
ls $path |
% { iex "`${$($_.fullname)} = `${$($_.fullname)} | select -skip $skip" }
}
Since there is no native way to do this ,Here is less intrusive solution i found (dont add any 'old' prototype methods):
var ListenerTracker=new function(){
var is_active=false;
// listener tracking datas
var _elements_ =[];
var _listeners_ =[];
this.init=function(){
if(!is_active){//avoid duplicate call
intercep_events_listeners();
}
is_active=true;
};
// register individual element an returns its corresponding listeners
var register_element=function(element){
if(_elements_.indexOf(element)==-1){
// NB : split by useCapture to make listener easier to find when removing
var elt_listeners=[{/*useCapture=false*/},{/*useCapture=true*/}];
_elements_.push(element);
_listeners_.push(elt_listeners);
}
return _listeners_[_elements_.indexOf(element)];
};
var intercep_events_listeners = function(){
// backup overrided methods
var _super_={
"addEventListener" : HTMLElement.prototype.addEventListener,
"removeEventListener" : HTMLElement.prototype.removeEventListener
};
Element.prototype["addEventListener"]=function(type, listener, useCapture){
var listeners=register_element(this);
// add event before to avoid registering if an error is thrown
_super_["addEventListener"].apply(this,arguments);
// adapt to 'elt_listeners' index
useCapture=useCapture?1:0;
if(!listeners[useCapture][type])listeners[useCapture][type]=[];
listeners[useCapture][type].push(listener);
};
Element.prototype["removeEventListener"]=function(type, listener, useCapture){
var listeners=register_element(this);
// add event before to avoid registering if an error is thrown
_super_["removeEventListener"].apply(this,arguments);
// adapt to 'elt_listeners' index
useCapture=useCapture?1:0;
if(!listeners[useCapture][type])return;
var lid = listeners[useCapture][type].indexOf(listener);
if(lid>-1)listeners[useCapture][type].splice(lid,1);
};
Element.prototype["getEventListeners"]=function(type){
var listeners=register_element(this);
// convert to listener datas list
var result=[];
for(var useCapture=0,list;list=listeners[useCapture];useCapture++){
if(typeof(type)=="string"){// filtered by type
if(list[type]){
for(var id in list[type]){
result.push({"type":type,"listener":list[type][id],"useCapture":!!useCapture});
}
}
}else{// all
for(var _type in list){
for(var id in list[_type]){
result.push({"type":_type,"listener":list[_type][id],"useCapture":!!useCapture});
}
}
}
}
return result;
};
};
}();
ListenerTracker.init();
The correct answer should be 2nCn/(n+1) for unlabelled nodes and if the nodes are labelled then (2nCn)*n!/(n+1).
I actually ended up with something like this to allow for the navbar collapse.
@media (min-width: 768px) { //set this to wherever the navbar collapse executes
.navbar-nav > li > a{
line-height: 7em; //set this height to the height of the logo.
}
}
Please find below code if you want user to restrict with entering 10 digit in input control
<input class="form-control input-md text-box single-line" id="ContactNumber" max="9999999999" min="1000000000" name="ContactNumber" required="required" type="number" value="9876658688">
Benefits -
It will not allow to type any alphabets in input box because type of input box is 'number'
it will allow max 10 digits because max property is set to maximum possible value in 10 digits
it will not allow user to enter anything less than 10 digits as we want to restrict user in 10 digit phone number. min property in code is having minimum possible value in 10 digits so it will tell user to enter valid 10 digit value not less than that.
I figured it out!
With almost 2 hours worth of trial and error, i figured it out.
This WORKS and is what you do to pass variables to remote job:
def handle = triggerRemoteJob(remoteJenkinsName: 'remoteJenkins', job: 'RemoteJob' paramters: "param1=${env.PARAM1}\nparam2=${env.param2}")
Use \n to separate two parameters, no spaces..
As opposed to parameters: '''someparams'''
we use paramters: "someparams"
the " ... " is what gets us the values of the desired variables. (These are double quotes, not two single quotes)
the ''' ... ''' or ' ... ' will not get us those values. (Three single quotes or just single quotes)
All parameters here are defined in environment{} block at the start of the pipeline and are modified in stages>steps>scripts wherever necessary.
I also tested and found that when you use " ... " you cannot use something like ''' ... "..." ''' or "... '..'..." or any combination of it...
The catch here is that when you are using "..." in parameters section, you cannot pass a string parameter; for example This WILL NOT WORK:
def handle = triggerRemoteJob(remoteJenkinsName: 'remoteJenkins', job: 'RemoteJob' paramters: "param1=${env.PARAM1}\nparam2='param2'")
if you want to pass something like the one above, you will need to set an environment variable param2='param2' and then use ${env.param2} in the parameters section of remote trigger plugin step
var pdf = MyPdf.pdf;
window.open(pdf);
This will open the pdf document in a full window from JavaScript
A function to open windows would look like this:
function openPDF(pdf){
window.open(pdf);
return false;
}
While Guy's answer is correct (and probably fits 9 out of 10 cases), it's worth noting that if you are attempting to do this from a control that already has its DataContext set further up the stack, you'll resetting this when you set DataContext back to itself:
DataContext="{Binding RelativeSource={RelativeSource Self}}"
This will of course then break your existing bindings.
If this is the case, you should set the RelativeSource on the control you are trying to bind, rather than its parent.
i.e. for binding to a UserControl's properties:
Binding Path=PropertyName,
RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}
Given how difficult it can be currently to see what's going on with data binding, it's worth bearing this in mind even if you find that setting RelativeSource={RelativeSource Self}
currently works :)
You cannot directly save a Python file as an exe and expect it to work -- the computer cannot automatically understand whatever code you happened to type in a text file. Instead, you need to use another program to transform your Python code into an exe.
I recommend using a program like Pyinstaller. It essentially takes the Python interpreter and bundles it with your script to turn it into a standalone exe that can be run on arbitrary computers that don't have Python installed (typically Windows computers, since Linux tends to come pre-installed with Python).
To install it, you can either download it from the linked website or use the command:
pip install pyinstaller
...from the command line. Then, for the most part, you simply navigate to the folder containing your source code via the command line and run:
pyinstaller myscript.py
You can find more information about how to use Pyinstaller and customize the build process via the documentation.
You don't necessarily have to use Pyinstaller, though. Here's a comparison of different programs that can be used to turn your Python code into an executable.
Look at this answer: https://css-tricks.com/the-trick-to-viewport-units-on-mobile/
// First we get the viewport height and we multiple it by 1% to get a value for a vh unit_x000D_
let vh = window.innerHeight * 0.01;_x000D_
// Then we set the value in the --vh custom property to the root of the document_x000D_
document.documentElement.style.setProperty('--vh', `${vh}px`);_x000D_
_x000D_
// We listen to the resize event_x000D_
window.addEventListener('resize', () => {_x000D_
// We execute the same script as before_x000D_
let vh = window.innerHeight * 0.01;_x000D_
document.documentElement.style.setProperty('--vh', `${vh}px`);_x000D_
});
_x000D_
body {_x000D_
background-color: #333;_x000D_
}_x000D_
_x000D_
.module {_x000D_
height: 100vh; /* Use vh as a fallback for browsers that do not support Custom Properties */_x000D_
height: calc(var(--vh, 1vh) * 100);_x000D_
margin: 0 auto;_x000D_
max-width: 30%;_x000D_
}_x000D_
_x000D_
.module__item {_x000D_
align-items: center;_x000D_
display: flex;_x000D_
height: 20%;_x000D_
justify-content: center;_x000D_
}_x000D_
_x000D_
.module__item:nth-child(odd) {_x000D_
background-color: #fff;_x000D_
color: #F73859;_x000D_
}_x000D_
_x000D_
.module__item:nth-child(even) {_x000D_
background-color: #F73859;_x000D_
color: #F1D08A;_x000D_
}
_x000D_
<div class="module">_x000D_
<div class="module__item">20%</div>_x000D_
<div class="module__item">40%</div>_x000D_
<div class="module__item">60%</div>_x000D_
<div class="module__item">80%</div>_x000D_
<div class="module__item">100%</div>_x000D_
</div>
_x000D_
I realise that it's been a very long time but thought I'd add anyway. If you just want the table, and not the create table statement you could use
select into x from db.schema.y where 1=0
to copy the table to a new DB
You can vertically align by setting an element to display: inline-block, then setting vertical-align: middle;
A better and quite simpler one
SELECT [Database Name] = DB_NAME(database_id),
[Type] = CASE WHEN Type_Desc = 'ROWS' THEN 'Data File(s)'
WHEN Type_Desc = 'LOG' THEN 'Log File(s)'
ELSE Type_Desc END,
[Size in MB] = CAST( ((SUM(Size)* 8) / 1024.0) AS DECIMAL(18,2) )
FROM sys.master_files
--Uncomment if you need to query for a particular database
--WHERE database_id = DB_ID(‘Database Name’)
GROUP BY GROUPING SETS
(
(DB_NAME(database_id), Type_Desc),
(DB_NAME(database_id))
) ORDER BY DB_NAME(database_id), Type_Desc DESC
It will give you size of Data File(s) and Log File(s) separately like below
DatabaseName Type Size in MB
-------------------------------------------
FMS Data File(s) 23.00
FMS Log File(s) 1.50
PointOfSale Data File(s) 4.00
PointOfSale Log File(s) 1.25
Union2 Data File(s) 336.00
Union2 Log File(s) 1191.13
SurveyProject Data File(s) 4.00
SurveyProject Log File(s) 1.00
Using ".h" method is better But if you really want to include the .cpp file then make foo(int) static in foo.cpp
"Connection reset by peer" is the TCP/IP equivalent of slamming the phone back on the hook. It's more polite than merely not replying, leaving one hanging. But it's not the FIN-ACK expected of the truly polite TCP/IP converseur. (From other SO answer)
So you can't do anything about it, it is the issue of the server.
But you could use try .. except
block to handle that exception:
from socket import error as SocketError
import errno
try:
response = urllib2.urlopen(request).read()
except SocketError as e:
if e.errno != errno.ECONNRESET:
raise # Not error we are looking for
pass # Handle error here.