This line looks suspicious:
invaders[i] = inv;
You're never incrementing i
, so you keep assigning to invaders[0]
. If this is just an error you made when reducing your code to the example, check how you calculate i
in the real code; you could be exceeding the size of invaders
.
If as your comment suggests, you're creating 55 invaders
, then check that invaders
has been initialised correctly to handle this number.
If the types of the parameters are all the same (varchar2
for example), you can have a package like this which will do the following:
CREATE OR REPLACE PACKAGE testuser.test_pkg IS
TYPE assoc_array_varchar2_t IS TABLE OF VARCHAR2(4000) INDEX BY BINARY_INTEGER;
PROCEDURE your_proc(p_parm IN assoc_array_varchar2_t);
END test_pkg;
CREATE OR REPLACE PACKAGE BODY testuser.test_pkg IS
PROCEDURE your_proc(p_parm IN assoc_array_varchar2_t) AS
BEGIN
FOR i IN p_parm.first .. p_parm.last
LOOP
dbms_output.put_line(p_parm(i));
END LOOP;
END;
END test_pkg;
Then, to call it you'd need to set up the array and pass it:
DECLARE
l_array testuser.test_pkg.assoc_array_varchar2_t;
BEGIN
l_array(0) := 'hello';
l_array(1) := 'there';
testuser.test_pkg.your_proc(l_array);
END;
/
The shortest way is indeed just
String fileContents = new File('/path/to/file').text
but in this case you have no control on how the bytes in the file are interpreted as characters. AFAIK groovy tries to guess the encoding here by looking at the file content.
If you want a specific character encoding you can specify a charset name with
String fileContents = new File('/path/to/file').getText('UTF-8')
See API docs on File.getText(String)
for further reference.
I suspect something is not right when you are saving to the db. Do i understand your steps as:
got more code, especially when saving? where in your code are initializing and populating the bindinglist
There are a couple of ways.
One is to add
this.onToggleLoop = this.onToggleLoop.bind(this);
in the constructor.
Another is arrow functions
onToggleLoop = (event) => {...}
.
And then there is onClick={this.onToggleLoop.bind(this)}
.
Yes, there is a command to find the size of a database in Postgres. It's the following:
SELECT pg_database.datname as "database_name", pg_size_pretty(pg_database_size(pg_database.datname)) AS size_in_mb FROM pg_database ORDER by size_in_mb DESC;
Find Arabic chars and replace them with its UTF-8 encoding. some thing like this:
for (int i = 0; i < urlAsString.length(); i++) {
if (urlAsString.charAt(i) > 255) {
urlAsString = urlAsString.substring(0, i) + URLEncoder.encode(urlAsString.charAt(i)+"", "UTF-8") + urlAsString.substring(i+1);
}
}
encodedURL = urlAsString;
XSLT stylesheets must be well-formed XML. Since " "
is not one of the five predefined XML entities, it cannot be directly included in the stylesheet.
So coming back to your solution " "
is a perfect replacement of " "
you should use.
Example:
<xsl:value-of select="$txtFName"/> <xsl:value-of select="$txtLName"/>
Close, but not the same. They're getting the same element, but the jQuery version is wrapped in a jQuery object.
The equivalent would be this
var contents = $('#contents').get(0);
or this
var contents = $('#contents')[0];
These will pull the element out of the jQuery object.
Try out this package, Jiffy, it also runs on top of Intl, but makes it easier using momentjs syntax. See below
import 'package:jiffy/jiffy.dart';
var now = Jiffy().format("yyyy-MM-dd HH:mm:ss");
You can also do the following
var a = Jiffy().yMMMMd; // October 18, 2019
And you can also pass in your DateTime object, A string and an array
var a = Jiffy(DateTime(2019, 10, 18)).yMMMMd; // October 18, 2019
var a = Jiffy("2019-10-18").yMMMMd; // October 18, 2019
var a = Jiffy([2019, 10, 18]).yMMMMd; // October 18, 2019
list out the installed packages in the virtualenv
step 1:
workon envname
step 2:
pip freeze
it will display the all installed packages and installed packages and versions
1: The arguments to the callback functions are reversed.
.each()
's, $.each()
's, and .map()
's callback function take the index first, and then the element
function (index, element)
$.map()
's callback has the same arguments, but reversed
function (element, index)
2: .each()
, $.each()
, and .map()
do something special with this
each()
calls the function in such a way that this
points to the current element. In most cases, you don't even need the two arguments in the callback function.
function shout() { alert(this + '!') }
result = $.each(['lions', 'tigers', 'bears'], shout)
// result == ['lions', 'tigers', 'bears']
For $.map()
the this
variable refers to the global window object.
3: map()
does something special with the callback's return value
map()
calls the function on each element, and stores the result in a new array, which it returns. You usually only need to use the first argument in the callback function.
function shout(el) { return el + '!' }
result = $.map(['lions', 'tigers', 'bears'], shout)
// result == ['lions!', 'tigers!', 'bears!']
You should try this:
select TABNAME from syscat.tables where tabschema = 'yourschemaname'";
This snippet will handle more than two checkboxes in case you decide to expand the form.
$("input[type=text]").keyup(function(){
var count = 0, attr = "disabled", $sub = $("#submit"), $inputs = $("input[type=text]");
$inputs.each(function(){
count += ($.trim($(this).val())) ? 1:0;
});
(count >= $inputs.length ) ? $sub.removeAttr(attr):$sub.attr(attr,attr);
});
Working Example: http://jsfiddle.net/sr4gq/
Looks like problem is based on a server side.
Im my case I worked with paypal server and neither of suggested answers helped, but http://forums.iis.net/t/1217360.aspx?HTTP+403+Forbidden+error
I was facing this issue and just got the reply from Paypal technical. Add this will fix the 403 issue.
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.UserAgent = "[any words that is more than 5 characters]";
.groupby
on the 'method'
column, and create a dict
of DataFrames
with unique 'method'
values as the keys, with a dict-comprehension
.
.groupby
returns a groupby
object, that contains information about the groups, where g
is the unique value in 'method'
for each group, and d
is the DataFrame
for that group.value
of each key
in df_dict
, will be a DataFrame
, which can be accessed in the standard way, df_dict['key']
.list
of DataFrames
, which can be done with a list-comprehension
df_list = [d for _, d in df.groupby('method')]
import pandas as pd
import seaborn as sns # for test dataset
# load data for example
df = sns.load_dataset('planets')
# display(df.head())
method number orbital_period mass distance year
0 Radial Velocity 1 269.300 7.10 77.40 2006
1 Radial Velocity 1 874.774 2.21 56.95 2008
2 Radial Velocity 1 763.000 2.60 19.84 2011
3 Radial Velocity 1 326.030 19.40 110.62 2007
4 Radial Velocity 1 516.220 10.50 119.47 2009
# Using a dict-comprehension, the unique 'method' value will be the key
df_dict = {g: d for g, d in df.groupby('method')}
print(df_dict.keys())
[out]:
dict_keys(['Astrometry', 'Eclipse Timing Variations', 'Imaging', 'Microlensing', 'Orbital Brightness Modulation', 'Pulsar Timing', 'Pulsation Timing Variations', 'Radial Velocity', 'Transit', 'Transit Timing Variations'])
# or a specific name for the key, using enumerate (e.g. df1, df2, etc.)
df_dict = {f'df{i}': d for i, (g, d) in enumerate(df.groupby('method'))}
print(df_dict.keys())
[out]:
dict_keys(['df0', 'df1', 'df2', 'df3', 'df4', 'df5', 'df6', 'df7', 'df8', 'df9'])
df_dict['df1].head(3)
or df_dict['Astrometry'].head(3)
method number orbital_period mass distance year
113 Astrometry 1 246.36 NaN 20.77 2013
537 Astrometry 1 1016.00 NaN 14.98 2010
df_dict['df2].head(3)
or df_dict['Eclipse Timing Variations'].head(3)
method number orbital_period mass distance year
32 Eclipse Timing Variations 1 10220.0 6.05 NaN 2009
37 Eclipse Timing Variations 2 5767.0 NaN 130.72 2008
38 Eclipse Timing Variations 2 3321.0 NaN 130.72 2008
df_dict['df3].head(3)
or df_dict['Imaging'].head(3)
method number orbital_period mass distance year
29 Imaging 1 NaN NaN 45.52 2005
30 Imaging 1 NaN NaN 165.00 2007
31 Imaging 1 NaN NaN 140.00 2004
DataFrames
using pandas: Boolean Indexing.loc
is not required.DataFrames
.dict
, list
, generator
, etc.), as shown above.df1 = df[df.method == 'Astrometry']
df2 = df[df.method == 'Eclipse Timing Variations']
you can drop the Constraint which is restricting you. If the column has access to other table. suppose a view is accessing the column which you are altering then it wont let you alter the column unless you drop the view. and after making changes you can recreate the view.
Well, note that the request contains binary data, so I'm not posting the request as such - instead, I've converted every non-printable-ascii character into a dot (".").
POST /cgi-bin/qtest HTTP/1.1
Host: aram
User-Agent: Mozilla/5.0 Gecko/2009042316 Firefox/3.0.10
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://aram/~martind/banner.htm
Content-Type: multipart/form-data; boundary=2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Length: 514
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile1"; filename="r.gif"
Content-Type: image/gif
GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile2"; filename="g.gif"
Content-Type: image/gif
GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile3"; filename="b.gif"
Content-Type: image/gif
GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f--
Note that every line (including the last one) is terminated by a \r\n sequence.
For me on windows it was Ctrl+¡
, indent line. It adds a tab at the beggining of each line.
Just another approach
function parseTimestamp(timestampStr) {_x000D_
return new Date(new Date(timestampStr).getTime() + (new Date(timestampStr).getTimezoneOffset() * 60 * 1000));_x000D_
};_x000D_
_x000D_
//Sun Jan 01 2017 12:00:00_x000D_
var timestamp = 1483272000000;_x000D_
date = parseTimestamp(timestamp);_x000D_
document.write(date);
_x000D_
Cheers!
I would use XMLHTTP request to retrieve page content as much faster. Then it is easy enough to use querySelectorAll to apply a CSS class selector to grab by class name. Then you access the child elements by tag name and index.
Option Explicit
Public Sub GetInfo()
Dim sResponse As String, html As HTMLDocument, elements As Object, i As Long
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", "https://www.hsbc.com/about-hsbc/leadership", False
.setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"
.send
sResponse = StrConv(.responseBody, vbUnicode)
End With
Set html = New HTMLDocument
With html
.body.innerHTML = sResponse
Set elements = .querySelectorAll(".profile-col1")
For i = 0 To elements.Length - 1
Debug.Print String(20, Chr$(61))
Debug.Print elements.item(i).getElementsByTagName("a")(0).innerText
Debug.Print elements.item(i).getElementsByTagName("p")(0).innerText
Debug.Print elements.item(i).getElementsByTagName("p")(1).innerText
Next
End With
End Sub
References:
VBE > Tools > References > Microsoft HTML Object Library
You appear to have a heredoc
containing a single SQL*Plus command, though it doesn't look right as noted in the comments. You can either pass a value in the heredoc
:
sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql BUILDING
exit;
EOF
or if BUILDING
is $2
in your script:
sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql $2
exit;
EOF
If your file.sql
had an exit
at the end then it would be even simpler as you wouldn't need the heredoc
:
sqlplus -S user/pass@localhost @/opt/D2RQ/file.sql $2
In your SQL you can then refer to the position parameters using substitution variables:
...
}',SEM_Models('&1'),NULL,
...
The &1
will be replaced with the first value passed to the SQL script, BUILDING
; because that is a string it still needs to be enclosed in quotes. You might want to set verify off
to stop if showing you the substitutions in the output.
You can pass multiple values, and refer to them sequentially just as you would positional parameters in a shell script - the first passed parameter is &1
, the second is &2
, etc. You can use substitution variables anywhere in the SQL script, so they can be used as column aliases with no problem - you just have to be careful adding an extra parameter that you either add it to the end of the list (which makes the numbering out of order in the script, potentially) or adjust everything to match:
sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count BUILDING
exit;
EOF
or:
sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count $2
exit;
EOF
If total_count
is being passed to your shell script then just use its positional parameter, $4
or whatever. And your SQL would then be:
SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
?s rdf:type :ProcessSpec .
?s ?p ?o
}',SEM_Models('&2'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));
If you pass a lot of values you may find it clearer to use the positional parameters to define named parameters, so any ordering issues are all dealt with at the start of the script, where they are easier to maintain:
define MY_ALIAS = &1
define MY_MODEL = &2
SELECT COUNT(*) as &MY_ALIAS
FROM TABLE(SEM_MATCH(
'{
?s rdf:type :ProcessSpec .
?s ?p ?o
}',SEM_Models('&MY_MODEL'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));
From your separate question, maybe you just wanted:
SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
?s rdf:type :ProcessSpec .
?s ?p ?o
}',SEM_Models('&1'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));
... so the alias will be the same value you're querying on (the value in $2
, or BUILDING
in the original part of the answer). You can refer to a substitution variable as many times as you want.
That might not be easy to use if you're running it multiple times, as it will appear as a header above the count value in each bit of output. Maybe this would be more parsable later:
select '&1' as QUERIED_VALUE, COUNT(*) as TOTAL_COUNT
If you set pages 0
and set heading off
, your repeated calls might appear in a neat list. You might also need to set tab off
and possibly use rpad('&1', 20)
or similar to make that column always the same width. Or get the results as CSV with:
select '&1' ||','|| COUNT(*)
Depends what you're using the results for...
I couldn't get it to work with a hardware device. I kept getting the same error, but...
For your emulator you have to choose the IntelX86 Atom System image. Then ADB will connect to your emulator and it will properly install the installDebug.apk.
This is what I had to do.
Also look at this tutorial. It helped me immensely.
This font is not standard on all devices. It is installed by default on some Macs, but rarely on PCs and mobile devices.
To use this font on all devices, use a @font-face declaration in your CSS to link to it on your domain if you wish to use it.
@font-face { font-family: Delicious; src: url('Delicious-Roman.otf'); }
@font-face { font-family: Delicious; font-weight: bold; src: url('Delicious-Bold.otf'); }
Taken from css3.info
Check it with a regex.
Javascript regexen don't have POSIX character classes, so you have to write character ranges manually:
if (!input_string.match(/^[0-9a-z]+$/))
show_error_or_something()
Here ^
means beginning of string and $
means end of string, and [0-9a-z]+
means one or more of character from 0
to 9
OR from a
to z
.
More information on Javascript regexen here: https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions
This may be what you are looking for:
for ($i=1; $i -le $ActiveCampaigns; $i++)
{
$PQCampaign = Get-Variable -Name "PQCampaign$i" -ValueOnly
$PQCampaignPath = Get-Variable -Name "PQCampaignPath$i" -ValueOnly
# Do stuff with $PQCampaign and $PQCampaignPath
}
A commenter asked "why use a third-party library for this?" The answer is that it's way too much of a pain to do it yourself. Here's an example of how to properly do the inverse operation of reading a byte array from a file (sorry, this is just the code I had readily available, and it's not like I want the asker to actually paste and use this code anyway):
public static byte[] toByteArray(File file) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
boolean threw = true;
InputStream in = new FileInputStream(file);
try {
byte[] buf = new byte[BUF_SIZE];
long total = 0;
while (true) {
int r = in.read(buf);
if (r == -1) {
break;
}
out.write(buf, 0, r);
}
threw = false;
} finally {
try {
in.close();
} catch (IOException e) {
if (threw) {
log.warn("IOException thrown while closing", e);
} else {
throw e;
}
}
}
return out.toByteArray();
}
Everyone ought to be thoroughly appalled by what a pain that is.
Use Good Libraries. I, unsurprisingly, recommend Guava's Files.write(byte[], File).
The code I use for all browser gradients:
background: #0A284B;
background: -webkit-gradient(linear, left top, left bottom, from(#0A284B), to(#135887));
background: -webkit-linear-gradient(#0A284B, #135887);
background: -moz-linear-gradient(top, #0A284B, #135887);
background: -ms-linear-gradient(#0A284B, #135887);
background: -o-linear-gradient(#0A284B, #135887);
background: linear-gradient(#0A284B, #135887);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#0A284B', endColorstr='#135887');
zoom: 1;
You will need to specify a height or zoom: 1
to apply hasLayout
to the element for this to work in IE.
Update:
Here is a LESS Mixin (CSS) version for all you LESS users out there:
.gradient(@start, @end) {
background: mix(@start, @end, 50%);
filter: ~"progid:DXImageTransform.Microsoft.gradient(startColorStr="@start~", EndColorStr="@end~")";
background: -webkit-gradient(linear, left top, left bottom, from(@start), to(@end));
background: -webkit-linear-gradient(@start, @end);
background: -moz-linear-gradient(top, @start, @end);
background: -ms-linear-gradient(@start, @end);
background: -o-linear-gradient(@start, @end);
background: linear-gradient(@start, @end);
zoom: 1;
}
I solved using as credential built-in accounts as the NetworkService this article point me out in the right direction http://www.sqlcoffee.com/SQLServer2008_0013.htm
I was trying to wrap my Docker commands in gulp tasks and realised that you can do the following:
docker stop container-name
docker rm container-name
This might not work for scenarios where you have multiple containers with the same name (if that's possible), but for my use case it was perfect.
Immutable simply mean unchangeable or unmodifiable. Once string object is created its data or state can't be changed
Consider bellow example,
class Testimmutablestring{
public static void main(String args[]){
String s="Future";
s.concat(" World");//concat() method appends the string at the end
System.out.println(s);//will print Future because strings are immutable objects
}
}
Let's get idea considering bellow diagram,
In this diagram, you can see new object created as "Future World". But not change "Future".Because String is immutable
. s
, still refer to "Future". If you need to call "Future World",
String s="Future";
s=s.concat(" World");
System.out.println(s);//print Future World
Why are string objects immutable in java?
Because Java uses the concept of string literal. Suppose there are 5 reference variables, all refers to one object "Future".If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java.
The corrected code is
import urllib.request
fhand = urllib.request.urlopen('http://data.pr4e.org/romeo.txt')
counts = dict()
for line in fhand:
words = line.decode().split()
for word in words:
counts[word] = counts.get(word, 0) + 1
print(counts)
running the code above produces
{'Who': 1, 'is': 1, 'already': 1, 'sick': 1, 'and': 1, 'pale': 1, 'with': 1, 'grief': 1}
Because you wanted to install specific package "I need to install only 1 package for my SF2 distribution (DoctrineFixtures)."
php composer.phar require package/package-name:package-version
would be enough
You can input variables via switch -e
$ gnuplot -e "filename='foo.data'" foo.plg
In foo.plg you can then use that variable
$ cat foo.plg
plot filename
pause -1
To make "foo.plg" a bit more generic, use a conditional:
if (!exists("filename")) filename='default.dat'
plot filename
pause -1
Note that -e
has to precede the filename otherwise the file runs before the -e
statements. In particular, running a shebang gnuplot #!/usr/bin/env gnuplot
with ./foo.plg -e ...
CLI arguments will ignore use the arguments provided.
Tools are just tools.
They help or they don't.
You need help or you don't.
If you know Unix and those tools do what you need them to do on Windows - then you are a happy guy and there is no need to learn PowerShell (unless you want to explore).
My original intent was to include a set of Unix tools in Windows and be done with it (a number of us on the team have deep Unix backgrounds and a healthy dose of respect for that community.)
What I found was that this didn't really help much. The reason for that is that AWK/grep/sed don't work against COM, WMI, ADSI, the Registry, the certificate store, etc., etc.
In other words, UNIX is an entire ecosystem self-tuned around text files. As such, text processing tools are effectively management tools. Windows is a completely different ecosystem self-tuned around APIs and Objects. That's why we invented PowerShell.
What I think you'll find is that there will be lots of occasions when text-processing won't get you what you want on Windows. At that point, you'll want to pick up PowerShell. NOTE - it is not an all or nothing deal. Within PowerShell, you can call out to your Unix tools (and use their text process or PowerShell's text processing). Also you can call PowerShell from your Unix tools and get text.
Again - there is no religion here - our focus is on giving you the tools you need to succeed. That is why we are so passionate about feedback. Let us know where we are falling down on the job or where you don't have a tool you need and we'll put it on the list and get to it.
In all honesty, we are digging ourselves out of a 30-year-hole, so it is going to take a while. That said, if you pick up the beta of Windows Server 2008 /R2 and/or the betas of our server products, I think you'll be shocked at how quickly that hole is getting filled.
With regard to usage - we've had > 3.5 million downloads to date. That does not include the people using it in Windows Server 2008, because it is included as an optional component and does not need a download.
V2 will ship in all versions of Windows. It will be on-by-default for all editions except Server core where it is an optional component. Shortly after Windows 7/Windows Server 2008 R2 ships, we'll make V2 available on all platforms, Windows XP and above. In other words - your investment in learning will be applicable to a very large number of machines/environments.
One last comment. If/when you start to learn PowerShell, I think you'll be pretty happy. Much of the design is heavily influenced by our Unix backgrounds, so while we are quite different, you'll pick it up very quickly (after you get over cussing that it isn't Unix :-) ).
We know that people have a very limited budget for learning - that is why we are super hard-core about consistency. You are going to learn something, and then you'll use it over and over and over again.
Experiment! Enjoy! Engage!
Sometimes it takes longer to figure out the regex than to just write it out in python:
import string
s = "how much for the maple syrup? $20.99? That's ricidulous!!!"
for char in string.punctuation:
s = s.replace(char, ' ')
If you need other characters you can change it to use a white-list or extend your black-list.
Sample white-list:
whitelist = string.letters + string.digits + ' '
new_s = ''
for char in s:
if char in whitelist:
new_s += char
else:
new_s += ' '
Sample white-list using a generator-expression:
whitelist = string.letters + string.digits + ' '
new_s = ''.join(c for c in s if c in whitelist)
This is how you can do it from DB2 client.
Open the Command Editor and Run the select Query in the Commands Tab.
Open the corresponding Query Results Tab
Then from Menu --> Selected --> Export
I was seeing this error along with: "Error:compileSdkVersion android-21 requires compiling with JDK 7"
For me, the solution was found here, where I had to update the JDK location in the project structure.
You could have one abstract base class that implements both IFirst and ISecond, and then inherit from just that base.
You can build the Dockerfile from the parent directory:
docker build -t <some tag> -f <dir/dir/Dockerfile> .
@import url(https://fonts.googleapis.com/css?family=Roboto+Slab:400);_x000D_
_x000D_
body {_x000D_
background: #222;_x000D_
}_x000D_
_x000D_
h1 {_x000D_
display: table;_x000D_
margin: 0 auto;_x000D_
font-family: "Roboto Slab";_x000D_
font-weight: 600;_x000D_
font-size: 7em;_x000D_
background: linear-gradient(330deg, #e05252 0%, #99e052 25%, #52e0e0 50%, #9952e0 75%, #e05252 100%);_x000D_
-webkit-background-clip: text;_x000D_
-webkit-text-fill-color: transparent;_x000D_
line-height: 200px;_x000D_
}
_x000D_
<h1>beautiful</h1>
_x000D_
From Python's documentation:
import signal
import time
def handler(signum, frame):
print 'Here you go'
signal.signal(signal.SIGINT, handler)
time.sleep(10) # Press Ctrl+c here
Although the accepted answer is correct, it does not state why the original code failed to work.
Bad code from your question:
HttpCookie userid = new HttpCookie("userid", objUser.id.ToString());
userid.Expires.AddYears(1);
Response.Cookies.Add(userid);
Take a look at the second line. The basis for expiration is on the Expires property which contains the default of 1/1/0001. The above code is evaluating to 1/1/0002. Furthermore the evaluation is not being saved back to the property. Instead the Expires property should be set with the basis on the current date.
Corrected code:
HttpCookie userid = new HttpCookie("userid", objUser.id.ToString());
userid.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(userid);
Try:
SELECT DATE(`date_time_field`) AS date_part, TIME(`date_time_field`) AS time_part FROM `your_table`
To remove the commas, you'll need to use replace
on the string. To convert to a float so you can do the maths, you'll need parseFloat
:
var total = parseFloat('100,000.00'.replace(/,/g, '')) +
parseFloat('500,000.00'.replace(/,/g, ''));
There are 3 ways to do this:
Right-click on the Chart and click Select Data then edit the series names directly as shown below.
You can either specify the values directly e.g. Series 1
or specify a range e.g. =A2
Simply select your data range (in similar format as I specified) and create a simple bar chart. The labels should be defined automatically.
Similarly you can define the series names dynamically using VBA. A simple example below:
ActiveChart.ChartArea.Select
ActiveChart.FullSeriesCollection(1).Name = "=""Hello"""
This will redefine the first series name. Just change the index from (1)
to e.g. (2)
and so on to change the following series names. What does the VBA above do? It sets the series name to Hello
as "=""Hello"""
translates to ="Hello"
("
have to be escaped by a preceding "
).
The best way I've found to do this is with StrMethodFormatter
:
import matplotlib as mpl
ax.yaxis.set_major_formatter(mpl.ticker.StrMethodFormatter('{x:,.0f}'))
For example:
import pandas as pd
import requests
import matplotlib.pyplot as plt
import matplotlib as mpl
url = 'https://min-api.cryptocompare.com/data/histoday?fsym=BTC&tsym=USDT&aggregate=1'
df = pd.DataFrame({'BTC/USD': [d['close'] for d in requests.get(url).json()['Data']]})
ax = df.plot()
ax.yaxis.set_major_formatter(mpl.ticker.StrMethodFormatter('{x:,.0f}'))
plt.show()
You can also do it as a one-liner directly in your crontab:
* * * * * [ `ps -ef|grep -v grep|grep <command>` -eq 0 ] && <command>
You need to use cell.Text = "#N/A" instead of cell.Value = "#N/A". The error in the cell is actually just text stored in the cell.
In my case I'm doing it like this:
module SayHi {
export default () => { console.log("Hi"); }
}
new SayHi();
You have to look how this is called:
someObject.equals(someOtherObj);
This invokes the equals
method on the instance of someObject
. Now, inside that method:
public boolean equals(Object obj) { if (obj == this) { //is someObject equal to obj, which in this case is someOtherObj? return true;//If so, these are the same objects, and return true }
You can see that this
is referring to the instance of the object that equals is called on. Note that equals()
is non-static, and so must be called only on objects that have been instantiated.
Note that ==
is only checking to see if there is referential equality; that is, the reference of this
and obj
are pointing to the same place in memory. Such references are naturally equal:
Object a = new Object(); Object b = a; //sets the reference to b to point to the same place as a Object c = a; //same with c b.equals(c);//true, because everything is pointing to the same place
Further note that equals()
is generally used to also determine value equality. Thus, even if the object references are pointing to different places, it will check the internals to determine if those objects are the same:
FancyNumber a = new FancyNumber(2);//Internally, I set a field to 2 FancyNumber b = new FancyNumber(2);//Internally, I set a field to 2 a.equals(b);//true, because we define two FancyNumber objects to be equal if their internal field is set to the same thing.
This could also be an issue of building the code using a 64 bit
configuration. You can try to select x86
as the build platform which can solve this issue. To do this right-click the solution and select Configuration Manager
From there you can change the Platform
of the project using the 32-bit .dll to x86
PEP 8 advises the first form for readability. You can find it here.
Function names should be lowercase, with words separated by underscores as necessary to improve readability.
The idea is that the response body gives you a page that links you to the thing:
201 Created
The 201 (Created) status code indicates that the request has been fulfilled and has resulted in one or more new resources being created. The primary resource created by the request is identified by either a Location header field in the response or, if no Location field is received, by the effective request URI.
This means that you would include a Location
in the response header that gives the URL of where you can find the newly created thing:
HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/36373586/12597
They then go on to mention what you should include in the response body:
The 201 response payload typically describes and links to the resource(s) created.
For the human using the browser, you give them something they can look at, and click, to get to their newly created resource:
HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/36373586/12597
Content-Type: text/html
Your answer has been saved!
Click <A href="/a/36373586/12597">here</A> to view it.
If the page will only be used by a robot, the it makes sense to have the response be computer readable:
HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/36373586/12597
Content-Type: application/xml
<createdResources>
<questionID>1860645</questionID>
<answerID>36373586</answerID>
<primary>/a/36373586/12597</primary>
<additional>
<resource>http://stackoverflow.com/questions/1860645/create-request-with-post-which-response-codes-200-or-201-and-content/36373586#36373586</resource>
<resource>http://stackoverflow.com/a/1962757/12597</resource>
</additional>
</createdResource>
Or, if you prefer:
HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/36373586/12597
Content-Type: application/json
{
"questionID": 1860645,
"answerID": 36373586,
"primary": "/a/36373586/12597",
"additional": [
"http://stackoverflow.com/questions/1860645/create-request-with-post-which-response-codes-200-or-201-and-content/36373586#36373586",
"http://stackoverflow.com/a/36373586/12597"
]
}
The response is entirely up to you; it's arbitrarily what you'd like.
Finally there's the optimization that I can pre-cache the created resource (because I already have the content; I just uploaded it). The server can return a date or ETag which I can store with the content I just uploaded:
See Section 7.2 for a discussion of the meaning and purpose of validator header fields, such as ETag and Last-Modified, in a 201 response.
HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/23704283/12597
Content-Type: text/html
ETag: JF2CA53BOMQGU5LTOQQGC3RAMV4GC3LQNRSS4
Last-Modified: Sat, 02 Apr 2016 12:22:39 GMT
Your answer has been saved!
Click <A href="/a/36373586/12597">here</A> to view it.
And ETag
s are purely arbitrary values. Having them be different when a resource changes (and caches need to be updated) is all that matters. The ETag is usually a hash (e.g. SHA2). But it can be a database rowversion
, or an incrementing revision number. Anything that will change when the thing changes.
Since your object type is custom, I would tend to agree with your solution - break it down into smaller segments using an encoding method (like JSON or serializing the content), and on the other end have corresponding code to re-construct the object.
This is what you need in 1 line of code.
Route::get('/groups/{groupId}', 'GroupsController@getShow');
Suggestion: Use CamelCase as opposed to underscores, try & follow PSR-* guidelines.
Hope it helps.
I solved this by getting the Bluetooth name, but not from the BluetoothAdapter
(that needs Bluetooth permission).
Here's the code:
Settings.Secure.getString(getContentResolver(), "bluetooth_name");
No extra permissions needed.
If your base query is expected to return only one row, then you could use this trick:
select NVL( MIN(rate), 0 ) AS rate
from d_payment_index
where fy = 2007
and payment_year = 2008
and program_id = 18
(Oracle code, not sure if NVL is the right function for SQL Server.)
Array.join
is what you need, but if you like, the friendly people at phpjs.org have created implode
for you.
Then some slightly off topic ranting. As @jon_darkstar alreadt pointed out, jQuery is JavaScript and not vice versa. You don't need to know JavaScript to be able to understand how to use jQuery, but it certainly doesn't hurt and once you begin to appreciate reusability or start looking at the bigger picture you absolutely need to learn it.
The simplest way:
string input = null;
Color color = Color.White;
TextBoxText_Changed(object sender, EventsArgs e)
{
input = TextBox.Text;
}
Button_Click(object sender, EventsArgs e)
{
color = Color.FromName(input)
}
Looks like the invisible character -
ALT+255
Try this
select REPLACE(ProductAlternateKey, ' ', '@')
--type ALT+255 instead of space for the second expression in REPLACE
from DimProducts
where ProductAlternateKey like '46783815%'
Raj
Edit: Based on ASCII() results, try ALT+10
- use numeric keypad
The fastest emulators at the moment of writing this are the built-in x86 emulators which come with the Android SDK. You can find them in AVD manager where you create virtual machines. Simply pick any of them and then you pick the type of CPU (choose x86 for best performance). It will be as fast as your machine.
The latest such machine for Android 4.0 and 4.0.3 can be found in Giving your Android Emulator a Boost: Building Android ICS with Goldfish & x86 KVM support on EC2 - TestObject.
Note: This is only for a development purpose. To test for performance, you still have to either use a real device or test on the emulator with ARM CPU.
def trim(x):
if x.dtype == object:
x = x.str.split(' ').str[0]
return(x)
df = df.apply(trim)
Updated version of @Alaaedeen's answer. You can specify any part of the version of any package you want to install. This may cause other package versions to change. For example, if you don't care about which specific version of PyQt4 you want, do:
conda install pyqt=4
This would install the latest minor version and release of PyQt 4. You can specify any portion of the version that you want, not just the major number. So, for example
conda install pyqt=4.11
would install the latest (or last) release of version 4.11.
Keep in mind that installing a different version of a package may cause the other packages that depend on it to be rolled forward or back to where they support the version you want.
std::iota is limited to a sequence n, n+1, n+2, ...
But what if you want to fill an array with a generic sequence f(0), f(1), f(2), etc.? Often, we can avoid a state tracking generator. For example,
int a[7];
auto f = [](int x) { return x*x; };
transform(a, a+7, a, [a, f](int &x) {return f(&x - a);});
will produce the sequence of squares
0 1 4 9 16 25 36
However, this trick will not work with other containers.
If you're stuck with C++98, you can do horrible things like:
int f(int &x) { int y = (int) (long) &x / sizeof(int); return y*y; }
and then
int a[7];
transform((int *) 0, ((int *) 0) + 7, a, f);
But I would not recommend it. :)
Use the SimpleDateFormat
class parse()
method. This method will return a Date
object. You can then create a Calendar
object for this Date
and add 2 hours to it.
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = formatter.parse(theDateToParse);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR_OF_DAY, 2);
cal.getTime(); // This will give you the time you want.
With docker-compose try docker-compose up -d --build --force-recreate
Try this ...
PropertyInfo isreadonly =typeof(System.Collections.Specialized.NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
isreadonly.SetValue(this.Request.QueryString, false, null);
this.Request.QueryString.Remove("foo");
Use the GetType() method
http://msdn.microsoft.com/en-us/library/system.object.gettype.aspx
Another way to do this is (using Apache Commons
FileUtils
) -
private void printEmptyFileName(final File file) throws IOException {
if (FileUtils.readFileToString(file).trim().isEmpty()) {
System.out.println("File is empty: " + file.getName());
}
}
You need to git add my_project
to stage your new folder. Then git add my_project/*
to stage its contents. Then commit what you've staged using git commit
and finally push your changes back to the source using git push origin master
(I'm assuming you wish to push to the master branch).
Make sure that Spring version and xsd version both are same.In my case I am using Spring 4.1.1 so my all xsd should be version *-4.1.xsd
a = if true then 5 else 10
a = if false then 5 else 10
See documentation.
You can use JsonConvert from Newtonsoft library. To serialize an object and write to a file in json format:
File.WriteAllText(filePath, JsonConvert.SerializeObject(obj));
And to deserialize it back into object:
var obj = JsonConvert.DeserializeObject<ObjType>(File.ReadAllText(filePath));
To start redis with a config file all you need to do is specifiy the config file as an argument:
redis-server /root/config/redis.rb
Instead of using and killing PID's I would suggest creating an init script for your service
I would suggest taking a look at the Installing Redis more properly section of http://redis.io/topics/quickstart. It will walk you through setting up an init script with redis so you can just do something like service redis_server start
and service redis_server stop
to control your server.
I am not sure exactly what distro you are using, that article describes instructions for a Debian based distro. If you are are using a RHEL/Fedora distro let me know, I can provide you with instructions for the last couple of steps, the config file and most of the other steps will be the same.
This works for me https://www.nuget.org/packages/ASquare.WindowsTaskScheduler/
It is nicely designed Fluent API.
//This will create Daily trigger to run every 10 minutes for a duration of 18 hours
SchedulerResponse response = WindowTaskScheduler
.Configure()
.CreateTask("TaskName", "C:\\Test.bat")
.RunDaily()
.RunEveryXMinutes(10)
.RunDurationFor(new TimeSpan(18, 0, 0))
.SetStartDate(new DateTime(2015, 8, 8))
.SetStartTime(new TimeSpan(8, 0, 0))
.Execute();
Here's an even faster approach:
// strpos is faster than an unnecessary substr() and is built just for that
if (strpos($str, $prefix) === 0) $str = substr($str, strlen($prefix));
In getUserById
you shouldn't create a new object (user1) which isn't used. Just assign it to the already (but null) initialized user
. Otherwise Hibernate.initialize(user);
is actually Hibernate.initialize(null);
Here's the new getUserById
(I haven't tested this ;)):
public User getUserById(Long user_id) {
Session session = null;
Object user = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
user = (User)session.load(User.class, user_id);
Hibernate.initialize(user);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (session != null && session.isOpen()) {
session.close();
}
}
return user;
}
In class WeatherRecord
:
First import the class if they are in different package else this statement is not requires
Import <path>.ClassName
Then, just referene or call your object like:
Date d;
TempratureRange tr;
d = new Date();
tr = new TempratureRange;
//this can be done in Single Line also like :
// Date d = new Date();
But in your code you are not required to create an object to call function of Date and TempratureRange. As both of the Classes contain Static Function , you cannot call the thoes function by creating object.
Date.date(date,month,year); // this is enough to call those static function
Have clear concept on Object and Static functions. Click me
I recently wrote a module called keysight that translates keypress
, keydown
, and keyup
events into characters and keys respectively.
Example:
element.addEventListener("keydown", function(event) {
var character = keysight(event).char
})
Hey there's a useful tutorial on Dot Net pearls: http://www.dotnetperls.com/progressbar
In agreement with Peter, you need to use some amount of threading or the program will just hang, somewhat defeating the purpose.
Example that uses ProgressBar and BackgroundWorker: C#
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, System.EventArgs e)
{
// Start the BackgroundWorker.
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 1; i <= 100; i++)
{
// Wait 100 milliseconds.
Thread.Sleep(100);
// Report progress.
backgroundWorker1.ReportProgress(i);
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// Change the value of the ProgressBar to the BackgroundWorker progress.
progressBar1.Value = e.ProgressPercentage;
// Set the text.
this.Text = e.ProgressPercentage.ToString();
}
}
} //closing here
This can happen due to a different language in the phone for which your code doesn't have the asset for. For example your preference.xml is placed in xml-en and you are trying to run your app in a phone which has French selected, the app will crash.
If anyone cares I found this post initially, but I use ASP.NET's build in Validation on the page. The solutions work, but disable the button even if its been validated. You can use this following code in order to make it so it only disables the button if it passes page validation.
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Submit" OnClientClick=" if ( Page_ClientValidate() ) { this.value='Submitting..'; this.disabled=true; }" UseSubmitBehavior="false" />
If you want the #header
to be the same width as your container, with 10px of padding, you can leave out its width declaration. That will cause it to implicitly take up its entire parent's width (since a div is by default a block level element).
Then, since you haven't defined a width on it, the 10px of padding will be properly applied inside the element, rather than adding to its width:
#container {
position: relative;
width: 80%;
}
#header {
position: relative;
height: 50px;
padding: 10px;
}
You can see it in action here.
The key when using percentage widths and pixel padding/margins is not to define them on the same element (if you want to accurately control the size). Apply the percentage width to the parent and then the pixel padding/margin to a display: block
child with no width set.
Update
Another option for dealing with this is to use the box-sizing CSS rule:
#container {
-webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
-moz-box-sizing: border-box; /* Firefox, other Gecko */
box-sizing: border-box; /* Opera/IE 8+ */
/* Since this element now uses border-box sizing, the 10px of horizontal
padding will be drawn inside the 80% width */
width: 80%;
padding: 0 10px;
}
Here's a post talking about how box-sizing works.
You need the WHERE clause to replace ONLY the records that complies with the condition in the WHERE clause (as opposed to all records). You use % sign to indicate partial string: I.E.
LIKE ('...//domain1.com/images/%');
means all records that BEGIN with "...//domain1.com/images/"
and have anything AFTER (that's the %
for...)
Another example:
LIKE ('%http://domain1.com/images/%')
which means all records that contains "http://domain1.com/images/"
in any part of the string...
My favorite function for entropy is the following:
def entropy(labels):
prob_dict = {x:labels.count(x)/len(labels) for x in labels}
probs = np.array(list(prob_dict.values()))
return - probs.dot(np.log2(probs))
I am still looking for a nicer way to avoid the dict -> values -> list -> np.array conversion. Will comment again if I found it.
When you want to differ between a superClass and the inheritedClass you can use:
if([myTestClass class] == [myInheritedClass class]){
NSLog(@"I'm the inheritedClass);
}
if([myTestClass class] == [mySuperClass class]){
NSLog(@"I'm the superClass);
}
Using - (BOOL)isKindOfClass:(Class)aClass
in this case would result in TRUE both times because the inheritedClass is also a kind of the superClass.
When you add an object to $stateProvider.state
that object is then passed with the state. So you can add additional properties which you can read later on when needed.
Example route configuration
$stateProvider
.state('public', {
abstract: true,
module: 'public'
})
.state('public.login', {
url: '/login',
module: 'public'
})
.state('tool', {
abstract: true,
module: 'private'
})
.state('tool.suggestions', {
url: '/suggestions',
module: 'private'
});
The $stateChangeStart
event gives you acces to the toState
and fromState
objects. These state objects will contain the configuration properties.
Example check for the custom module property
$rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
if (toState.module === 'private' && !$cookies.Session) {
// If logged out and transitioning to a logged in page:
e.preventDefault();
$state.go('public.login');
} else if (toState.module === 'public' && $cookies.Session) {
// If logged in and transitioning to a logged out page:
e.preventDefault();
$state.go('tool.suggestions');
};
});
I didn't change the logic of the cookies because I think that is out of scope for your question.
You can create a Helper to get you this to work more modular.
Value publicStates
myApp.value('publicStates', function(){
return {
module: 'public',
routes: [{
name: 'login',
config: {
url: '/login'
}
}]
};
});
Value privateStates
myApp.value('privateStates', function(){
return {
module: 'private',
routes: [{
name: 'suggestions',
config: {
url: '/suggestions'
}
}]
};
});
The Helper
myApp.provider('stateshelperConfig', function () {
this.config = {
// These are the properties we need to set
// $stateProvider: undefined
process: function (stateConfigs){
var module = stateConfigs.module;
$stateProvider = this.$stateProvider;
$stateProvider.state(module, {
abstract: true,
module: module
});
angular.forEach(stateConfigs, function (route){
route.config.module = module;
$stateProvider.state(module + route.name, route.config);
});
}
};
this.$get = function () {
return {
config: this.config
};
};
});
Now you can use the helper to add the state configuration to your state configuration.
myApp.config(['$stateProvider', '$urlRouterProvider',
'stateshelperConfigProvider', 'publicStates', 'privateStates',
function ($stateProvider, $urlRouterProvider, helper, publicStates, privateStates) {
helper.config.$stateProvider = $stateProvider;
helper.process(publicStates);
helper.process(privateStates);
}]);
This way you can abstract the repeated code, and come up with a more modular solution.
Note: the code above isn't tested
<form class="form-inline">
<div class="form-group">
<label class="sr-only" for="exampleInputEmail3">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail3" placeholder="Email">
</div>
<button type="submit" class="btn btn-default">Sign in</button>
</form>
Thanks acdcjunior for your solution. Here's a little optimized version for formatting and parsing :
public static final SimpleDateFormat XML_SDF = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.FRANCE)
{
private static final long serialVersionUID = -8275126788734707527L;
public StringBuffer format(Date date, StringBuffer toAppendTo, java.text.FieldPosition pos)
{
final StringBuffer buf = super.format(date, toAppendTo, pos);
buf.insert(buf.length() - 2, ':');
return buf;
};
public Date parse(String source) throws java.text.ParseException {
final int split = source.length() - 2;
return super.parse(source.substring(0, split - 1) + source.substring(split)); // replace ":" du TimeZone
};
};
This is worked for me successfully.
"C:\Program Files\Java\jdk1.6.0_26\bin\keytool.exe" -exportcert -alias sociallisting -keystore "D:\keystore\SocialListing" | "C:\cygwin\bin\openssl.exe" sha1 -binary | "C:\cygwin\bin\openssl.exe" base64
Be careful with below path :
If command successfully work then you will see this command :
Enter keystore password : typeyourpassword
Encryptedhashkey**
If the table is already created in the database, then you can add a unique constraint later on by using this SQL query:
ALTER TABLE dbo.User
ADD CONSTRAINT ucCodes UNIQUE (fcode, scode, dcode)
msg * message goes here
That method is very simple and easy and should work in any batch file i believe. The only "downside" to this method is that it can only show 1 message at once, if there is more than one message it will show each one after the other depending on the order you put them inside the code. Also make sure there is a different looping or continuous operator in your batch file or it will close automatically and only this message will appear. If you need a "quiet" background looping opperator, heres one:
pause >nul
That should keep it running but then it will close after a button is pressed.
Also to keep all the commands "quiet" when running, so they just run and dont display that they were typed into the file, just put the following line at the beginning of the batch file:
@echo off
I hope all these tips helped!
You simply add another @font-face
rule:
@font-face {
font-family: CustomFont;
src: url('CustomFont.ttf');
}
@font-face {
font-family: CustomFont2;
src: url('CustomFont2.ttf');
}
If your second font still doesn't work, make sure you're spelling its typeface name and its file name correctly, your browser caches are behaving, your OS isn't messing around with a font of the same name, etc.
one cannot use the Context
of the Service
; was able to get the (package) Context
alike:
Intent intent = new Intent(getApplicationContext(), SomeActivity.class);
For those who don't use jQuery, below is my vanilla JavaScript function to create a form data object that can be accessed like any common object, unlike new FormData(form)
.
var oFormData = {_x000D_
'username': 'Minnie',_x000D_
'phone': '88889999',_x000D_
'avatar': '',_x000D_
'gender': 'F',_x000D_
'private': 1,_x000D_
'friends': ['Dick', 'Harry'],_x000D_
'theme': 'dark',_x000D_
'bio': 'A friendly cartoon mouse.'_x000D_
};_x000D_
_x000D_
function isObject(arg) {_x000D_
return Object.prototype.toString.call(arg)==='[object Object]';_x000D_
}_x000D_
_x000D_
function formDataToObject(elForm) {_x000D_
if (!elForm instanceof Element) return;_x000D_
var fields = elForm.querySelectorAll('input, select, textarea'),_x000D_
o = {};_x000D_
for (var i=0, imax=fields.length; i<imax; ++i) {_x000D_
var field = fields[i],_x000D_
sKey = field.name || field.id;_x000D_
if (field.type==='button' || field.type==='image' || field.type==='submit' || !sKey) continue;_x000D_
switch (field.type) {_x000D_
case 'checkbox':_x000D_
o[sKey] = +field.checked;_x000D_
break;_x000D_
case 'radio':_x000D_
if (o[sKey]===undefined) o[sKey] = '';_x000D_
if (field.checked) o[sKey] = field.value;_x000D_
break;_x000D_
case 'select-multiple':_x000D_
var a = [];_x000D_
for (var j=0, jmax=field.options.length; j<jmax; ++j) {_x000D_
if (field.options[j].selected) a.push(field.options[j].value);_x000D_
}_x000D_
o[sKey] = a;_x000D_
break;_x000D_
default:_x000D_
o[sKey] = field.value;_x000D_
}_x000D_
}_x000D_
alert('Form data:\n\n' + JSON.stringify(o, null, 2));_x000D_
return o;_x000D_
}_x000D_
_x000D_
function populateForm(o) {_x000D_
if (!isObject(o)) return;_x000D_
for (var i in o) {_x000D_
var el = document.getElementById(i) || document.querySelector('[name=' + i + ']');_x000D_
if (el.type==='radio') el = document.querySelectorAll('[name=' + i + ']');_x000D_
switch (typeof o[i]) {_x000D_
case 'number':_x000D_
el.checked = o[i];_x000D_
break;_x000D_
case 'object':_x000D_
if (el.options && o[i] instanceof Array) {_x000D_
for (var j=0, jmax=el.options.length; j<jmax; ++j) {_x000D_
if (o[i].indexOf(el.options[j].value)>-1) el.options[j].selected = true;_x000D_
}_x000D_
}_x000D_
break;_x000D_
default:_x000D_
if (el instanceof NodeList) {_x000D_
for (var j=0, jmax=el.length; j<jmax; ++j) {_x000D_
if (el[j].value===o[i]) el[j].checked = true;_x000D_
}_x000D_
} else {_x000D_
el.value = o[i];_x000D_
}_x000D_
}_x000D_
}_x000D_
}
_x000D_
form {_x000D_
border: 1px solid #000;_x000D_
}_x000D_
_x000D_
tr {_x000D_
vertical-align: top;_x000D_
}
_x000D_
<form id="profile" action="formdata.html" method="get">_x000D_
<table>_x000D_
<tr>_x000D_
<td><label for="username">Username:</label></td>_x000D_
<td><input type="text" id="username" name="username" value="Tom"></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td><label for="phone">Phone:</label></td>_x000D_
<td><input type="number" id="phone" name="phone" value="7672676"></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td><label for="avatar">Avatar:</label></td>_x000D_
<td><input type="file" id="avatar" name="avatar"></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td><label>Gender:</label></td>_x000D_
<td>_x000D_
<input type="radio" id="gender-m" name="gender" value="M"> <label for="gender-m">Male</label><br>_x000D_
<input type="radio" id="gender-f" name="gender" value="F"> <label for="gender-f">Female</label>_x000D_
</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td><label for="private">Private:</label></td>_x000D_
<td><input type="checkbox" id="private" name="private"></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td><label for="friends">Friends:</label></td>_x000D_
<td>_x000D_
<select id="friends" name="friends" size="2" multiple>_x000D_
<option>Dick</option>_x000D_
<option>Harry</option>_x000D_
</select>_x000D_
</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td><label for="theme">Theme:</label></td>_x000D_
<td>_x000D_
<select id="theme" name="theme">_x000D_
<option value="">-- Select --</option>_x000D_
<option value="dark">Dark</option>_x000D_
<option value="light">Light</option>_x000D_
</select>_x000D_
</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td><label for="bio">Bio:</label></td>_x000D_
<td><textarea id="bio" name="bio"></textarea></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td colspan="2">_x000D_
<input type="submit" value="Submit">_x000D_
<button>Cancel</button>_x000D_
</td>_x000D_
</tr>_x000D_
</table>_x000D_
</form>_x000D_
<p>_x000D_
<button onclick="formDataToObject(document.getElementById('profile'))"><strong>Convert to Object</strong></button>_x000D_
<button onclick="populateForm(oFormData)"><strong>Populate Form</strong></button>_x000D_
</p>
_x000D_
You can also play around with it in this pen: http://codepen.io/thdoan/pen/EyawvR
UPDATE: I also added a function to populate the form with the object returned by formDataToObject()
.
So much for this simple question, but I just wanted to highlight a new feature in Java which will avoid all confusions around indexing in arrays even for beginners. Java-8 has abstracted the task of iterating for you.
int[] array = new int[5];
//If you need just the items
Arrays.stream(array).forEach(item -> { println(item); });
//If you need the index as well
IntStream.range(0, array.length).forEach(index -> { println(array[index]); })
What's the benefit? Well, one thing is the readability like English. Second, you need not worry about the ArrayIndexOutOfBoundsException
You can do that with a single statement and a subquery in nearly all relational databases.
INSERT INTO targetTable(field1)
SELECT field1
FROM myTable
WHERE NOT(field1 IN (SELECT field1 FROM targetTable))
Certain relational databases have improved syntax for the above, since what you describe is a fairly common task. SQL Server has a MERGE
syntax with all kinds of options, and MySQL has optional INSERT OR IGNORE
syntax.
Edit: SmallSQL's documentation is fairly sparse as to which parts of the SQL standard it implements. It may not implement subqueries, and as such you may be unable to follow the advice above, or anywhere else, if you need to stick with SmallSQL.
As pointed out in Manto's answer, .utcOffset()
is the preferred method as of Moment 2.9.0. This function uses the real offset from UTC, not the reverse offset (e.g., -240 for New York during DST). Offset strings like "+0400" work the same as before:
// always "2013-05-23 00:55"
moment(1369266934311).utcOffset(60).format('YYYY-MM-DD HH:mm')
moment(1369266934311).utcOffset('+0100').format('YYYY-MM-DD HH:mm')
The older .zone()
as a setter was deprecated in Moment.js 2.9.0. It accepted a string containing a timezone identifier (e.g., "-0400" or "-04:00" for -4 hours) or a number representing minutes behind UTC (e.g., 240 for New York during DST).
// always "2013-05-23 00:55"
moment(1369266934311).zone(-60).format('YYYY-MM-DD HH:mm')
moment(1369266934311).zone('+0100').format('YYYY-MM-DD HH:mm')
To work with named timezones instead of numeric offsets, include Moment Timezone and use .tz()
instead:
// determines the correct offset for America/Phoenix at the given moment
// always "2013-05-22 16:55"
moment(1369266934311).tz('America/Phoenix').format('YYYY-MM-DD HH:mm')
or make a start.bat file:
Good luck!
This standard library solution likely has not been mentioned because the question is so dated. While these answers may scale to the other use cases beyond currency where differing levels of decimals are required, it seems you need it for currency.
I recommend you use the standard library locale.currency
object. It seems to have been created to address this problem of currency representation.
import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
locale.currency(1.23)
>>>'$1.23'
locale.currency(1.53251)
>>>'$1.23'
locale.currency(1)
>>>'$1.00'
locale.currency(mealPrice)
Currency generalizes to other countries as well.
If you are using it with Hibernate, you'll have to explicitly define the annotation CascadeType.DELETE_ORPHAN
, which can be used in conjunction with JPA CascadeType.ALL
.
If you don't plan to use Hibernate, you'll have to explicitly first delete the child elements and then delete the main record to avoid any orphan records.
execution sequence
With JPA 2.0, you can now use the option orphanRemoval = true
@OneToMany(mappedBy="foo", orphanRemoval=true)
Sorry I didn't see your Java tag, was reading question only. I'll leave my other answers here anyway since I've typed them out.
Java
String myString = "9Hello World!";
if ( Character.isDigit(myString.charAt(0)) )
{
System.out.println("String begins with a digit");
}
C++:
string myString = "2Hello World!";
if (isdigit( myString[0]) )
{
printf("String begins with a digit");
}
Regular expression:
\b[0-9]
Just a note for .Net Core
: We can use the FileContentResult
and set the contentType to application/octet-stream
if we want to send the raw bytes. Example:
[HttpGet("{id}")]
public IActionResult GetDocumentBytes(int id)
{
byte[] byteArray = GetDocumentByteArray(id);
return new FileContentResult(byteArray, "application/octet-stream");
}
The answer for Ashwini is great, in pointing out that scipy.math.factorial
, numpy.math.factorial
, math.factorial
are the same functions. However, I'd recommend use the one that Janne mentioned, that scipy.special.factorial
is different. The one from scipy can take np.ndarray
as an input, while the others can't.
In [12]: import scipy.special
In [13]: temp = np.arange(10) # temp is an np.ndarray
In [14]: math.factorial(temp) # This won't work
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-14-039ec0734458> in <module>()
----> 1 math.factorial(temp)
TypeError: only length-1 arrays can be converted to Python scalars
In [15]: scipy.special.factorial(temp) # This works!
Out[15]:
array([ 1.00000000e+00, 1.00000000e+00, 2.00000000e+00,
6.00000000e+00, 2.40000000e+01, 1.20000000e+02,
7.20000000e+02, 5.04000000e+03, 4.03200000e+04,
3.62880000e+05])
So, if you are doing factorial to a np.ndarray, the one from scipy will be easier to code and faster than doing the for-loops.
CSS:
html,body {
background: url(images/bg.jpg) no-repeat center center fixed;
-webkit-background-size: cover; /* For WebKit*/
-moz-background-size: cover; /* Mozilla*/
-o-background-size: cover; /* Opera*/
background-size: cover; /* Generic*/
}
show tables like 'table_name'
if this returns rows > 0 the table exists
You can use nonzero function. it returns the nonzero indices of the given input.
Easy Way
>>> (e > 15).nonzero()
(array([1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]), array([6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
to see the indices more cleaner, use transpose
method:
>>> numpy.transpose((e>15).nonzero())
[[1 6]
[1 7]
[1 8]
[1 9]
[2 0]
...
Not Bad Way
>>> numpy.nonzero(e > 15)
(array([1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]), array([6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
or the clean way:
>>> numpy.transpose(numpy.nonzero(e > 15))
[[1 6]
[1 7]
[1 8]
[1 9]
[2 0]
...
The instructions by peter_budo worked perfectly. I had to add the jars under /Library/Java/JavaVirtualMachines/JDK 1.7.0 Developer Preview.jdk/Contents/Home/jre/lib/ to my IntelliJ project libraries. Now it works like a charm. Note that I didn't need my IDE itself to run under 1.7; rather, I only needed to be able to compile and run against 1.7. I'll most likely continue to use Apple's JRE for running the IDE since it's probably more stable with respect to graphics routines (Swing, AWT). Like the OP, I was really keen on testing out the new NIO2 API. Looking good so far. Thanks, Peter.
I'm also surprised these aren't compile time constants. But I suppose you could create these values easily enough by simply executing an instruction that returns such an invalid result. Dividing by 0, log of 0, tan of 90, that kinda thing.
e.preventDefault(); from https://developer.mozilla.org/en-US/docs/Web/API/event.preventDefault
Or have return false from your method.
To rename the header without reassign df:
df.rename(columns=df.iloc[0], inplace = True)
To drop the row without reassign df:
df.drop(df.index[0], inplace = True)
Building upon your existing Student class, this is how I usually do it, especially if I need more than one comparator.
public class Student implements Comparable<Student> {
String name;
int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return name + ":" + age;
}
@Override
public int compareTo(Student o) {
return Comparators.NAME.compare(this, o);
}
public static class Comparators {
public static Comparator<Student> NAME = new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.name.compareTo(o2.name);
}
};
public static Comparator<Student> AGE = new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.age - o2.age;
}
};
public static Comparator<Student> NAMEANDAGE = new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
int i = o1.name.compareTo(o2.name);
if (i == 0) {
i = o1.age - o2.age;
}
return i;
}
};
}
}
Usage:
List<Student> studentList = new LinkedList<>();
Collections.sort(studentList, Student.Comparators.AGE);
EDIT
Since the release of Java 8 the inner class Comparators
may be greatly simplified using lambdas. Java 8 also introduces a new method for the Comparator
object thenComparing
, which removes the need for doing manual checking of each comparator when nesting them. Below is the Java 8 implementation of the Student.Comparators
class with these changes taken into account.
public static class Comparators {
public static final Comparator<Student> NAME = (Student o1, Student o2) -> o1.name.compareTo(o2.name);
public static final Comparator<Student> AGE = (Student o1, Student o2) -> Integer.compare(o1.age, o2.age);
public static final Comparator<Student> NAMEANDAGE = (Student o1, Student o2) -> NAME.thenComparing(AGE).compare(o1, o2);
}
That specifies the how many digits you want it to show.
integer value or * that specifies minimum field width. The result is padded with space characters (by default), if required, on the left when right-justified, or on the right if left-justified. In the case when * is used, the width is specified by an additional argument of type int. If the value of the argument is negative, it results with the - flag specified and positive field width.
Faster clearing than Arrays.fill is with this (From Fast Serialization Lib). I just use arrayCopy (is native) to clear the array:
static Object[] EmptyObjArray = new Object[10000];
public static void clear(Object[] arr) {
final int arrlen = arr.length;
clear(arr, arrlen);
}
public static void clear(Object[] arr, int arrlen) {
int count = 0;
final int length = EmptyObjArray.length;
while( arrlen - count > length) {
System.arraycopy(EmptyObjArray,0,arr,count, length);
count += length;
}
System.arraycopy(EmptyObjArray,0,arr,count, arrlen -count);
}
An activity populates the ActionBar in its onCreateOptionsMenu()
method.
Instead of using setcustomview()
, just override onCreateOptionsMenu
like this:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu, menu);
return true;
}
If an actions in the ActionBar is selected, the onOptionsItemSelected()
method is called. It receives the selected action as parameter. Based on this information you code can decide what to do for example:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuitem1:
Toast.makeText(this, "Menu Item 1 selected", Toast.LENGTH_SHORT).show();
break;
case R.id.menuitem2:
Toast.makeText(this, "Menu item 2 selected", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
nodevars.bat
"%HOMEDRIVE%%HOMEPATH% /file1/file2/file3
nodevars.bat
This work even with Swedish words
When inserting a row, regardless of the CopyOrigin, Excel will only put vertical borders on the inserted cells if the borders above and below the insert position are the same.
I'm running into a similar (but rotated) situation with inserting columns, but Copy/Paste is too slow for my workbook (tens of thousands of rows, many columns, and complex formatting).
I've found three workarounds that don't require copying the formatting from the source row:
Ensure the vertical borders are the same weight, color, and pattern above and below the insert position so Excel will replicate them in your new row. (This is the "It hurts when I do this," "Stop doing that!" answer.)
Use conditional formatting to establish the border (with a Formula of "=TRUE"). The conditional formatting will be copied to the new row, so you still end up with a border.Caveats:
Set the border on the inserted row in VBA after inserting the row. Setting a border on a range is much faster than copying and pasting all of the formatting just to get a border (assuming you know ahead of time what the border should be or can sample it from the row above without losing performance).
I got same error before,
type this query in your database CREATE SEQUENCE hibernate_sequence START WITH 1 INCREMENT BY 1 NOCYCLE;
that's work for me, good luck ~
Also look at log4net, which makes logging to 1 or more event stores — whether it's the console, the Windows event log, a text file, a network pipe, a SQL database, etc. — pretty trivial. You can even filter stuff in its configuration, for instance, so that only log records of a particular severity (say ERROR or FATAL) from a single component or assembly are directed to a particular event store.
I've searched and tried different things for hours.. To summarize, I had to take into consideration the following points:
smtp.gmail.com
instead of smtp.google.com
client.UseDefaultCredentials = false;
before setting credentialsclient.EnableSsl = true;
If these steps didn't help, check this answer.
Perhaps, you can find something useful on this System.Net.Mail FAQ too.
I have installed the SSH2 PECL extension and its working fine thanks all for you help...
Why not just create a setup project? It's really easy.
Voila, and you're done.
See here for more: http://www.codeproject.com/KB/dotnet/simplewindowsservice.aspx
There is also a way to prompt the user for credentials (or supply your own).
If you want the time as well, just go with
datetime.datetime.now().__str__()
Prints 2019-07-11 19:36:31.118766
in console for me
You should not care. If size is a concern I would use byte, short, int, then long. The only reason you would use an int larger than int32 is if you need a number higher than 2147483647 or lower than -2147483648.
Other than that I wouldn't care, there are plenty of other items to be concerned with.
try
fileName = Path.GetFileName (path);
http://msdn.microsoft.com/de-de/library/system.io.path.getfilename.aspx
You may find it helpful to look at Apple's documentation for its Core Foundation set of APIs. It is a pure C API, but many of the types are bridged to Objective-C object equivalents.
You may also find it helpful to look at the design of Objective-C itself. It's a bit different from C++ in that the object system is defined in terms of C functions, e.g. objc_msg_send
to call a method on an object. The compiler translates the square bracket syntax into those function calls, so you don't have to know it, but considering your question you may find it useful to learn how it works under the hood.
You must put all columns of the SELECT
in the GROUP BY
or use functions on them which compress the results to a single value (like MIN
, MAX
or SUM
).
A simple example to understand why this happens: Imagine you have a database like this:
FOO BAR
0 A
0 B
and you run SELECT * FROM table GROUP BY foo
. This means the database must return a single row as result with the first column 0
to fulfill the GROUP BY
but there are now two values of bar
to chose from. Which result would you expect - A
or B
? Or should the database return more than one row, violating the contract of GROUP BY
?
If the file is in the same directory as the one where the .md is, then just putting [Click here](MY-FILE.md)
should work.
Otherwise, can create a path from the root directory of the project. So if the entire project/git-repo root directory is called 'my-app', and one wants to point to my-app/client/read-me.md, then try [My hyperlink](/client/read-me.md)
.
At least works from Chrome.
For swift 3, I couldn't use just reachability from RAJAMOHAN-S solutions since it returns "true" if there is WiFi but no Internet. Thus, I implemented second validation via URLSession class and completion handler.
Here is the whole class.
import Foundation
import SystemConfiguration
public class Reachability {
class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
}
}
var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
return false
}
// Working for Cellular and WIFI
let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
let ret = (isReachable && !needsConnection)
return ret
}
class func isInternetAvailable(webSiteToPing: String?, completionHandler: @escaping (Bool) -> Void) {
// 1. Check the WiFi Connection
guard isConnectedToNetwork() else {
completionHandler(false)
return
}
// 2. Check the Internet Connection
var webAddress = "https://www.google.com" // Default Web Site
if let _ = webSiteToPing {
webAddress = webSiteToPing!
}
guard let url = URL(string: webAddress) else {
completionHandler(false)
print("could not create url from: \(webAddress)")
return
}
let urlRequest = URLRequest(url: url)
let session = URLSession.shared
let task = session.dataTask(with: urlRequest, completionHandler: { (data, response, error) in
if error != nil || response == nil {
completionHandler(false)
} else {
completionHandler(true)
}
})
task.resume()
}
}
And you call this like this, for example:
Reachability.isInternetAvailable(webSiteToPing: nil) { (isInternetAvailable) in
guard isInternetAvailable else {
// Inform user for example
return
}
// Do some action if there is Internet
}
On your existing button code, simply insert this line before the procedure:
If MsgBox("This will erase everything! Are you sure?", vbYesNo) = vbNo Then Exit Sub
This will force it to quit if the user presses no.
I thought that I might add this snippet to this old post. This is what I had done in the past, before the icons were fonts:
<i class="social-icon linkedin small" style="border-radius:7.5px;height:15px;width:15px;background-color:white;></i>
<i class="social-icon facebook small" style="border-radius:7.5px;height:15px;width:15px;background-color:white;></i>
This is very similar to @frbl 's sneaky answer, yet it does not use another image. Instead, this sets the background-color of the <i>
element to white
and uses the CSS property border-radius
to make the entire <i>
element "rounded." If you noticed, the value of the border-radius
(7.5px) is exactly half that of the width
and height
property (both 15px, making the icon square), making the <i>
element circular.
The root cause of this issue can be in the regional settings - DB waiting for YYYY-MM-DD while an app sents, for example, DD-MM-YYYY (Russian locale format) as it was in my case. All I did - change locale format from Russian to English (United States) and voilà.
Use count()
:
sc=scorm.objects.filter(Header__id=qp.id)
if sc.count() > 0:
...
The advantage over e.g. len()
is, that the QuerySet is not yet evaluated:
count()
performs aSELECT COUNT(*)
behind the scenes, so you should always usecount()
rather than loading all of the record into Python objects and callinglen()
on the result.
Having this in mind, When QuerySets are evaluated can be worth reading.
If you use get()
, e.g. scorm.objects.get(pk=someid)
, and the object does not exists, an ObjectDoesNotExist
exception is raised:
from django.core.exceptions import ObjectDoesNotExist
try:
sc = scorm.objects.get(pk=someid)
except ObjectDoesNotExist:
print ...
Update:
it's also possible to use exists()
:
if scorm.objects.filter(Header__id=qp.id).exists():
....
Returns
True
if the QuerySet contains any results, andFalse
if not. This tries to perform the query in the simplest and fastest way possible, but it does execute nearly the same query as a normal QuerySet query.
The Spring Framework has a class which allows to recursively search through the classpath:
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
resolver.getResources("classpath*:some/package/name/**/*.xml");
there is another solution to download a web page in ajax. But I am referring to a page that must first be processed and then downloaded.
First you need to separate the page processing from the results download.
1) Only the page calculations are made in the ajax call.
$.post("CalculusPage.php", { calculusFunction: true, ID: 29, data1: "a", data2: "b" }, function(data, status) { if (status == "success") { /* 2) In the answer the page that uses the previous calculations is downloaded. For example, this can be a page that prints the results of a table calculated in the ajax call. */ window.location.href = DownloadPage.php+"?ID="+29; } } ); // For example: in the CalculusPage.php if ( !empty($_POST["calculusFunction"]) ) { $ID = $_POST["ID"]; $query = "INSERT INTO ExamplePage (data1, data2) VALUES ('".$_POST["data1"]."', '".$_POST["data2"]."') WHERE id = ".$ID; ... } // For example: in the DownloadPage.php $ID = $_GET["ID"]; $sede = "SELECT * FROM ExamplePage WHERE id = ".$ID; ... $filename="Export_Data.xls"; header("Content-Type: application/vnd.ms-excel"); header("Content-Disposition: inline; filename=$filename"); ...
I hope this solution can be useful for many, as it was for me.
You can use the Console API (which made its appearance in Java 6) as follows:
Console cons = System.console();
if(cons != null) {
char c = (char) cons.reader().read(); // Checking for EOF omitted
...
}
If you just need a single line you don't even need to go through the reader object:
String s = cons.readLine();
I'm using eclipse neon 3. I just wanted to use javafx.application.Application, so I followed Christian Hujer's answer above and it worked. Just some tips: the access rules are very similar to the import statement. For me, the access rules I added was "javafx/application/**". Just replace the dot in the import statement with forward slash and that's the rule. Hope that helps.
Use java.time.Instant
class to parse text in standard ISO 8601 format, representing a moment in UTC.
Instant.parse( "2010-10-02T12:23:23Z" )
That format is defined by the ISO 8601 standard for date-time string formats.
Both:
…use ISO 8601 formats by default for parsing and generating strings.
You should generally avoid using the old java.util.Date/.Calendar & java.text.SimpleDateFormat classes as they are notoriously troublesome, confusing, and flawed. If required for interoperating, you can convert to and fro.
Built into Java 8 and later is the new java.time framework. Inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project.
Instant instant = Instant.parse( "2010-10-02T12:23:23Z" ); // `Instant` is always in UTC.
Convert to the old class.
java.util.Date date = java.util.Date.from( instant ); // Pass an `Instant` to the `from` method.
Time Zone
If needed, you can assign a time zone.
ZoneId zoneId = ZoneId.of( "America/Montreal" ); // Define a time zone rather than rely implicitly on JVM’s current default time zone.
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId ); // Assign a time zone adjustment from UTC.
Convert.
java.util.Date date = java.util.Date.from( zdt.toInstant() ); // Extract an `Instant` from the `ZonedDateTime` to pass to the `from` method.
UPDATE: The Joda-Time project is now in maintenance mode. The team advises migration to the java.time classes.
Here is some example code in Joda-Time 2.8.
org.joda.time.DateTime dateTime_Utc = new DateTime( "2010-10-02T12:23:23Z" , DateTimeZone.UTC ); // Specifying a time zone to apply, rather than implicitly assigning the JVM’s current default.
Convert to old class. Note that the assigned time zone is lost in conversion, as j.u.Date cannot be assigned a time zone.
java.util.Date date = dateTime_Utc.toDate(); // The `toDate` method converts to old class.
Time Zone
If needed, you can assign a time zone.
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime dateTime_Montreal = dateTime_Utc.withZone ( zone );
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
The best way to find out what properties and methods are available to an HTML node (object) is to do something like:
console.log($("#my-node"));
From jQuery 1.6+ you can just use outerHTML to include the HTML tags in your string output:
var node = $("#my-node").outerHTML;
As for the negation, if you want to know if an element hasn't a class you can simply do as Mark said.
if (!currentPage.parent().hasClass('home')) { do what you want }
Their feature sets are not at all the same. Sqlite is an embedded database which has no network capabilities (unless you add them). So you can't use it on a network.
If you need
You need to use mysql or some other server-based RDBMS.
Note that MySQL is not the only choice and there are plenty of others which might be better for new applications (for example pgSQL).
Sqlite is a very, very nice piece of software, but it has never made claims to do any of these things that RDBMS servers do. It's a small library which runs SQL on local files (using locking to ensure that multiple processes don't screw the file up). It's really well tested and I like it a lot.
Also, if you aren't able to choose this correctly by yourself, you probably need to hire someone on your team who can.
You can use this:
comment = Comment.objects.filter(pk=comment_id)
Just to add Python 3 f-string solution
prob = 1.0/3.0
print(f"{prob:.0%}")
i have same issue and solve it by using this command
$git config --global http.proxy http://enter_your_proxy:enter_port
Define tooltip text
<input type="text" id="firstname" name="firstname" tooltipText="Type in your firstname in this box">
Initialize and configure the script
<script type="text/javascript">
var tooltipObj = new DHTMLgoodies_formTooltip();
tooltipObj.setTooltipPosition('right');
tooltipObj.setPageBgColor('#EEE');
tooltipObj.setCloseMessage('Exit');
tooltipObj.initFormFieldTooltip();
</script>
just .idea/
works fine for me
In Eclipse, go to Help -> Install New Software -> Add -> Name: any name like egit; Location: http://download.eclipse.org/egit/updates -> Okay. Now Search for egit in Work with and select all the check boxes and press Next till finish.
File -> Import -> search Git and select "Projects from Git" -> Clone URI. In the URI, paste the HTTPS URL of the repository (the one with .git extension). -> Next ->It will show all the branches "Next" -> Local Destination "Next" -> "Import as a general project" -> Next till finish.
You can refer to this Youtube tutorial: https://www.youtube.com/watch?v=ptK9-CNms98
Extend Code for Show Selected Sheet(s) [ one or more sheets].
Sub Show_SelectSheet()
For Each xSheet In ThisWorkbook.Worksheets
For Each xSelectSheet In ActiveWindow.SelectedSheets
If xSheet.Name = xSelectSheet.Name Then
'=== Show Selected Sheet ===
GoTo xNext_SelectSheet
End If
Next xSelectSheet
xSheet.Visible = False
xNext_SelectSheet:
Next xSheet
MsgBox "Show Selected Sheet(s) Completed !!!"
end sub
Try this version which does not require order to be the same but does support having multiple of the same value. They match only if each has the same quantity of any value.
public boolean arraysMatch(List<String> elements1, List<String> elements2) {
// Optional quick test since size must match
if (elements1.size() != elements2.size()) {
return false;
}
List<String> work = newArrayList(elements2);
for (String element : elements1) {
if (!work.remove(element)) {
return false;
}
}
return work.isEmpty();
}
You can replace the first letter (preceded by a digit
) of each word using regex:
re.sub(r'(\d\w)', lambda w: w.group().upper(), '1bob 5sandy')
output:
1Bob 5Sandy
Instead of changing the COM port in Device manager, if you're using the Arduino software, I had to set the port in Tools > Port menu.
Also simple and easy:
Start-Sleep 10
The most easiest way I came up with to send the push notification to all the devices is to subscribe them to a topic "all" and then send notification to this topic. Copy this in your main activity
FirebaseMessaging.getInstance().subscribeToTopic("all");
Now send the request as
{
"to":"/topics/all",
"data":
{
"title":"Your title",
"message":"Your message"
"image-url":"your_image_url"
}
}
This might be inefficient or non-standard way, but as I mentioned above it's the easiest. Please do post if you have any better way to send a push notification to all the devices.
You can follow this tutorial if you're new to sending push notifications using Firebase Cloud Messaging Tutorial - Push Notifications using FCM
To send a message to a combination of topics, specify a condition, which is a boolean expression that specifies the target topics. For example, the following condition will send messages to devices that are subscribed to TopicA
and either TopicB
or TopicC
:
{
"data":
{
"title": "Your title",
"message": "Your message"
"image-url": "your_image_url"
},
"condition": "'TopicA' in topics && ('TopicB' in topics || 'TopicC' in topics)"
}
Read more about conditions and topics here on FCM documentation
The dollarsign as a prefix in the var name is a usage from the concept of the hungarian notation.
I suggest you use a wrapper div or paragraph:
<td><p style="width:50%;">Text only allowed to extend 50% of the cell.</p></td>
And you can make a class out of it:
<td class="linebreak"><p>Text only allowed to extend 50% of the cell.</p></td>
td.linebreak p {
width: 50%;
}
All of this assuming that you meant 50% as in 50% of the cell.
You are missing an include :
#include <stdlib.h>
, so GCC creates an implicit declaration of atof
and atod
, leading to garbage values.
And the format specifier for double is %f
, not %d
(that is for integers).
#include <stdlib.h>
#include <stdio.h>
int main()
{
char *test = "12.11";
double temp = strtod(test,NULL);
float ftemp = atof(test);
printf("price: %f, %f",temp,ftemp);
return 0;
}
/* Output */
price: 12.110000, 12.110000
Use bases if you just want to get the parents, use __mro__
(as pointed out by @naught101) for getting the method resolution order (so to know in which order the init's were executed).
Bases (and first getting the class for an existing object):
>>> some_object = "some_text"
>>> some_object.__class__.__bases__
(object,)
For mro in recent Python versions:
>>> some_object = "some_text"
>>> some_object.__class__.__mro__
(str, object)
Obviously, when you already have a class definition, you can just call __mro__
on that directly:
>>> class A(): pass
>>> A.__mro__
(__main__.A, object)
The simplest way to sidestep this limitation is to switch to 64 bit R.
Try docker rmi node
. That should work.
Seeing all created containers is as simple as docker ps -a
.
To remove all existing containers (not images!) run docker rm $(docker ps -aq)
input[type='text'],textarea {font-size:1em;}
Windows Software Development Kit (SDK) for Windows 8.1
http://go.microsoft.com/fwlink/p/?LinkId=323507
Right click on Project, select properties and Un-Check the sign on option in teh project save and re-built.
This has fixed issue for me.
I figured it out. Basically it's an async issue. You can't just submit and expect to render the subsequent page immediately. You have to wait until the onLoad event for the next page is triggered. My code is below:
var page = new WebPage(), testindex = 0, loadInProgress = false;
page.onConsoleMessage = function(msg) {
console.log(msg);
};
page.onLoadStarted = function() {
loadInProgress = true;
console.log("load started");
};
page.onLoadFinished = function() {
loadInProgress = false;
console.log("load finished");
};
var steps = [
function() {
//Load Login Page
page.open("https://website.com/theformpage/");
},
function() {
//Enter Credentials
page.evaluate(function() {
var arr = document.getElementsByClassName("login-form");
var i;
for (i=0; i < arr.length; i++) {
if (arr[i].getAttribute('method') == "POST") {
arr[i].elements["email"].value="mylogin";
arr[i].elements["password"].value="mypassword";
return;
}
}
});
},
function() {
//Login
page.evaluate(function() {
var arr = document.getElementsByClassName("login-form");
var i;
for (i=0; i < arr.length; i++) {
if (arr[i].getAttribute('method') == "POST") {
arr[i].submit();
return;
}
}
});
},
function() {
// Output content of page to stdout after form has been submitted
page.evaluate(function() {
console.log(document.querySelectorAll('html')[0].outerHTML);
});
}
];
interval = setInterval(function() {
if (!loadInProgress && typeof steps[testindex] == "function") {
console.log("step " + (testindex + 1));
steps[testindex]();
testindex++;
}
if (typeof steps[testindex] != "function") {
console.log("test complete!");
phantom.exit();
}
}, 50);
Consider the following servlet conf:
<servlet>
<servlet-name>NewServlet</servlet-name>
<servlet-class>NewServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>NewServlet</servlet-name>
<url-pattern>/NewServlet/*</url-pattern>
</servlet-mapping>
Now, when I hit the URL http://localhost:8084/JSPTemp1/NewServlet/jhi
, it will invoke NewServlet
as it is mapped with the pattern described above.
Here:
getRequestURI() = /JSPTemp1/NewServlet/jhi
getPathInfo() = /jhi
We have those ones:
getPathInfo()
returns
a String, decoded by the web container, specifying extra path information that comes after the servlet path but before the query string in the request URL; or null if the URL does not have any extra path information
getRequestURI()
returns
a String containing the part of the URL from the protocol name up to the query string
use like this :-
gridview1.DataSource = ds.Tables[0]; <-- Use index or your table name which you want to bind
gridview1.DataBind();
I hope it helps!!
Use NSLog()
like this:
NSLog(@"The code runs through here!");
Or like this - with placeholders:
float aFloat = 5.34245;
NSLog(@"This is my float: %f \n\nAnd here again: %.2f", aFloat, aFloat);
In NSLog()
you can use it like + (id)stringWithFormat:(NSString *)format, ...
float aFloat = 5.34245;
NSString *aString = [NSString stringWithFormat:@"This is my float: %f \n\nAnd here again: %.2f", aFloat, aFloat];
You can add other placeholders, too:
float aFloat = 5.34245;
int aInteger = 3;
NSString *aString = @"A string";
NSLog(@"This is my float: %f \n\nAnd here is my integer: %i \n\nAnd finally my string: %@", aFloat, aInteger, aString);
If non-numeric value encountered in your code try below one. The below code is converted to float.
$PlannedAmount = ''; // empty string ''
if(!is_numeric($PlannedAmount)) {
$PlannedAmount = floatval($PlannedAmount);
}
echo $PlannedAmount; //output = 0
If you're fine with using ES6. Arrays now have the findIndex function. Which means you can do something like this:
const index = Data.findIndex(item => item.name === 'John');
I do not know how to solve this using code, but I do manually adjust the control panel at the right bottom in the plot figure, and adjust the figure size like:
f, ax = plt.subplots(figsize=(16, 12))
at the meantime until you get a matched size colobar. This worked for me.
You can "abort" a task by running it on a thread you control and aborting that thread. This causes the task to complete in a faulted state with a ThreadAbortException
. You can control thread creation with a custom task scheduler, as described in this answer. Note that the caveat about aborting a thread applies.
(If you don't ensure the task is created on its own thread, aborting it would abort either a thread-pool thread or the thread initiating the task, neither of which you typically want to do.)
If its only the cluttering what gives the problem in the constructor
why not implement a initialize
method that intializes
the variables. This is a normal thing to do when the constructor gets to full with unnecessary stuff. Even in typed program languages like C#
its normal convention to add an Initialize
method to handle that.
Another native solution (in coffee):
el = document.getElementsByTagName 'b'
docFrag = document.createDocumentFragment()
docFrag.appendChild el.firstChild while el.childNodes.length
el.parentNode.replaceChild docFrag, el
I don't know if it's faster than user113716's solution, but it might be easier to understand for some.
I need to code such that if a certain list index exists, then run a function.
You already know how to test for this and in fact are already performing such tests in your code.
The valid indices for a list of length n
are 0
through n-1
inclusive.
Thus, a list has an index i
if and only if the length of the list is at least i + 1
.
You can use .filter()
with boolean operators ie &&:
var find = my_array.filter(function(result) {
return result.param1 === "srting1" && result.param2 === 'string2';
});
return find[0];
The combination of map
and lambda
functions in Python is a good solution for this kind of problem:
a = [2,2,2]
b = [1,1,1]
map(lambda x,y: x-y, a,b)
zip
function is another good choice, as demonstrated by @UncleZeiv
You can use the following to get the previous URL.
var oldURL = document.referrer;
alert(oldURL);
This error (and also ORA-6413: Connection not open) can also be caused by parentheses in the application executable path and a bug in the 10.2.0.1 or lower oracle client libraries.
You should either upgrade your oracle client library or change the executable path.
Further details see:
If you would migrate your project to Spring Boot 1.4, you could use new annotation @MockBean
for faking MyDependentObject
. With that feature you could remove Mockito's @Mock
and @InjectMocks
annotations from your test.
Just for anyone who is still looking for solutions:
The RecordMyScreen jailbreak app is opensourced and works fine even on non-jailbreak devices if we have the developer license. You can have a look at the source: https://github.com/coolstar/RecordMyScreen
seems you need to link with the obj file that implements tolayer5()
Update: your function declaration doesn't match the implementation:
void tolayer5(int AorB, struct msg msgReceived)
void tolayer5(int, char data[])
So compiler would treat them as two different functions (you are using c++). and it cannot find the implementation for the one you called in main().
Josepmra example works well for what i need. But i had to add the line
form.appendTo( document.body )
for it to work.
var form = $(document.createElement('form'));
$(form).attr("action", "reserves.php");
$(form).attr("method", "POST");
var input = $("<input>")
.attr("type", "hidden")
.attr("name", "mydata")
.val("bla" );
$(form).append($(input));
form.appendTo( document.body )
$(form).submit();
Try this:
string selected = this.ComboBox.GetItemText(this.ComboBox.SelectedItem);
MessageBox.Show(selected);
File --> Preferences --> Settings --> User --> Font --> Font Size Enter the Font size. You can sync these settings with your Git Hub or Microsoft TFS.
HTML:
?<div class="header">This is the header</div>
<div class="content">This is the content</div>?????????????????????????????????
CSS:
?.header
{
height:50px;
}
.content
{
position:absolute;
top: 50px;
left:0px;
right:0px;
bottom:0px;
overflow-y:scroll;
}?
ListView.FocusedItem.Index
or you can use foreach loop like this
int index= -1;
foreach (ListViewItem itm in listView1.SelectedItems)
{
if (itm.Selected)
{
index= itm.Index;
}
}
I'm having the same issue here and I was a bit afraid of checking the last box, since I have no idea what the 3rd party SDK will do with the data collected and if they will respect the Limit Ad Settings.
But I found a post by a Google Admob programmer, Eric Leichtenschlag, on their forums:
The Google Mobile Ads SDK and the Google Conversion Tracking SDK utilize Apple's advertising identifier introduced in iOS 6 (IDFA). While each developer is responsible for how they access device data, the SDKs use IDFA under the guidelines laid out in the iOS developer program license agreement, including Limit Ad Tracking.
Including Limit Ad Tracking. This is what the last box is all about. So you must check the that box if you use AdMob. If you use other SDK I strongly recommend checking if they respect the guidelines as well.
Since I run only ads (Google AdMob), I checked the first (Serve ads...) and last box (I, ___, confirm...). App was approved and released, no issues.
Source: https://groups.google.com/forum/#!topic/google-admob-ads-sdk/BsGRSZ-gLmk
Try using float: left
(or right
) instead of display: inline
. Inline display replaces list-item display, which is what adds the bullet points.
<form class="form-horizontal" method="post">
<div class="control-group">
<input type="text" name="subject_code" id="inputEmail" placeholder="Subject Code">
</div>
<div class="control-group">
<input type="text" class="span8" name="title" id="inputPassword" placeholder="Subject Title" required>
</div>
<div class="control-group">
<input type="text" class="span1" name="unit" id="inputPassword" required>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Semester</label>
<div class="controls">
<select name="semester">
<option></option>
<option>1st</option>
<option>2nd</option>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Deskripsi</label>
<div class="controls">
<textarea name="description" id="ckeditor_full"></textarea>
<script>CKEDITOR.replace('ckeditor_full');</script>
</div>
</div>
<div class="control-group">
<div class="controls">
<button name="save" type="submit" class="btn btn-info"><i class="icon-save"></i> Simpan</button>
</div>
</div>
</form>
<?php
if (isset($_POST['save'])){
$subject_code = $_POST['subject_code'];
$title = $_POST['title'];
$unit = $_POST['unit'];
$description = $_POST['description'];
$semester = $_POST['semester'];
$query = mysql_query("select * from subject where subject_code = '$subject_code' ")or die(mysql_error());
$count = mysql_num_rows($query);
if ($count > 0){ ?>
<script>
alert('Data Sudah Ada');
</script>
<?php
}else{
mysql_query("insert into subject (subject_code,subject_title,description,unit,semester) values('$subject_code','$title','$description','$unit','$semester')")or die(mysql_error());
mysql_query("insert into activity_log (date,username,action) values(NOW(),'$user_username','Add Subject $subject_code')")or die(mysql_error());
?>
<script>
window.location = "subjects.php";
</script>
<?php
}
}
?>
i would see a very simple way
git reset --hard HEAD <YOUR COMMIT ID>
and then reset remote branch
git push origin -f
Agree with neubert about the DECLARE statements, this will fix syntax error. But I would suggest you to avoid using openning cursors, they may be slow.
For your task: use INSERT...SELECT statement which will help you to copy data from one table to another using only one query.
You didn't say which database server you are using, but if temp tables are available they may be the best approach.
// table is a temp table
select ... into #table ....
SELECT COUNT(column1),column1 FROM #table GROUP BY column1
SELECT COUNT(column2),column2 FROM #table GROUP BY column2
SELECT COUNT(column3),column3 FROM #table GROUP BY column3
// drop may not be required
drop table #table
For kotlin check out
val string = "<<<First Grade>>>"
println(string.drop(6)) // st Grade>>>
println(string.dropLast(6)) // <<<First Gr
println(string.dropWhile { !it.isLetter() }) // First Grade>>>
println(string.dropLastWhile { !it.isLetter() }) // <<<First Grade
Yes,
class Bar : public Foo
{
...
void printStuff()
{
Foo::printStuff();
}
};
It is the same as super
in Java, except it allows calling implementations from different bases when you have multiple inheritance.
class Foo {
public:
virtual void foo() {
...
}
};
class Baz {
public:
virtual void foo() {
...
}
};
class Bar : public Foo, public Baz {
public:
virtual void foo() {
// Choose one, or even call both if you need to.
Foo::foo();
Baz::foo();
}
};
Is Java smart enough to skip checking bool2 and bool2 if bool1 was evaluated to false?
Its not a matter of being smart, its a requirement specified in the language. Otherwise you couldn't write expressions like.
if(s != null && s.length() > 0)
or
if(s == null || s.length() == 0)
BTW if you use &
and |
it will always evaluate both sides of the expression.
Use calendar.isleap
:
import calendar
print(calendar.isleap(1900))
Declare value attribute for input tag (i.e value= {this.state.name}
) and if you want to clear this input vale you have to use this.setState({name : ''})
PFB working code for your reference :
<script type="text/babel">
var StateComponent = React.createClass({
resetName : function(event){
this.setState({
name : ''
});
},
render : function(){
return (
<div>
<input type="text" value= {this.state.name}/>
<button onClick={this.resetName}>Reset</button>
</div>
)
}
});
ReactDOM.render(<StateComponent/>, document.getElementById('app'));
</script>
git config --global credential.helper cache
statement level trigger is only once for dml statement row leval trigger is for each row for dml statements
also, look for a comment // that breaks the closing curly brace
if (1==1) { //echo "it is true"; }
the closing curly brace will not properly close the conditional section and php won't properly process the remainder of code.
@Matt Dodges answer put me on the right track. Thanks again for all the answers, which helped a lot of guys in the mean time. Got it working like this:
SELECT *
FROM feeds f
LEFT JOIN artists a ON a.artist_id = (
SELECT artist_id
FROM feeds_artists fa
WHERE fa.feed_id = f.id
LIMIT 1
)
WHERE f.id = '13815'