How about using the ExecutorService.shutDownNow()
method as described in http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html? It seems to be the simplest solution.
This is because of AbstractExecutorService :: submit
is wrapping your runnable
into RunnableFuture
(nothing but FutureTask
) like below
AbstractExecutorService.java
public Future<?> submit(Runnable task) {
if (task == null) throw new NullPointerException();
RunnableFuture<Void> ftask = newTaskFor(task, null); /////////HERE////////
execute(ftask);
return ftask;
}
Then execute
will pass it to Worker
and Worker.run()
will call the below.
ThreadPoolExecutor.java
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // allow interrupts
boolean completedAbruptly = true;
try {
while (task != null || (task = getTask()) != null) {
w.lock();
// If pool is stopping, ensure thread is interrupted;
// if not, ensure thread is not interrupted. This
// requires a recheck in second case to deal with
// shutdownNow race while clearing interrupt
if ((runStateAtLeast(ctl.get(), STOP) ||
(Thread.interrupted() &&
runStateAtLeast(ctl.get(), STOP))) &&
!wt.isInterrupted())
wt.interrupt();
try {
beforeExecute(wt, task);
Throwable thrown = null;
try {
task.run(); /////////HERE////////
} catch (RuntimeException x) {
thrown = x; throw x;
} catch (Error x) {
thrown = x; throw x;
} catch (Throwable x) {
thrown = x; throw new Error(x);
} finally {
afterExecute(task, thrown);
}
} finally {
task = null;
w.completedTasks++;
w.unlock();
}
}
completedAbruptly = false;
} finally {
processWorkerExit(w, completedAbruptly);
}
}
Finally
task.run();
in the above code call will callFutureTask.run()
. Here is the exception handler code, because of this you are NOT getting the expected exception.
class FutureTask<V> implements RunnableFuture<V>
public void run() {
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return;
try {
Callable<V> c = callable;
if (c != null && state == NEW) {
V result;
boolean ran;
try {
result = c.call();
ran = true;
} catch (Throwable ex) { /////////HERE////////
result = null;
ran = false;
setException(ex);
}
if (ran)
set(result);
}
} finally {
// runner must be non-null until state is settled to
// prevent concurrent calls to run()
runner = null;
// state must be re-read after nulling runner to prevent
// leaked interrupts
int s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
ArrayBlockingQueue has lower memory footprint, it can reuse element node, not like LinkedBlockingQueue that have to create a LinkedBlockingQueue$Node object for each new insertion.
Shorter version:
public static String unescapeJava(String escaped) {
if(escaped.indexOf("\\u")==-1)
return escaped;
String processed="";
int position=escaped.indexOf("\\u");
while(position!=-1) {
if(position!=0)
processed+=escaped.substring(0,position);
String token=escaped.substring(position+2,position+6);
escaped=escaped.substring(position+6);
processed+=(char)Integer.parseInt(token,16);
position=escaped.indexOf("\\u");
}
processed+=escaped;
return processed;
}
select nvl(max(1), 0) from mytable;
This statement yields 0 if there are no rows, 1 if you have at least one row in that table. It's way faster than doing a select count(*). The optimizer "sees" that only a single row needs to be fetched to answer the question.
Here's a (verbose) little example:
declare
YES constant signtype := 1;
NO constant signtype := 0;
v_table_has_rows signtype;
begin
select nvl(max(YES), NO)
into v_table_has_rows
from mytable -- where ...
;
if v_table_has_rows = YES then
DBMS_OUTPUT.PUT_LINE ('mytable has at least one row');
end if;
end;
I was also facing that problem, but I resolved it. Make sure that both the programs for client-side and server-side are on different projects in your IDE, in my case NetBeans. Then assuming you're using localhost, I recommend you to implement both the programs as two different projects.
In addition to Idriss answer:
In CSS we write code as depicted bellow, in full length.
body{
width: 800px;
color: #ffffff;
}
body content{
width:750px;
background:#ffffff;
}
In SCSS we can shorten this code using a @mixin
so we don’t have to write color
and width
properties again and again. We can define this through a function, similarly to PHP or other languages.
$color: #ffffff;
$width: 800px;
@mixin body{
width: $width;
color: $color;
content{
width: $width;
background:$color;
}
}
In SASS however, the whole structure is visually quicker and cleaner than SCSS.
It seems that it doesn't support inline CSS currently.
$color: #ffffff
$width: 800px
$stack: Helvetica, sans-serif
body
width: $width
color: $color
font: 100% $stack
content
width: $width
background:$color
I used convert Activity
Activity activity = (Activity) context;
Public SUB test()
Dim mdate As Date
mdate = now()
MsgBox (Round(CDbl(mdate), 0))
End SUB
I know it's a bit late, but I just came across this post and wanted to mention that I don't really see way everybody wants to do it in a difficult way... The problem here is just that the book class takes twoside as default, so, as gromgull said, just pass oneside as argument and it's solved.
Java doesn't have the concept of optional parameters with default values either in constructors or in methods. You're basically stuck with overloading. However, you chain constructors easily so you don't need to repeat the code:
public Foo(int param1, int param2)
{
this.param1 = param1;
this.param2 = param2;
}
public Foo(int param1)
{
this(param1, 2);
}
Jackson appears to support some amount of JSON parsing straight from an InputStream
. My understanding is that it runs on Android and is fairly quick. On the other hand, it is an extra JAR to include with your app, increasing download and on-flash size.
Here is a way to avoid the assumption that
all users are consenting adults, and thus are responsible for using things correctly themselves.
Using @property
, is very verbose e.g.:
class AClassWithManyAttributes:
'''refactored to properties'''
def __init__(a, b, c, d, e ...)
self._a = a
self._b = b
self._c = c
self.d = d
self.e = e
@property
def a(self):
return self._a
@property
def b(self):
return self._b
@property
def c(self):
return self._c
# you get this ... it's long
Using
No underscore: it's a public variable.
One underscore: it's a protected variable.
Two underscores: it's a private variable.
Except the last one, it's a convention. You can still, if you really try hard, access variables with double underscore.
Behold! read_only_properties
decorator to the rescue!
@read_only_properties('readonly', 'forbidden')
class MyClass(object):
def __init__(self, a, b, c):
self.readonly = a
self.forbidden = b
self.ok = c
m = MyClass(1, 2, 3)
m.ok = 4
# we can re-assign a value to m.ok
# read only access to m.readonly is OK
print(m.ok, m.readonly)
print("This worked...")
# this will explode, and raise AttributeError
m.forbidden = 4
You ask:
Where is
read_only_properties
coming from?
Glad you asked, here is the source for read_only_properties:
def read_only_properties(*attrs):
def class_rebuilder(cls):
"The class decorator"
class NewClass(cls):
"This is the overwritten class"
def __setattr__(self, name, value):
if name not in attrs:
pass
elif name not in self.__dict__:
pass
else:
raise AttributeError("Can't modify {}".format(name))
super().__setattr__(name, value)
return NewClass
return class_rebuilder
I never expected this answer will get so much attention. Surprisingly it does. This encouraged me to create a package you can use.
$ pip install read-only-properties
in your python shell:
In [1]: from rop import read_only_properties
In [2]: @read_only_properties('a')
...: class Foo:
...: def __init__(self, a, b):
...: self.a = a
...: self.b = b
...:
In [3]: f=Foo('explodes', 'ok-to-overwrite')
In [4]: f.b = 5
In [5]: f.a = 'boom'
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-5-a5226072b3b4> in <module>()
----> 1 f.a = 'boom'
/home/oznt/.virtualenvs/tracker/lib/python3.5/site-packages/rop.py in __setattr__(self, name, value)
116 pass
117 else:
--> 118 raise AttributeError("Can't touch {}".format(name))
119
120 super().__setattr__(name, value)
AttributeError: Can't touch a
You can use element.getBoundingClientRect()
to retrieve element position relative to the viewport.
Then use document.documentElement.scrollTop
to calculate the viewport offset.
The sum of the two will give the element position relative to the document:
element.getBoundingClientRect().top + document.documentElement.scrollTop
Xcode 11.1 requires generating ?ertificate from Xcode directly
So you will have smth like this on https://developer.apple.com after
As gratitude to the timely help I got from here - a minor update to above.
$query = "UPDATE `db`.`table` SET `fieldname`= str_to_date( fieldname, '%d/%m/%Y')";
For example, if you can be confident that any Bug object is going to be a blessed hash, you can (finally!) fill in the missing code in the Bug::print_me method:
package Bug;
sub print_me
{
my ($self) = @_;
print "ID: $self->{id}\n";
print "$self->{descr}\n";
print "(Note: problem is fatal)\n" if $self->{type} eq "fatal";
}
Now, whenever the print_me method is called via a reference to any hash that's been blessed into the Bug class, the $self variable extracts the reference that was passed as the first argument and then the print statements access the various entries of the blessed hash.
I normally run sites on Linux, but I also develop on a local Windows machine. I've run into this problem many times and just fixed the tables when I encountered the problems. I installed an app yesterday to help someone out and of course ran into the problem again. So, I decided it was time to figure out what was going on - and found this thread. I really don't like the idea of changing the sql_mode of the server to an earlier mode (by default), so I came up with a simple (me thinks) solution.
This solution would of course require developers to wrap their table creation scripts to compensate for the MySQL issue running on Windows. You'll see similar concepts in dump files. One BIG caveat is that this could/will cause problems if partitioning is used.
// Store the current sql_mode
mysql_query("set @orig_mode = @@global.sql_mode");
// Set sql_mode to one that won't trigger errors...
mysql_query('set @@global.sql_mode = "MYSQL40"');
/**
* Do table creations here...
*/
// Change it back to original sql_mode
mysql_query('set @@global.sql_mode = @orig_mode');
That's about it.
There's an error in your code. You're using a mix of full syntax and shorthand notation on the background-image property.This is causing the no-repeat to be ignored, since it's not a valid value for the background-image property.
body{
background-position:center;
background-image:url(../images/images2.jpg) no-repeat;
}
Should become one of the following:
body{
background:url(../images/images2.jpg) center center no-repeat;
}
or
body
{
background-image: url(path-to-file/img.jpg);
background-repeat:no-repeat;
background-position: center center;
}
EDIT: For your image 'scaling' issue, you might want to look at this question's answer.
I assume you are getting an exception because of Single. Your list may have more than one answer marked as correct, that is why Single
will throw an exception use First, or FirstOrDefault();
Answer answer = Answers.FirstOrDefault(a => a.Correct);
Also if you want to get list of all items marked as correct you may try:
List<Answer> correctedAnswers = Answers.Where(a => a.Correct).ToList();
If your desired result is Single
, then the mistake you are doing in your query is comparing an item with the bool value. Your comparison
a == a.Correct
is wrong in the statement. Your single query should be:
Answer answer = Answers.Single(a => a.Correct == true);
Or shortly as:
Answer answer = Answers.Single(a => a.Correct);
The main difference between struct and class is that in struct you can only declare data variables of different data types while in class you can declare data variables,member functions and thus you can manipulate data variables through functions.
-> another handy thing that i find in class vs struct is that while implementing files in a program if you want to make some operations of a struct again and again on every new set of operations you need to make a separate function and you need to pass object of struct after reading it from the file so as to make some operations on it . while in class if you make a function that does some operations on the data needed everytime..its easy you just have to read object from file and call the function..
But it depennds on the programmer which way he/she finds suitable...according to me i prefer class everytime just because it supports OOPs and thats the reason it is implemented in almost every languages and its the wonderful feature of all time programming ;-)
And yeah the most unforgotten difference i forgot to mention is that class supports data hiding and also supports operations that are performed on built in data types while struct doesnt !
Here is the code little modified that i got it from google -
List data_table = new ArrayList<>();
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection(conn_url, user_id, password);
Statement stmt = con.createStatement();
System.out.println("query_string: "+query_string);
ResultSet rs = stmt.executeQuery(query_string);
ResultSetMetaData rsmd = rs.getMetaData();
int row_count = 0;
while (rs.next()) {
HashMap<String, String> data_map = new HashMap<>();
if (row_count == 240001) {
break;
}
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
data_map.put(rsmd.getColumnName(i), rs.getString(i));
}
data_table.add(data_map);
row_count = row_count + 1;
}
rs.close();
stmt.close();
con.close();
Your css will only work in IE browser. And the css suggessted by hayk.mart will olny work in webkit browsers. And by using different css hacks you can't style your browsers scroll bars with a same result.
So, it is better to use a jQuery/Javascript plugin to achieve a cross browser solution with a same result.
Solution:
By Using jScrollPane a jQuery plugin, you can achieve a cross browser solution
We can change the default parallelism using the following property:
-Djava.util.concurrent.ForkJoinPool.common.parallelism=16
which can set up to use more parallelism.
Here is another variant I posted on related question. The REGEX
check to see if you are out of bounds is useful, so for a table column you would put it in the where clause.
SET @Array = 'one,two,three,four';
SET @ArrayIndex = 2;
SELECT CASE
WHEN @Array REGEXP CONCAT('((,).*){',@ArrayIndex,'}')
THEN SUBSTRING_INDEX(SUBSTRING_INDEX(@Array,',',@ArrayIndex+1),',',-1)
ELSE NULL
END AS Result;
SUBSTRING_INDEX(string, delim, n)
returns the first nSUBSTRING_INDEX(string, delim, -1)
returns the last onlyREGEXP '((delim).*){n}'
checks if there are n delimiters (i.e. you are in bounds)Yisrael Dov's answer is the straightforward one, but it doesn't allow compression. You can use --format=zip
, but you can't directly unzip that with a pipe command like you can with tar, so you need to save it as a temporary file. Here's a script:
#!/bin/bash
BASENAME=$0
function usage {
echo "usage: $BASENAME <remote-repo> <file> ..."
exit 1
}
[ 2 -gt "$#" ] && { usage; }
REPO=$1
shift
FILES=$@
TMPFILE=`mktemp`.zip
git archive -9 --remote=$REPO HEAD $FILES -o $TMPFILE
unzip $TMPFILE
rm $TMPFILE
This works with directories too.
I wanted to do something similar, but on a form with a background image, I found that when the text in the label changed the repaints were obvious with this method, so I did the following: * Set the label AutoSize to true and TextAlign to MiddleCenter
Then, each time the text changed (mine was done using a timer) I called the following method:
private Point GetPosition()
{
int y = (this.Height / 2) - (label1.Height / 2);
int x = (this.Width / 2) - (label1.Width / 2);
return new Point(x, y);
}
And set the label's Location property to this return value. This ensured that the label was always in the center of the form when the text changed and the repaints for a full-screen form weren't obvious.
pd.wide_to_long
You can add a prefix to your year columns and then feed directly to pd.wide_to_long
. I won't pretend this is efficient, but it may in certain situations be more convenient than pd.melt
, e.g. when your columns already have an appropriate prefix.
df.columns = np.hstack((df.columns[:2], df.columns[2:].map(lambda x: f'Value{x}')))
res = pd.wide_to_long(df, stubnames=['Value'], i='name', j='Date').reset_index()\
.sort_values(['location', 'name'])
print(res)
name Date location Value
0 test Jan-2010 A 12
2 test Feb-2010 A 20
4 test March-2010 A 30
1 foo Jan-2010 B 18
3 foo Feb-2010 B 20
5 foo March-2010 B 25
If you use the prettier extension in Visual Studio Code, try adding this to the settings.json file:
"editor.insertSpaces": false,
"editor.tabSize": 4,
"editor.detectIndentation": false,
"prettier.tabWidth": 4,
"prettier.useTabs": true // This made it finally work for me
I think I've found it....from http://www-cs-students.stanford.edu/~blynn/gitmagic/ch02.html
Sometimes you just want to go back and forget about every change past a certain point because they're all wrong.
Start with:
$ git log
which shows you a list of recent commits, and their SHA1 hashes.
Next, type:
$ git reset --hard SHA1_HASH
to restore the state to a given commit and erase all newer commits from the record permanently.
Is the value of your particular COMMENT column null?
Sometimes NOT LIKE doesn't know how to behave properly around nulls.
Do you want a better way to pass the arguments or just a way to stop pylint
from giving you a hard time? If the latter, I seem to recall that you could stop the nagging by putting pylint
-controlling comments in your code along the lines of:
#pylint: disable=R0913
or, better:
#pylint: disable=too-many-arguments
remembering to turn them back on as soon as practicable.
In my opinion, there's nothing inherently wrong with passing a lot of arguments and solutions advocating wrapping them all up in some container argument don't really solve any problems, other than stopping pylint
from nagging you :-).
If you need to pass twenty arguments, then pass them. It may be that this is required because your function is doing too much and a re-factoring could assist there, and that's something you should look at. But it's not a decision we can really make unless we see what the 'real' code is.
Ok, finally found the solution.
Probably due to lack of experience with ReactJS and web development...
var Task = React.createClass({
render: function() {
var percentage = this.props.children + '%';
....
<div className="ui-progressbar-value ui-widget-header ui-corner-left" style={{width : percentage}}/>
...
I created the percentage variable outside in the render function.
Just keep the following in mind.
In IIS if you have a folder for example called Pages with multiple websites in it. Website will inherit settings from the web.config file from the parent directory. So even if the folder page (in this example Pages) isn't a website but contains a web.config file, all websites listed inside of it will inherit the setting.
This is against the general mechanism of Stream. Say you can split Stream S0 to Sa and Sb like you wanted. Performing any terminal operation, say count()
, on Sa will necessarily "consume" all elements in S0. Therefore Sb lost its data source.
Previously, Stream had a tee()
method, I think, which duplicate a stream to two. It's removed now.
Stream has a peek() method though, you might be able to use it to achieve your requirements.
The legitimate way to do that irrespective of size of the div for any browser size is :
div{
margin:auto;
height: 200px;
width: 200px;
position:fixed;
top:0;
bottom:0;
left:0;
right:0;
background:red;
}
Qberticus's answer is good, but one useful detail is missing. If you are implementing these in a library replace:
xmlns:whatever="http://schemas.android.com/apk/res/org.example.mypackage"
with:
xmlns:whatever="http://schemas.android.com/apk/res-auto"
Otherwise the application that uses the library will have runtime errors.
.jar isn't executable. Instantiate classes or make call to any static method.
EDIT: Add Main-Class entry while creating a JAR.
>p.mf (content of p.mf)
Main-Class: pk.Test
>Test.java
package pk;
public class Test{
public static void main(String []args){
System.out.println("Hello from Test");
}
}
Use Process class and it's methods,
public class Exec
{
public static void main(String []args) throws Exception
{
Process ps=Runtime.getRuntime().exec(new String[]{"java","-jar","A.jar"});
ps.waitFor();
java.io.InputStream is=ps.getInputStream();
byte b[]=new byte[is.available()];
is.read(b,0,b.length);
System.out.println(new String(b));
}
}
another thing that working for me , is to open the project in xcode, and then clean and build it. usually it reruns the packaging server and solve the problem.
As suggested here by @0x7fffffff, if you have UINavigationController it can be easier to do:
YourViewController *rootController =
(YourViewController *)
[self.navigationController.viewControllers objectAtIndex: 0];
The code in the answer above returns UINavigation controller (if you have it) and if this is what you need, you can use self.navigationController
.
//converts decimal to binary string
String convertToBinary(int decimalNumber){
String binary="";
while(decimalNumber>0){
int remainder=decimalNumber%2;
//line below ensures the remainders are reversed
binary=remainder+binary;
decimalNumber=decimalNumber/2;
}
return binary;
}
By default Chrome extensions do not run in Incognito mode. You have to explicitly enable the extension to run in Incognito.
Thank you Phil for your solution; in case someone ever gets in the same situation as me, here is a (more complex) variant:
---
# this is just to avoid a call to |default on each iteration
- set_fact:
postconf_d: {}
- name: 'get postfix default configuration'
command: 'postconf -d'
register: command
# the answer of the command give a list of lines such as:
# "key = value" or "key =" when the value is null
- name: 'set postfix default configuration as fact'
set_fact:
postconf_d: >
{{
postconf_d |
combine(
dict([ item.partition('=')[::2]|map('trim') ])
)
with_items: command.stdout_lines
This will give the following output (stripped for the example):
"postconf_d": {
"alias_database": "hash:/etc/aliases",
"alias_maps": "hash:/etc/aliases, nis:mail.aliases",
"allow_min_user": "no",
"allow_percent_hack": "yes"
}
Going even further, parse the lists in the 'value':
- name: 'set postfix default configuration as fact'
set_fact:
postconf_d: >-
{% set key, val = item.partition('=')[::2]|map('trim') -%}
{% if ',' in val -%}
{% set val = val.split(',')|map('trim')|list -%}
{% endif -%}
{{ postfix_default_main_cf | combine({key: val}) }}
with_items: command.stdout_lines
...
"postconf_d": {
"alias_database": "hash:/etc/aliases",
"alias_maps": [
"hash:/etc/aliases",
"nis:mail.aliases"
],
"allow_min_user": "no",
"allow_percent_hack": "yes"
}
A few things to notice:
in this case it's needed to "trim" everything (using the >-
in YAML and -%}
in Jinja), otherwise you'll get an error like:
FAILED! => {"failed": true, "msg": "|combine expects dictionaries, got u\" {u'...
obviously the {% if ..
is far from bullet-proof
in the postfix case, val.split(',')|map('trim')|list
could have been simplified to val.split(', ')
, but I wanted to point out the fact you will need to |list
otherwise you'll get an error like:
"|combine expects dictionaries, got u\"{u'...': <generator object do_map at ...
Hope this can help.
Just Re install the turbo C++ from your Computer and install again in the Directory C:\TC\ Folder.
Again The Problem exists ,then change the directory from FILE>>CHANGE DIRECTORY to C:\TC\BIN\
here is one in c# that doesn't run out of memory when splitting into large chunks! I needed to split 95M file into 10M x line files.
var fileSuffix = 0;
int lines = 0;
Stream fstream = File.OpenWrite($"{filename}.{(++fileSuffix)}");
StreamWriter sw = new StreamWriter(fstream);
using (var file = File.OpenRead(filename))
using (var reader = new StreamReader(file))
{
while (!reader.EndOfStream)
{
sw.WriteLine(reader.ReadLine());
lines++;
if (lines >= 10000000)
{
sw.Close();
fstream.Close();
lines = 0;
fstream = File.OpenWrite($"{filename}.{(++fileSuffix)}");
sw = new StreamWriter(fstream);
}
}
}
sw.Close();
fstream.Close();
You have to rely on '#' but to make the task easier in vi you can perform the following (press escape first):
:10,20 s/^/#
with 10 and 20 being the start and end line numbers of the lines you want to comment out
and to undo when you are complete:
:10,20 s/^#//
So simple you can use case statement here.
CASE WHEN ISSUE_DIVISION = ISSUE_DIVISION_2 THEN
CASE WHEN ISSUE_DIVISION is null then "Null Value found" //give your option
Else 1 End
ELSE 0 END As Issue_Division_Result
As specified in the documentation, use undefined
:
export interface INotificationService {
error(message: string, title?: string, autoHideAfter? : number);
}
class X {
error(message: string, title?: string, autoHideAfter?: number) {
console.log(message, title, autoHideAfter);
}
}
new X().error("hi there", undefined, 1000);
To store Python objects in files, use the pickle
module:
import pickle
a = {
'a': 1,
'b': 2
}
with open('file.txt', 'wb') as handle:
pickle.dump(a, handle)
with open('file.txt', 'rb') as handle:
b = pickle.loads(handle.read())
print a == b # True
Notice that I never set b = a
, but instead pickled a
to a file and then unpickled it into b
.
As for your error:
self.whip = open('deed.txt', 'r').read()
self.whip
was a dictionary object. deed.txt
contains text, so when you load the contents of deed.txt
into self.whip
, self.whip
becomes the string representation of itself.
You'd probably want to evaluate the string back into a Python object:
self.whip = eval(open('deed.txt', 'r').read())
Notice how eval
sounds like evil
. That's intentional. Use the pickle
module instead.
string strConn = "Data Source=ORCL134; User ID=user; Password=psd;";
System.Data.OracleClient.OracleConnection con = newSystem.Data.OracleClient.OracleConnection(strConn);
con.Open();
System.Data.OracleClient.OracleCommand Cmd =
new System.Data.OracleClient.OracleCommand(
"SELECT * FROM TBLE_Name WHERE ColumnName_year= :year", con);
//for oracle..it is :object_name and for sql it s @object_name
Cmd.Parameters.Add(new System.Data.OracleClient.OracleParameter("year", (txtFinYear.Text).ToString()));
System.Data.OracleClient.OracleDataAdapter da = new System.Data.OracleClient.OracleDataAdapter(Cmd);
DataSet myDS = new DataSet();
da.Fill(myDS);
try
{
lblBatch.Text = "Batch Number is : " + Convert.ToString(myDS.Tables[0].Rows[0][19]);
lblBatch.ForeColor = System.Drawing.Color.Green;
lblBatch.Visible = true;
}
catch
{
lblBatch.Text = "No Data Found for the Year : " + txtFinYear.Text;
lblBatch.ForeColor = System.Drawing.Color.Red;
lblBatch.Visible = true;
}
da.Dispose();
con.Close();
It really all comes down to how you want to handle output that the command might return and whether you want your PHP script to wait for the callee program to finish or not.
exec
executes a command and passes output to the caller (or returns it in an optional variable).
passthru
is similar to the exec()
function in that it executes a command . This function should be used in place of exec()
or system()
when the output from the Unix command is binary data which needs to be passed directly back to the browser.
system
executes an external program and displays the output, but only the last line.
If you need to execute a command and have all the data from the command passed directly back without any interference, use the passthru()
function.
I'd use recursion just in case so you can deep copy the map
and avoid bad surprises in case you were to change a map
element that is a map
itself.
Here's an example in a utils.go:
package utils
func CopyMap(m map[string]interface{}) map[string]interface{} {
cp := make(map[string]interface{})
for k, v := range m {
vm, ok := v.(map[string]interface{})
if ok {
cp[k] = CopyMap(vm)
} else {
cp[k] = v
}
}
return cp
}
And its test file (i.e. utils_test.go):
package utils
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestCopyMap(t *testing.T) {
m1 := map[string]interface{}{
"a": "bbb",
"b": map[string]interface{}{
"c": 123,
},
}
m2 := CopyMap(m1)
m1["a"] = "zzz"
delete(m1, "b")
require.Equal(t, map[string]interface{}{"a": "zzz"}, m1)
require.Equal(t, map[string]interface{}{
"a": "bbb",
"b": map[string]interface{}{
"c": 123,
},
}, m2)
}
It should easy enough to adapt if you need the map
key to be something else instead of a string
.
From the ECMAScript specification in section 7.6 Identifier Names and Identifiers, a valid identifier is defined as:
Identifier ::
IdentifierName but not ReservedWord
IdentifierName ::
IdentifierStart
IdentifierName IdentifierPart
IdentifierStart ::
UnicodeLetter
$
_
\ UnicodeEscapeSequence
IdentifierPart ::
IdentifierStart
UnicodeCombiningMark
UnicodeDigit
UnicodeConnectorPunctuation
\ UnicodeEscapeSequence
UnicodeLetter
any character in the Unicode categories “Uppercase letter (Lu)”, “Lowercase letter (Ll)”, “Titlecase letter (Lt)”,
“Modifier letter (Lm)”, “Other letter (Lo)”, or “Letter number (Nl)”.
UnicodeCombiningMark
any character in the Unicode categories “Non-spacing mark (Mn)” or “Combining spacing mark (Mc)”
UnicodeDigit
any character in the Unicode category “Decimal number (Nd)”
UnicodeConnectorPunctuation
any character in the Unicode category “Connector punctuation (Pc)”
UnicodeEscapeSequence
see 7.8.4.
HexDigit :: one of
0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F
which creates a lot of opportunities for naming variables and also in golfing. Let's try some examples.
A valid identifier could start with either a UnicodeLetter
, $
, _
, or \ UnicodeEscapeSequence
. A unicode letter is any character from these categories (see all categories):
This alone accounts for some crazy possibilities - working examples. If it doesn't work in all browsers, then call it a bug, cause it should.
var ? = "something";
var HELLO = "hello";
var ???? = "less than? wtf";
var ????????????? = "javascript"; // ok that's JavaScript in hindi
var KingGeorge? = "Roman numerals, awesome!";
Define a method named remove() on array objects using the prototyping feature of JavaScript.
Use splice() method to fulfill your requirement.
Please have a look at the below code.
Array.prototype.remove = function(item) {
// 'index' will have -1 if 'item' does not exist,
// else it will have the index of the first item found in the array
var index = this.indexOf(item);
if (index > -1) {
// The splice() method is used to add/remove items(s) in the array
this.splice(index, 1);
}
return index;
}
var arr = [ 11, 22, 67, 45, 61, 89, 34, 12, 7, 8, 3, -1, -4];
// Printing array
// [ 11, 22, 67, 45, 61, 89, 34, 12, 7, 8, 3, -1, -4];
console.log(arr)
// Removing 67 (getting its index, i.e. 2)
console.log("Removing 67")
var index = arr.remove(67)
if (index > 0){
console.log("Item 67 found at ", index)
} else {
console.log("Item 67 does not exist in array")
}
// Printing updated array
// [ 11, 22, 45, 61, 89, 34, 12, 7, 8, 3, -1, -4];
console.log(arr)
// ............... Output ................................
// [ 11, 22, 67, 45, 61, 89, 34, 12, 7, 8, 3, -1, -4 ]
// Removing 67
// Item 67 found at 2
// [ 11, 22, 45, 61, 89, 34, 12, 7, 8, 3, -1, -4 ]
Note: The below is the full example code executed on the Node.js REPL which describes the use of push(), pop(), shift(), unshift(), and splice() methods.
> // Defining an array
undefined
> var arr = [12, 45, 67, 89, 34, 12, 7, 8, 3, -1, -4, -11, 0, 56, 12, 34];
undefined
> // Getting length of array
undefined
> arr.length;
16
> // Adding 1 more item at the end i.e. pushing an item
undefined
> arr.push(55);
17
> arr
[ 12, 45, 67, 89, 34, 12, 7, 8, 3, -1, -4, -11, 0, 56, 12, 34, 55 ]
> // Popping item from array (i.e. from end)
undefined
> arr.pop()
55
> arr
[ 12, 45, 67, 89, 34, 12, 7, 8, 3, -1, -4, -11, 0, 56, 12, 34 ]
> // Remove item from beginning
undefined
> arr.shift()
12
> arr
[ 45, 67, 89, 34, 12, 7, 8, 3, -1, -4, -11, 0, 56, 12, 34 ]
> // Add item(s) at beginning
undefined
> arr.unshift(67); // Add 67 at beginning of the array and return number of items in updated/new array
16
> arr
[ 67, 45, 67, 89, 34, 12, 7, 8, 3, -1, -4, -11, 0, 56, 12, 34 ]
> arr.unshift(11, 22); // Adding 2 more items at the beginning of array
18
> arr
[ 11, 22, 67, 45, 67, 89, 34, 12, 7, 8, 3, -1, -4, -11, 0, 56, 12, 34 ]
>
> // Define a method on array (temporarily) to remove an item and return the index of removed item; if it is found else return -1
undefined
> Array.prototype.remove = function(item) {
... var index = this.indexOf(item);
... if (index > -1) {
..... this.splice(index, 1); // splice() method is used to add/remove items in array
..... }
... return index;
... }
[Function]
>
> arr
[ 11, 22, 67, 45, 67, 89, 34, 12, 7, 8, 3, -1, -4, -11, 0, 56, 12, 34 ]
>
> arr.remove(45); // Remove 45 (you will get the index of removed item)
3
> arr
[ 11, 22, 67, 67, 89, 34, 12, 7, 8, 3, -1, -4, -11, 0, 56, 12, 34 ]
>
> arr.remove(22) // Remove 22
1
> arr
[ 11, 67, 67, 89, 34, 12, 7, 8, 3, -1, -4, -11, 0, 56, 12, 34 ]
> arr.remove(67) // Remove 67
1
> arr
[ 11, 67, 89, 34, 12, 7, 8, 3, -1, -4, -11, 0, 56, 12, 34 ]
>
> arr.remove(89) // Remove 89
2
> arr
[ 11, 67, 34, 12, 7, 8, 3, -1, -4, -11, 0, 56, 12, 34 ]
>
> arr.remove(100); // 100 doesn't exist, remove() will return -1
-1
>
Something like next:
>>> myList = [1, 2, 3, 100, 5]
>>> [i[0] for i in sorted(enumerate(myList), key=lambda x:x[1])]
[0, 1, 2, 4, 3]
enumerate(myList)
gives you a list containing tuples of (index, value):
[(0, 1), (1, 2), (2, 3), (3, 100), (4, 5)]
You sort the list by passing it to sorted
and specifying a function to extract the sort key (the second element of each tuple; that's what the lambda
is for. Finally, the original index of each sorted element is extracted using the [i[0] for i in ...]
list comprehension.
It's better to use the String.substr()
.
Like this:
ReplString = GivenStr.substr(0, PostostarRelStr)
+ GivenStr(PostostarRelStr, ReplString.lenght());
To know number of selected elements use
$("select option:selected").length
To Get the value of all selected elements use
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
There's really no easy way to mix fluid and fixed widths with Bootstrap 3. It's meant to be like this, as the grid system is designed to be a fluid, responsive thing. You could try hacking something up, but it would go against what the Responsive Grid system is trying to do, the intent of which is to make that layout flow across different device types.
If you need to stick with this layout, I'd consider laying out your page with custom CSS and not using the grid.
Change your systemPath.
<dependency>
<groupId>stuff</groupId>
<artifactId>library</artifactId>
<version>1.0</version>
<systemPath>${project.basedir}/MyLibrary.jar</systemPath>
<scope>system</scope>
</dependency>
This worked for me, based on your code, generating a 93Mb png image with color noise and the desired dimensions:
import matplotlib.pyplot as plt
import numpy
w = 7195
h = 3841
im_np = numpy.random.rand(h, w)
fig = plt.figure(frameon=False)
fig.set_size_inches(w,h)
ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()
fig.add_axes(ax)
ax.imshow(im_np, aspect='normal')
fig.savefig('figure.png', dpi=1)
I am using the last PIP versions of the Python 2.7 libraries in Linux Mint 13.
Hope that helps!
The file you are trying to import is a zip file. Unzip the file and then try to import again.
Make sure that in the path to the project there is no foldername having whitespace. While creating a project the specified path folders must not contain any space in their naming.
<Resource>
tag with your DB details inside <GlobalNamingResources>
<Resource name="jdbc/mydb"
global="jdbc/mydb"
auth="Container"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/test"
username="root"
password=""
maxActive="10"
maxIdle="10"
minIdle="5"
maxWait="10000"/>
<ResourceLink>
inside the <Context>
tag.<ResourceLink name="jdbc/mydb"
global="jdbc/mydb"
auth="Container"
type="javax.sql.DataSource" />
Adding:
-------
<property name="connection.datasource">java:comp/env/jdbc/mydb</property>
Removing:
--------
<!--<property name="connection.url">jdbc:mysql://localhost:3306/mydb</property> -->
<!--<property name="connection.username">root</property> -->
<!--<property name="connection.password"></property> -->
In addition to existing good answers, note that Jackson 1.9 improved handling by adding "property unification", meaning that ALL annotations from difference parts of a logical property are combined, using (hopefully) intuitive precedence.
In Jackson 1.8 and prior, only field and getter annotations were used when determining what and how to serialize (writing JSON); and only and setter annotations for deserialization (reading JSON). This sometimes required addition of "extra" annotations, like annotating both getter and setter.
With Jackson 1.9 and above these extra annotations are NOT needed. It is still possible to add those; and if different names are used, one can create "split" properties (serializing using one name, deserializing using other): this is occasionally useful for sort of renaming.
If your array is not initialized then it contains randoms values and cannot be checked !
To initialize your array with 0 values:
int array[5] = {0};
Then you can check if the value is 0:
array[4] == 0;
When you compare to NULL, it compares to 0 as the NULL is defined as integer value 0 or 0L.
If you have an array of pointers, better use the nullptr
value to check:
char* array[5] = {nullptr}; // we defined an array of char*, initialized to nullptr
if (array[4] == nullptr)
// do something
It really depends on the IE versions ... I found this excellent resource that is up to date from IE6-10:
CSS hack for Internet Explorer 6
It is called the Star HTML Hack and looks as follows:
- html .color {color: #F00;} This hack uses fully valid CSS.
CSS hack for Internet Explorer 7
It is called the Star Plus Hack.
*:first-child+html .color {color: #F00;} Or a shorter version:
*+html .color {color: #F00;} Like the star HTML hack, this uses valid CSS.
CSS hack for Internet Explorer 8
@media \0screen { .color {color: #F00;} } This hacks does not use valid CSS.
CSS hack for Internet Explorer 9
:root .color {color: #F00\9;} This hacks also does not use valid CSS.
Added 2013.02.04: Unfortunately IE10 understands this hack.
CSS hack for Internet Explorer 10
@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) { .color {color: #F00;} } This hacks also does not use valid CSS.
I had the very same issue, not being able to instantiate the type of a class which I was absolutely sure was not abstract. Turns out I was implementing an abstract class from Java.util
instead of implementing my own class.
So if the previous answers did not help you, please check that you import
the class you actually wanted to import, and not something else with the same name that you IDE might have hinted you.
For example, if you were trying to instantiate the class Queue from the package myCollections which you coded yourself :
import java.util.*; // replace this line
import myCollections.Queue; // by this line
Queue<Edge> theQueue = new Queue<Edge>();
If you have recently upgraded springboot to 1.4.3, you might need to make changes to yml file:
yml in 1.3 :
jpa:
hibernate:
namingStrategy: org.hibernate.cfg.EJB3NamingStrategy
yml in 1.4.3 :
jpa:
hibernate:
naming: physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
If you wish to customize your legend, just use the add_legend
method. It takes the same parameters as matplotlib plt.legend
.
import seaborn as sns
sns.set(style="whitegrid")
titanic = sns.load_dataset("titanic")
g = sns.factorplot("class", "survived", "sex",
data=titanic, kind="bar",
size=6, palette="muted",
legend_out=False)
g.despine(left=True)
g.set_ylabels("survival probability")
g.add_legend(bbox_to_anchor=(1.05, 0), loc=2, borderaxespad=0.)
After you get from Eclipse the ugly CheckoutConflictException, the Eclipse-Merge Tool button is disabled.
Git need alle your files added to the Index for enable Merging.
So, to merge your Changes and commit them you need to add your files first to the index "Add to Index" and "Commit" them without "Push". Then you should see one pending pull and one pending push request in Eclipse. You see that in one up arrow and one down arrow.
If all conflict Files are in the commit, you can "pull" again. Then you will see something like:
\< < < < < < < HEAD Server Version \======= Local Version > > > > > > > branch 'master' of ....git
Then you either change it by the Merge-Tool, which is now enable or just do the merge by hand direct in the file. In the last step, you have to add the modified files again to the index and "Commit and Push" them.
Checking done!
If you are using anaconda to go into python environment you should have build up different environment for different python version
The following scripts may help you build up a new environment(running in anaconda prompt)
conda create -n py27 python=2.7 #for version 2.7
activate py27
conda create -n py36 python=3.6 #for version 3.6
activate py36
you may leave the environment back to your global env by typing
deactivate py27
or
deactivate py36
and then you can either switch to different environment using your anaconda UI with @Francisco Camargo 's answer
or you can stick to anaconda prompt using @Dan 's answer
Those settings (core.whitespace
and apply.whitespace
) are not there to remove trailing whitespace but to:
core.whitespace
: detect them, and raise errors apply.whitespace
: and strip them, but only during patch, not "always automatically"I believe the git hook pre-commit
would do a better job for that (includes removing trailing whitespace)
Note that at any given time you can choose to not run the pre-commit
hook:
git commit --no-verify .
cd .git/hooks/ ; chmod -x pre-commit
Warning: by default, a pre-commit
script (like this one), has not a "remove trailing" feature", but a "warning" feature like:
if (/\s$/) {
bad_line("trailing whitespace", $_);
}
You could however build a better pre-commit
hook, especially when you consider that:
Committing in Git with only some changes added to the staging area still results in an “atomic” revision that may never have existed as a working copy and may not work.
For instance, oldman proposes in another answer a pre-commit
hook which detects and remove whitespace.
Since that hook get the file name of each file, I would recommend to be careful for certain type of files: you don't want to remove trailing whitespace in .md
(markdown) files!
Don't pass db models directly to your views. You're lucky enough to be using MVC, so encapsulate using view models.
Create a view model class like this:
public class EmployeeAddViewModel
{
public Employee employee { get; set; }
public Dictionary<int, string> staffTypes { get; set; }
// really? a 1-to-many for genders
public Dictionary<int, string> genderTypes { get; set; }
public EmployeeAddViewModel() { }
public EmployeeAddViewModel(int id)
{
employee = someEntityContext.Employees
.Where(e => e.ID == id).SingleOrDefault();
// instantiate your dictionaries
foreach(var staffType in someEntityContext.StaffTypes)
{
staffTypes.Add(staffType.ID, staffType.Type);
}
// repeat similar loop for gender types
}
}
Controller:
[HttpGet]
public ActionResult Add()
{
return View(new EmployeeAddViewModel());
}
[HttpPost]
public ActionResult Add(EmployeeAddViewModel vm)
{
if(ModelState.IsValid)
{
Employee.Add(vm.Employee);
return View("Index"); // or wherever you go after successful add
}
return View(vm);
}
Then, finally in your view (which you can use Visual Studio to scaffold it first), change the inherited type to ShadowVenue.Models.EmployeeAddViewModel. Also, where the drop down lists go, use:
@Html.DropDownListFor(model => model.employee.staffTypeID,
new SelectList(model.staffTypes, "ID", "Type"))
and similarly for the gender dropdown
@Html.DropDownListFor(model => model.employee.genderID,
new SelectList(model.genderTypes, "ID", "Gender"))
Update per comments
For gender, you could also do this if you can be without the genderTypes in the above suggested view model (though, on second thought, maybe I'd generate this server side in the view model as IEnumerable). So, in place of new SelectList...
below, you would use your IEnumerable.
@Html.DropDownListFor(model => model.employee.genderID,
new SelectList(new SelectList()
{
new { ID = 1, Gender = "Male" },
new { ID = 2, Gender = "Female" }
}, "ID", "Gender"))
Finally, another option is a Lookup table. Basically, you keep key-value pairs associated with a Lookup type. One example of a type may be gender, while another may be State, etc. I like to structure mine like this:
ID | LookupType | LookupKey | LookupValue | LookupDescription | Active
1 | Gender | 1 | Male | male gender | 1
2 | State | 50 | Hawaii | 50th state | 1
3 | Gender | 2 | Female | female gender | 1
4 | State | 49 | Alaska | 49th state | 1
5 | OrderType | 1 | Web | online order | 1
I like to use these tables when a set of data doesn't change very often, but still needs to be enumerated from time to time.
Hope this helps!
echo '{"ab": 1, "cd": 2}' | jq -r 'keys[]'
prints all keys one key per line without quotes.
ab
cd
I'm tuning into what krtek has written. More specifically solution 1:
Assumptions:
Solution:
hg rollback
to undo the last commitThe rollback really undoes the last operation. Its way of working is quite simple: normal operations in HG will only append to files; this includes a commit. Mercurial keeps track of the file lengths of the last transaction and can therefore completely undo one step by truncating the files back to their old lengths.
feof()
is not very intuitive. In my very humble opinion, the FILE
's end-of-file state should be set to true
if any read operation results in the end of file being reached. Instead, you have to manually check if the end of file has been reached after each read operation. For example, something like this will work if reading from a text file using fgetc()
:
#include <stdio.h>
int main(int argc, char *argv[])
{
FILE *in = fopen("testfile.txt", "r");
while(1) {
char c = fgetc(in);
if (feof(in)) break;
printf("%c", c);
}
fclose(in);
return 0;
}
It would be great if something like this would work instead:
#include <stdio.h>
int main(int argc, char *argv[])
{
FILE *in = fopen("testfile.txt", "r");
while(!feof(in)) {
printf("%c", fgetc(in));
}
fclose(in);
return 0;
}
You are using the wrong iteration counter, replace inp.charAt(i)
with inp.charAt(j)
.
You need to pass your data in the request body as a raw string rather than FormUrlEncodedContent
. One way to do so is to serialize it into a JSON string:
var json = JsonConvert.SerializeObject(data); // or JsonSerializer.Serialize if using System.Text.Json
Now all you need to do is pass the string to the post method.
var stringContent = new StringContent(json, UnicodeEncoding.UTF8, "application/json"); // use MediaTypeNames.Application.Json in Core 3.0+ and Standard 2.1+
var client = new HttpClient();
var response = await client.PostAsync(uri, stringContent);
3 Ways to Install Applications On Android Without The Market
And don't forget to enable Unknown sources in your Android device Settings, before installing apk, else Android platform will not allow you to install apk directly
CREATE VIEW MyView AS
SELECT Column, Value FROM Table;
SELECT Column FROM MyView WHERE Value = 1;
Is the proper solution in MySQL, some other SQLs let you define Views more exactly.
Note: Unless the View is very complicated, MySQL will optimize this just fine.
Use %.6f
.
This will print 6 decimals.
I was able to make this work with the
transform: scale(1.03);
Property applied on the image. For some reason, on Chrome, the other solutions provided wouldn't work if there was any relatively positioned parent element.
Check http://jsfiddle.net/ud5ya7jt/
This way the image will be slightly zoomed in by 3% and the edges will be cropped which shouldn't be a problem on a blurred image anyway. It worked well in my case because I was using a high res image as a background. Good luck!
You can use
window.clipboardData.getData('Text')
to get the content of user's clipboard in IE. However, in other browser you may need to use flash to get the content, since there is no standard interface to access the clipboard. May be you can have try this plugin Zero Clipboard
@GianCarlo: You can try calling System property user.dir that will give you root of your java project and then do append this path to your relative path for example:
String root = System.getProperty("user.dir");
String filepath = "/path/to/yourfile.txt"; // in case of Windows: "\\path \\to\\yourfile.txt
String abspath = root+filepath;
// using above path read your file into byte []
File file = new File(abspath);
FileInputStream fis = new FileInputStream(file);
byte []filebytes = new byte[(int)file.length()];
fis.read(filebytes);
I had the exact same problem and figured out that by default the Mail Shield from Avast antivirus had the "Scan SSL connection" activated. Make sure to turn that off.
From my knowledge, Avast will "open" the mail, scan it for any viruses and then sign it using it's own certificate so the mail won't be signed by the gmail's certificate anymore which produces that error.
Solution 1:
Solution 2 (Should be the best security speaking):
Loop like
foreach (GridViewRow row in grid.Rows)
{
if (((CheckBox)row.FindControl("chkboxid")).Checked)
{
//read the label
}
}
To add to these answers, if you have an R script containing calls that generate plots to screen (the native device), then these can all be saved to a pdf file (the default device for a non-interactive shell) "Rplots.pdf" (the default name) by redirecting the script into R from the terminal (assuming you are running linux or OS X), e.g.:
R < myscript.R --no-save
This could be converted to jpg/png as necessary
The other way to get in a git detached head state is to try to commit to a remote branch. Something like:
git fetch
git checkout origin/foo
vi bar
git commit -a -m 'changed bar'
Note that if you do this, any further attempt to checkout origin/foo will drop you back into a detached head state!
The solution is to create your own local foo branch that tracks origin/foo, then optionally push.
This probably has nothing to do with your original problem, but this page is high on the google hits for "git detached head" and this scenario is severely under-documented.
@nithin,
AWS released layers
concept inside Lambda
functions. You can create your layer and there you can upload as much as libraries and then you can connect the layer with the lambda functions.
For more details: https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html
Try edtFTPj/PRO, a mature, robust SFTP client library that supports connection pools and asynchronous operations. Also supports FTP and FTPS so all bases for secure file transfer are covered.
You can use AddHandler to add a handler for any event.
For example, this might be:
AddHandler theButton.Click, AddressOf Me.theButton_Click
When you set 64-bit the resulting binary is a "Fat" binary, which contains all three Mach-O images bundled with a thin fat header. You can see that using otool or jtool. You can check out some fat binaries included as part of the iOS 7.0 SDK, for example the AVFoundation Framework, like so:
% cd /Developer/Platforms/iPhoneOS.platform/DeviceSupport/7.0\ \(11A465\)/Symbols/System/Library/Frameworks/AVFoundation.framework/
%otool -V -f AVFoundation 9:36
Fat headers
fat_magic FAT_MAGIC
nfat_arch 3
architecture arm64 # The 64-bit version (A7)
cputype CPU_TYPE_ARM64
cpusubtype CPU_SUBTYPE_ARM64_ALL
capabilities 0x0
offset 16384
size 2329888
align 2^14 (16384)
architecture armv7 # A5X - packaged after the arm64version
cputype CPU_TYPE_ARM
cpusubtype CPU_SUBTYPE_ARM_V7
capabilities 0x0
offset 2359296
size 2046336
align 2^14 (16384)
architecture armv7s # A6 - packaged after the armv7 version
cputype CPU_TYPE_ARM
cpusubtype CPU_SUBTYPE_ARM_V7S
capabilities 0x0
offset 4407296
size 2046176
align 2^14 (16384)
As for the binary itself, it uses the ARM64 bit instruction set, which is (mostly compatible with 32-bit, but) a totally different instruction set. This is especially important for graphics program (using NEON instructions and registers). Likewise, the CPU has more registers, which makes quite an impact on program speed. There's an interesting discussion in http://blogs.barrons.com/techtraderdaily/2013/09/19/apple-the-64-bit-question/?mod=yahoobarrons on whether or not this makes a difference; benchmarking tests have so far clearly indicated that it does.
Using otool -tV will dump the assembly (if you have XCode 5 and later), and then you can see the instruction set differences for yourself. Most (but not all) developers will remain agnostic to the changes, as for the most part they do not directly affect Obj-C (CG* APIs notwithstanding), and have to do more with low level pointer handling. The compiler will work its magic and optimizations.
Here you can find a simple explanation of currying implementation in C#. In the comments, I have tried to show how currying can be useful:
public static class FuncExtensions {
public static Func<T1, Func<T2, TResult>> Curry<T1, T2, TResult>(this Func<T1, T2, TResult> func)
{
return x1 => x2 => func(x1, x2);
}
}
//Usage
var add = new Func<int, int, int>((x, y) => x + y).Curry();
var func = add(1);
//Obtaining the next parameter here, calling later the func with next parameter.
//Or you can prepare some base calculations at the previous step and then
//use the result of those calculations when calling the func multiple times
//with different input parameters.
int result = func(1);
This discussion is missing out on the important point: The question is not if the "non-key-columns" are better to include as index-columns or as included-columns.
The question is how expensive it is to use the include-mechanism to include columns that are not really needed in index? (typically not part of where-clauses, but often included in selects). So your dilemma is always:
Where: id1, id2 ... idN are columns often used in restrictions and col1, col2 ... colN are columns often selected, but typically not used in restrictions
(The option to include all of these columns as part of the index-key is just always silly (unless they are also used in restrictions) - cause it would always be more expensive to maintain since the index must be updated and sorted even when the "keys" have not changed).
So use option 1 or 2?
Answer: If your table is rarely updated - mostly inserted into/deleted from - then it is relatively inexpensive to use the include-mechanism to include some "hot columns" (that are often used in selects - but not often used on restrictions) since inserts/deletes require the index to be updated/sorted anyway and thus little extra overhead is associated with storing off a few extra columns while already updating the index. The overhead is the extra memory and CPU used to store redundant info on the index.
If the columns you consider to add as included-columns are often updated (without the index-key-columns being updated) - or - if it is so many of them that the index becomes close to a copy of your table - use option 1 I'd suggest! Also if adding certain include-column(s) turns out to make no performance-difference - you might want to skip the idea of adding them:) Verify that they are useful!
The average number of rows per same values in keys (id1, id2 ... idN) can be of some importance as well.
Notice that if a column - that is added as an included-column of index - is used in the restriction: As long as the index as such can be used (based on restriction against index-key-columns) - then SQL Server is matching the column-restriction against the index (leaf-node-values) instead of going the expensive way around the table itself.
>>> import string
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
If you really need a list:
>>> list(string.ascii_lowercase)
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
And to do it with range
>>> list(map(chr, range(97, 123))) #or list(map(chr, range(ord('a'), ord('z')+1)))
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
Other helpful string
module features:
>>> help(string) # on Python 3
....
DATA
ascii_letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'
ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
digits = '0123456789'
hexdigits = '0123456789abcdefABCDEF'
octdigits = '01234567'
printable = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
punctuation = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
whitespace = ' \t\n\r\x0b\x0c'
If you don't mind an one-time investment of 10 to 30 minutes to get a reliable solution (that doesn't depend on Windows' region settings), please read on.
Let's free our minds. Do you want to simplify the scripts to just look like this? (Assume you wants to set the LOG_DATETIME variable)
FOR /F "tokens=* USEBACKQ" %%F IN (`FormatNow "yyyy-MM-dd"`) DO (
Set LOG_DATETIME=%%F
)
echo I am going to write log to Testing_%LOG_DATETIME%.log
You can. Simply build a FormatNow.exe with C# .NET and add it to your PATH.
Notes:
Benefits:
Source code of FormatNow.exe which I built with Visual Studio 2010 (I prefer to build it myself to avoid the risk of downloading an unknown, possibly malicious program). Just copy and paste the codes below, build the program once, and then you have a reliable date formatter for all future uses.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
namespace FormatNow
{
class Program
{
static void Main(string[] args)
{
try
{
if (args.Length < 1)
{
throw new ArgumentException("Missing format");
}
string format = args[0];
Console.Write(DateTime.Now.ToString(format, CultureInfo.InvariantCulture.DateTimeFormat));
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}
In general, when dealing with complicated logics, we can make it simpler for by building a very small program and calling the program to capture the output back to a batch script variable instead. We are not students and we're not taking exams requiring us to follow the batch-script-only rule to solve problems. In real working environment, any (legal) method is allowed. Why should we still stick to the poor capabilities of Windows batch script that needs workarounds for many simple tasks? Why should we use the wrong tool for the job?
I use this
var e = document.getElementById('ticket_category_clone').value;
Notice that you don't need the '#' character in javascript.
function check () {
var str = document.getElementById('ticket_category_clone').value;
if (str==="Hardware")
{
SPICEWORKS.utils.addStyle('#ticket_c_hardware_clone{display: none !important;}');
}
}
SPICEWORKS.app.helpdesk.ready(check);?
The interface however defines the size() method, which returns an int.
Returns the number of elements in this list. If this list contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE.
So, no limit, but after you reach Integer.MAX_VALUE, the behaviour of the list changes a bit
ArrayList (which is tagged) is backed by an array, and is limited to the size of the array - i.e. Integer.MAX_VALUE
Or use a +
, i.e.:
>>> print 'me'+'no'+'likee'+'spacees'+'pls'
menolikeespaceespls
Just make sure all are concatenate-able objects.
Select * from people p, address a where p.id = a.person_id and a.zip='97229';
Or you must TRY using JOIN
which is a more efficient and better way to do this as Gordon Linoff in the comments below also says that you need to learn this.
SELECT p.*, a.street, a.city FROM persons AS p
JOIN address AS a ON p.id = a.person_id
WHERE a.zip = '97299';
Here p.*
means it will show all the columns of PERSONS table.
reinterpret_cast
cannot be used for this conversion, the code will not compile. According to C++03 standard section 5.2.10-1:
Conversions that can be performed explicitly using reinterpret_cast are listed below. No other conversion can be performed explicitly using reinterpret_cast.
This conversion is not listed in that section. Even this is invalid:
long l = reinterpret_cast<long>(i)
static_cast
is the one which has to be used here. See this and this SO questions.
I've found this absolutely invaluable when unable to grab something in a custom class or changing id's:
driver.find_element_by_xpath("//*[contains(text(), 'Show Next Date Available')]").click()
driver.find_element_by_xpath("//*[contains(text(), 'Show Next Date Available')]").text
driver.find_element_by_xpath("//*[contains(text(), 'Available')]").text
driver.find_element_by_xpath("//*[contains(text(), 'Avail')]").text
How to break out in java??
Ans: Best way: System.exit(0);
Java language provides three jump statemnts that allow you to interrupt the normal flow of program.
These include break , continue ,return ,labelled break statement for e.g
import java.util.Scanner;
class demo
{
public static void main(String args[])
{
outerLoop://Label
for(int i=1;i<=10;i++)
{
for(int j=1;j<=i;j++)
{
for(int k=1;k<=j;k++)
{
System.out.print(k+"\t");
break outerLoop;
}
System.out.println();
}
System.out.println();
}
}
}
Output: 1
Now Note below Program:
import java.util.Scanner;
class demo
{
public static void main(String args[])
{
for(int i=1;i<=10;i++)
{
for(int j=1;j<=i;j++)
{
for(int k=1;k<=j;k++)
{
System.out.print(k+"\t");
break ;
}
}
System.out.println();
}
}
}
output:
1
11
111
1111
and so on upto
1111111111
Similarly you can use continue statement just replace break with continue in above example.
Things to Remember :
A case label cannot contain a runtime expressions involving variable or method calls
outerLoop:
Scanner s1=new Scanner(System.in);
int ans=s1.nextInt();
// Error s1 cannot be resolved
$('html, body').animate({scrollTop:1200},'50');
You can do this!
Solved it!!!
After searching for ages and trying all these other suggestions which didn't work, I finally found the solution for my setup.
My setup/scenario:
Solution
Remove any the folder named django in the same directory of manage.py
Thats right...as soon as I removed the folder "django" which only contained a __init__.py file...I could run the server again!
Have no idea why though
From the Javadocs for setDisplayOrientation(int)
(Requires API level 9):
public static void setCameraDisplayOrientation(Activity activity,
int cameraId, android.hardware.Camera camera) {
android.hardware.Camera.CameraInfo info =
new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo(cameraId, info);
int rotation = activity.getWindowManager().getDefaultDisplay()
.getRotation();
int degrees = 0;
switch (rotation) {
case Surface.ROTATION_0: degrees = 0; break;
case Surface.ROTATION_90: degrees = 90; break;
case Surface.ROTATION_180: degrees = 180; break;
case Surface.ROTATION_270: degrees = 270; break;
}
int result;
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 360;
result = (360 - result) % 360; // compensate the mirror
} else { // back-facing
result = (info.orientation - degrees + 360) % 360;
}
camera.setDisplayOrientation(result);
}
C++ language has no such thing as typeof
. You must be looking at some compiler-specific extension. If you are talking about GCC's typeof
, then a similar feature is present in C++11 through the keyword decltype
. Again, C++ has no such typeof
keyword.
typeid
is a C++ language operator which returns type identification information at run time. It basically returns a type_info
object, which is equality-comparable with other type_info
objects.
Note, that the only defined property of the returned type_info
object has is its being equality- and non-equality-comparable, i.e. type_info
objects describing different types shall compare non-equal, while type_info
objects describing the same type have to compare equal. Everything else is implementation-defined. Methods that return various "names" are not guaranteed to return anything human-readable, and even not guaranteed to return anything at all.
Note also, that the above probably implies (although the standard doesn't seem to mention it explicitly) that consecutive applications of typeid
to the same type might return different type_info
objects (which, of course, still have to compare equal).
Check the text contents of the connection manager file itself, the password field might be configured in the Project.params file, in which case entering the password into the connection manager window will cause it to not save.
The sized box will not help in the case, the phone is in landscape mode.
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Expanded(
child: Container(
margin: EdgeInsets.all(15.0),
decoration: BoxDecoration(
color: Color(0xFF1D1E33),
borderRadius: BorderRadius.circular(10.0),
),
),
),
Expanded(
child: Container(
margin: EdgeInsets.all(15.0),
decoration: BoxDecoration(
color: Color(0xFF1D1E33),
borderRadius: BorderRadius.circular(10.0),
),
),
),
Expanded(
child: Container(
margin: EdgeInsets.all(15.0),
decoration: BoxDecoration(
color: Color(0xFF1D1E33),
borderRadius: BorderRadius.circular(10.0),
),
),
),
],
)
It seems that for full page reload $window.location.href
is the preferred way.
It does not cause a full page reload when the browser URL is changed. To reload the page after changing the URL, use the lower-level API, $window.location.href.
There's a short overview at MinGW-w64 Wiki:
Why doesn't mingw-w64 gcc support Dwarf-2 Exception Handling?
The Dwarf-2 EH implementation for Windows is not designed at all to work under 64-bit Windows applications. In win32 mode, the exception unwind handler cannot propagate through non-dw2 aware code, this means that any exception going through any non-dw2 aware "foreign frames" code will fail, including Windows system DLLs and DLLs built with Visual Studio. Dwarf-2 unwinding code in gcc inspects the x86 unwinding assembly and is unable to proceed without other dwarf-2 unwind information.
The SetJump LongJump method of exception handling works for most cases on both win32 and win64, except for general protection faults. Structured exception handling support in gcc is being developed to overcome the weaknesses of dw2 and sjlj. On win64, the unwind-information are placed in xdata-section and there is the .pdata (function descriptor table) instead of the stack. For win32, the chain of handlers are on stack and need to be saved/restored by real executed code.
GCC GNU about Exception Handling:
GCC supports two methods for exception handling (EH):
- DWARF-2 (DW2) EH, which requires the use of DWARF-2 (or DWARF-3) debugging information. DW-2 EH can cause executables to be slightly bloated because large call stack unwinding tables have to be included in th executables.
- A method based on setjmp/longjmp (SJLJ). SJLJ-based EH is much slower than DW2 EH (penalising even normal execution when no exceptions are thrown), but can work across code that has not been compiled with GCC or that does not have call-stack unwinding information.
[...]
Structured Exception Handling (SEH)
Windows uses its own exception handling mechanism known as Structured Exception Handling (SEH). [...] Unfortunately, GCC does not support SEH yet. [...]
See also:
This is the snippet to store environment variable and access it.
node {
withEnv(["ENABLE_TESTS=true", "DISABLE_SQL=false"]) {
stage('Select Jenkinsfile') {
echo "Enable test?: ${env.DEVOPS_SKIP_TESTS}
customStep script: this
}
}
}
Note: The value of environment variable is coming as a String. If you want to use it as a boolean then you have to parse it using Boolean.parse(env.DISABLE_SQL).
Check out the function getClientRects() which can be used to count the number of lines in an element. Here is an example of how to use it.
var message_lines = $("#message_container")[0].getClientRects();
It returns a javascript DOM object. The amount of lines can be known by doing this:
var amount_of_lines = message_lines.length;
It can return the height of each line, and more. See the full array of things it can do by adding this to your script, then looking in your console log.
console.log("");
console.log("message_lines");
console.log(".............................................");
console.dir(message_lines);
console.log("");
Though a few things to note is it only works if the containing element is inline, however you can surround the containing inline element with a block element to control the width like so:
<div style="width:300px;" id="block_message_container">
<div style="display:inline;" id="message_container">
..Text of the post..
</div>
</div>
Though I don't recommend hard coding the style like that. It's just for example purposes.
supportActionBar?.title = "Hola tio"
supportActionBar?.subtitle = "Vamos colega!"
Could use the following and then explode the post result explode(",", $_POST['data']);
to give an array of results.
var data = new Array();
$("input[name='checkBoxesName']:checked").each(function(i) {
data.push($(this).val());
});
Run select query on same table with all where
conditions you are applying in update query.
For development you can disable password policy if no other profile was set (i.e. disable password expiration in default one):
ALTER PROFILE "DEFAULT" LIMIT PASSWORD_VERIFY_FUNCTION NULL;
Then, reset password and unlock user account. It should never expire again:
alter user user_name identified by new_password account unlock;
Requests doesn't have an equivalent to Urlib2's read()
.
>>> import requests
>>> response = requests.get("http://www.google.com")
>>> print response.content
'<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage"><head>....'
>>> print response.content == response.text
True
It looks like the POST request you are making is returning no content. Which is often the case with a POST request. Perhaps it set a cookie? The status code is telling you that the POST succeeded after all.
Edit for Python 3:
Python now handles data types differently. response.content
returns a sequence of bytes
(integers that represent ASCII) while response.text
is a string
(sequence of chars).
Thus,
>>> print response.content == response.text
False
>>> print str(response.content) == response.text
True
I like Raynos' solution as well, but I prefer a different flow control library.
https://github.com/caolan/async
Depending on whether you need the results in each subsequent function, I'd either use series, parallel, or waterfall.
Series when they have to be serially executed, but you don't necessarily need the results in each subsequent function call.
Parallel if they can be executed in parallel, you don't need the results from each during each parallel function, and you need a callback when all have completed.
Waterfall if you want to morph the results in each function and pass to the next
endpoints =
[{ host: 'www.example.com', path: '/api_1.php' },
{ host: 'www.example.com', path: '/api_2.php' },
{ host: 'www.example.com', path: '/api_3.php' }];
async.mapSeries(endpoints, http.get, function(results){
// Array of results
});
As per Basil Bourque's comment, this is the updated answer for this question, taking into account the new API of Java 8:
String myDateString = "13:24:40";
LocalTime localTime = LocalTime.parse(myDateString, DateTimeFormatter.ofPattern("HH:mm:ss"));
int hour = localTime.get(ChronoField.CLOCK_HOUR_OF_DAY);
int minute = localTime.get(ChronoField.MINUTE_OF_HOUR);
int second = localTime.get(ChronoField.SECOND_OF_MINUTE);
//prints "hour: 13, minute: 24, second: 40":
System.out.println(String.format("hour: %d, minute: %d, second: %d", hour, minute, second));
Remarks:
====== Below is the old (original) answer for this question, using pre-Java8 API: =====
I'm sorry if I'm gonna upset anyone with this, but I'm actually gonna answer the question. The Java API's are pretty huge, I think it's normal that someone might miss one now and then.
A SimpleDateFormat might do the trick here:
http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
It should be something like:
String myDateString = "13:24:40";
//SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
//the above commented line was changed to the one below, as per Grodriguez's pertinent comment:
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
Date date = sdf.parse(myDateString);
Calendar calendar = GregorianCalendar.getInstance(); // creates a new calendar instance
calendar.setTime(date); // assigns calendar to given date
int hour = calendar.get(Calendar.HOUR);
int minute; /... similar methods for minutes and seconds
The gotchas you should be aware of:
the pattern you pass to SimpleDateFormat might be different then the one in my example depending on what values you have (are the hours in 12 hours format or in 24 hours format, etc). Look at the documentation in the link for details on this
Once you create a Date object out of your String (via SimpleDateFormat), don't be tempted to use Date.getHour(), Date.getMinute() etc. They might appear to work at times, but overall they can give bad results, and as such are now deprecated. Use the calendar instead as in the example above.
This can happen if you forget to return a value from a function: it then returns None. Look at all places where you are assigning to that variable, and see if one of them is a function call where the function lacks a return statement.
You have two ways:
First go to the particular path of Android SDK:
1) Open your command prompt and traverse to the platform-tools directory through it such as
$ cd Frameworks\Android-Sdk\platform-tools
2) Run your adb commands now such as to know that your adb is working properly :
$ adb devices OR adb logcat OR simply adb
Second way is :
1) Right click on your My Computer.
2) Open Environment variables.
3) Add new variable to your System PATH variable(Add if not exist otherwise no need to add new variable if already exist).
4) Add path of platform-tools directory to as value of this variable such as C:\Program Files\android-sdk\platform-tools.
5) Restart your computer once.
6) Now run the above adb commands such adb devices or other adb commands from anywhere in command prompt.
Also on you can fire a command on terminal setx PATH "%PATH%;C:\Program Files\android-sdk\platform-tools"
The first way is easier to maintain. Each declaration is a single statement on a single line, so you can easily add, remove, and reorder the declarations.
With the second way, it is annoying to remove the first or last declaration because they start from the var
keyword and finish with the semicolon respectively. Every time you add a new declaration, you have to replace the semicolon in the last old line with a comma.
Use this function:
function getDatetimeNow() {
$tz_object = new DateTimeZone('Brazil/East');
//date_default_timezone_set('Brazil/East');
$datetime = new DateTime();
$datetime->setTimezone($tz_object);
return $datetime->format('Y\-m\-d\ h:i:s');
}
Old question but got here because I need to move content from one container to another including all the event listeners.
jQuery doesn't have a way to do it but standard DOM function appendChild does.
//assuming only one .source and one .target
$('.source').on('click',function(){console.log('I am clicked');});
$('.target')[0].appendChild($('.source')[0]);
Using appendChild removes the .source and places it into target including it's event listeners: https://developer.mozilla.org/en-US/docs/Web/API/Node.appendChild
<asp:Button ID="btnGet" runat="server" Text="Get" OnClick="btnGet_Click" OnClientClick="retun callMethod();" />
<script type="text/javascript">
function callMethod() {
//your logic should be here and make sure your logic code note returing function
return false;
}
</script>
And if recursion is usually slower what is the technical reason for ever using it over for loop iteration?
Because in some algorithms are hard to solve it iteratively. Try to solve depth-first search in both recursively and iteratively. You will get the idea that it is plain hard to solve DFS with iteration.
Another good thing to try out : Try to write Merge sort iteratively. It will take you quite some time.
Is it correct to say that everywhere recursion is used a for loop could be used?
Yes. This thread has a very good answer for this.
And if it is always possible to convert an recursion into a for loop is there a rule of thumb way to do it?
Trust me. Try to write your own version to solve depth-first search iteratively. You will notice that some problems are easier to solve it recursively.
Hint : Recursion is good when you are solving a problem that can be solved by divide and conquer technique.
I prefer to put it in the WPF code.
In [WindowName].xaml
file:
<Window x:Class=...
...
WindowStartupLocation ="CenterScreen">
The easiest way in my experiences is to just use Dumpvalue.
use Dumpvalue;
...
my %hash = { key => "value", foo => "bar" };
my $dumper = new DumpValue();
$dumper->dumpValue(\%hash);
Works like a charm and you don't have to worry about formatting the hash, as it outputs it like the Perl debugger does (great for debugging). Plus, Dumpvalue is included with the stock set of Perl modules, so you don't have to mess with CPAN if you're behind some kind of draconian proxy (like I am at work).
If you want to append to the file, open it with 'a'
. If you want to seek through the file to find the place where you should insert the line, use 'r+'
. (docs)
You can do this in Interface Builder.
Select the UIButton
you wish to set in IB
then go to the attributes inspector
.
In the screen shots,I am using a custom button type , but that does not matter.
I know the topic is quite old, but such tools are always handy. I've used the resources above and created a version of NtpClient which allows asynchronously to acquire accurate time, instead of event based.
/// <summary>
/// Represents a client which can obtain accurate time via NTP protocol.
/// </summary>
public class NtpClient
{
private readonly TaskCompletionSource<DateTime> _resultCompletionSource;
/// <summary>
/// Creates a new instance of <see cref="NtpClient"/> class.
/// </summary>
public NtpClient()
{
_resultCompletionSource = new TaskCompletionSource<DateTime>();
}
/// <summary>
/// Gets accurate time using the NTP protocol with default timeout of 45 seconds.
/// </summary>
/// <returns>Network accurate <see cref="DateTime"/> value.</returns>
public async Task<DateTime> GetNetworkTimeAsync()
{
return await GetNetworkTimeAsync(TimeSpan.FromSeconds(45));
}
/// <summary>
/// Gets accurate time using the NTP protocol with default timeout of 45 seconds.
/// </summary>
/// <param name="timeoutMs">Operation timeout in milliseconds.</param>
/// <returns>Network accurate <see cref="DateTime"/> value.</returns>
public async Task<DateTime> GetNetworkTimeAsync(int timeoutMs)
{
return await GetNetworkTimeAsync(TimeSpan.FromMilliseconds(timeoutMs));
}
/// <summary>
/// Gets accurate time using the NTP protocol with default timeout of 45 seconds.
/// </summary>
/// <param name="timeout">Operation timeout.</param>
/// <returns>Network accurate <see cref="DateTime"/> value.</returns>
public async Task<DateTime> GetNetworkTimeAsync(TimeSpan timeout)
{
using (var socket = new DatagramSocket())
using (var ct = new CancellationTokenSource(timeout))
{
ct.Token.Register(() => _resultCompletionSource.TrySetCanceled());
socket.MessageReceived += OnSocketMessageReceived;
//The UDP port number assigned to NTP is 123
await socket.ConnectAsync(new HostName("pool.ntp.org"), "123");
using (var writer = new DataWriter(socket.OutputStream))
{
// NTP message size is 16 bytes of the digest (RFC 2030)
var ntpBuffer = new byte[48];
// Setting the Leap Indicator,
// Version Number and Mode values
// LI = 0 (no warning)
// VN = 3 (IPv4 only)
// Mode = 3 (Client Mode)
ntpBuffer[0] = 0x1B;
writer.WriteBytes(ntpBuffer);
await writer.StoreAsync();
var result = await _resultCompletionSource.Task;
return result;
}
}
}
private void OnSocketMessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
{
try
{
using (var reader = args.GetDataReader())
{
byte[] response = new byte[48];
reader.ReadBytes(response);
_resultCompletionSource.TrySetResult(ParseNetworkTime(response));
}
}
catch (Exception ex)
{
_resultCompletionSource.TrySetException(ex);
}
}
private static DateTime ParseNetworkTime(byte[] rawData)
{
//Offset to get to the "Transmit Timestamp" field (time at which the reply
//departed the server for the client, in 64-bit timestamp format."
const byte serverReplyTime = 40;
//Get the seconds part
ulong intPart = BitConverter.ToUInt32(rawData, serverReplyTime);
//Get the seconds fraction
ulong fractPart = BitConverter.ToUInt32(rawData, serverReplyTime + 4);
//Convert From big-endian to little-endian
intPart = SwapEndianness(intPart);
fractPart = SwapEndianness(fractPart);
var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);
//**UTC** time
DateTime networkDateTime = (new DateTime(1900, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)).AddMilliseconds((long)milliseconds);
return networkDateTime;
}
// stackoverflow.com/a/3294698/162671
private static uint SwapEndianness(ulong x)
{
return (uint)(((x & 0x000000ff) << 24) +
((x & 0x0000ff00) << 8) +
((x & 0x00ff0000) >> 8) +
((x & 0xff000000) >> 24));
}
}
Usage:
var ntp = new NtpClient();
var accurateTime = await ntp.GetNetworkTimeAsync(TimeSpan.FromSeconds(10));
The problem is that count is intended to count the indexes in an array, not the properties on an object, (unless it's a custom object that implements the Countable interface). Try casting the object, like below, as an array and seeing if that helps.
$total = count((array)$obj);
Simply casting an object as an array won't always work but being a simple stdClass object it should get the job done here.
I had this noted from somewhere:
adding text-transform to input to remove it
input.button {
text-indent:-9999px;
text-transform:capitalize;
}
Those are "non-client" areas and are controlled by Windows. Here is the MSDN docs on the subject (the pertinent info is at the top).
Basically, you set your Window's WindowStyle="None", then build your own window interface. (similar question on SO)
You'll need to join twice:
SELECT home.*, away.*, g.network, g.date_start
FROM game AS g
INNER JOIN team AS home
ON home.importid = g.home
INNER JOIN team AS away
ON away.importid = g.away
ORDER BY g.date_start DESC
LIMIT 7
We can calculate using mid point of line formula,
centre (x,y) = new Point((boundRect.tl().x+boundRect.br().x)/2,(boundRect.tl().y+boundRect.br().y)/2)
Here's a way to do it: make your "topmost" window subscribe to your other windows GotFocus and LostFocus events and use the following as the event handlers:
class TopMostWindow
{
void OtherWindow_LostFocus(object sender, EventArgs e)
{
this.Topmost = false;
}
void OtherWindow_GotFocus(object sender, EventArgs e)
{
this.Topmost = true;
}
}
Add this to your main CSS:
table td {
border-top: none !important;
}
Use this for newer versions of bootstrap:
.table th, .table td {
border-top: none !important;
}
The solution provided by ebeneditos works perfectly.
But if you have cv2.imwrite()
in several sections of a large code snippet and you want to change the path where the images get saved, you will have to change the path at every occurrence of cv2.imwrite()
individually.
As Soltius stated, here is a better way. Declare a path and pass it as a string into cv2.imwrite()
import cv2
import os
img = cv2.imread('1.jpg', 1)
path = 'D:/OpenCV/Scripts/Images'
cv2.imwrite(os.path.join(path , 'waka.jpg'), img)
cv2.waitKey(0)
Now if you want to modify the path, you just have to change the path
variable.
Edited based on solution provided by Kallz
Following commands may solve your issue:
npm config set proxy false
npm cache clean
It solved my same issue.
In python3, The way :
dict.keys()
return a value in type : dict_keys(), we'll got an error when got 1st member of keys of dict by this way:
dict.keys()[0]
TypeError: 'dict_keys' object does not support indexing
Finally, I convert dict.keys() to list @1st, and got 1st member by list splice method:
list(dict.keys())[0]
To convert a String to a Long (object), use Long.valueOf(String s).longValue();
See link
From Guppy:
import geocoders
g = geocoders.GoogleV3()
place, (lat, lng) = g.geocode('Fairbanks')
print place, (lat, lng)
Fairbanks, AK, USA (64.8377778, -147.7163889)
timezone = g.timezone((lat, lng))
print timezone.dst
Bound method America/Anchorage.dst
of DstTzInfo
America/Anchorage' LMT-1 day, 14:00:00 STD
Building off of Mamboking's answer:
ContractsDao mock_contractsDao = mock(ContractsDao.class);
when(mock_contractsDao.save(anyString())).thenReturn("Some result");
m_orderSvc.m_contractsDao = mock_contractsDao;
m_prog = new ProcessOrdersWorker(m_orderSvc, m_opportunitySvc, m_myprojectOrgSvc);
m_prog.work();
Addressing your request to verify whether the argument contains a certain value, I could assume you mean that the argument is a String and you want to test whether the String argument contains a substring. For this you could do:
ArgumentCaptor<String> savedCaptor = ArgumentCaptor.forClass(String.class);
verify(mock_contractsDao).save(savedCaptor.capture());
assertTrue(savedCaptor.getValue().contains("substring I want to find");
If that assumption was wrong, and the argument to save()
is a collection of some kind, it would be only slightly different:
ArgumentCaptor<Collection<MyType>> savedCaptor = ArgumentCaptor.forClass(Collection.class);
verify(mock_contractsDao).save(savedCaptor.capture());
assertTrue(savedCaptor.getValue().contains(someMyTypeElementToFindInCollection);
You might also check into ArgumentMatchers, if you know how to use Hamcrest matchers.
First you need to remember that in Unix and Linux, everything is a file, even directories. For a file to have the rights to be executed as a command, it needs to satisfy 3 conditions:
So this can be done simply with:
[ -f "${file}" ] && [ -r "${file}" ] && [ -x "${file}" ]
If your file is a symbolic link to a regular file, the test command will operate on the target and not the link-name. So the above command distinguishes if a file can be used as a command or not. So there is no need to pass the file first to realpath
or readlink
or any of those variants.
If the file can be executed on the current OS, that is a different question. Some answers above already pointed to some possibilities for that, so there is no need to repeat it here.
I've got this, which is working in FF3, IE6 & 7. The methods in the on-demand loaded scripts aren't available until page load is complete, but this is still very useful.
//handle on-demand loading of javascripts
makescript = function(url){
var v = document.createElement('script');
v.src=url;
v.type='text/javascript';
//insertAfter. Get last <script> tag in DOM
d=document.getElementsByTagName('script')[(document.getElementsByTagName('script').length-1)];
d.parentNode.insertBefore( v, d.nextSibling );
}
Here is an implementation of the Permutation in Java:
You should have a check on it!
Edit: code pasted below to protect against link-death:
// Permute.java -- A class generating all permutations
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.lang.reflect.Array;
public class Permute implements Iterator {
private final int size;
private final Object [] elements; // copy of original 0 .. size-1
private final Object ar; // array for output, 0 .. size-1
private final int [] permutation; // perm of nums 1..size, perm[0]=0
private boolean next = true;
// int[], double[] array won't work :-(
public Permute (Object [] e) {
size = e.length;
elements = new Object [size]; // not suitable for primitives
System.arraycopy (e, 0, elements, 0, size);
ar = Array.newInstance (e.getClass().getComponentType(), size);
System.arraycopy (e, 0, ar, 0, size);
permutation = new int [size+1];
for (int i=0; i<size+1; i++) {
permutation [i]=i;
}
}
private void formNextPermutation () {
for (int i=0; i<size; i++) {
// i+1 because perm[0] always = 0
// perm[]-1 because the numbers 1..size are being permuted
Array.set (ar, i, elements[permutation[i+1]-1]);
}
}
public boolean hasNext() {
return next;
}
public void remove() throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
private void swap (final int i, final int j) {
final int x = permutation[i];
permutation[i] = permutation [j];
permutation[j] = x;
}
// does not throw NoSuchElement; it wraps around!
public Object next() throws NoSuchElementException {
formNextPermutation (); // copy original elements
int i = size-1;
while (permutation[i]>permutation[i+1]) i--;
if (i==0) {
next = false;
for (int j=0; j<size+1; j++) {
permutation [j]=j;
}
return ar;
}
int j = size;
while (permutation[i]>permutation[j]) j--;
swap (i,j);
int r = size;
int s = i+1;
while (r>s) { swap(r,s); r--; s++; }
return ar;
}
public String toString () {
final int n = Array.getLength(ar);
final StringBuffer sb = new StringBuffer ("[");
for (int j=0; j<n; j++) {
sb.append (Array.get(ar,j).toString());
if (j<n-1) sb.append (",");
}
sb.append("]");
return new String (sb);
}
public static void main (String [] args) {
for (Iterator i = new Permute(args); i.hasNext(); ) {
final String [] a = (String []) i.next();
System.out.println (i);
}
}
}
For arbitrary, potentially large number of optional parameters, a nice idiom is to use Functional options.
For your type Foobar
, first write only one constructor:
func NewFoobar(options ...func(*Foobar) error) (*Foobar, error){
fb := &Foobar{}
// ... (write initializations with default values)...
for _, op := range options{
err := op(fb)
if err != nil {
return nil, err
}
}
return fb, nil
}
where each option is a function which mutates the Foobar. Then provide convenient ways for your user to use or create standard options, for example :
func OptionReadonlyFlag(fb *Foobar) error {
fb.mutable = false
return nil
}
func OptionTemperature(t Celsius) func(*Foobar) error {
return func(fb *Foobar) error {
fb.temperature = t
return nil
}
}
For conciseness, you may give a name to the type of the options (Playground) :
type OptionFoobar func(*Foobar) error
If you need mandatory parameters, add them as first arguments of the constructor before the variadic options
.
The main benefits of the Functional options idiom are :
This technique was coined by Rob Pike and also demonstrated by Dave Cheney.
SQL Compare by RedGate http://www.red-gate.com/products/SQL_Compare/index.htm
DBDeploy to help with database change management in an automated fashion http://dbdeploy.com/
Use the CSS pointer-events:none on fields you want to "disable" (possibly together with a greyed background) which allows the POST action, like:
<input type="text" class="disable">
.disable{
pointer-events:none;
background:grey;
}
Ref: https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events
Most answers don't work when debugging in the following IDEs:
Because in those the $PSScriptRoot
is empty and Resolve-Path .\
(and similars) will result in incorrect paths.
Freakydinde's answer is the only one that resolves those situations, so I up-voted that, but I don't think the Set-Location
in that answer is really what is desired. So I fixed that and made the code a little clearer:
$directorypath = if ($PSScriptRoot) { $PSScriptRoot } `
elseif ($psise) { split-path $psise.CurrentFile.FullPath } `
elseif ($psEditor) { split-path $psEditor.GetEditorContext().CurrentFile.Path }
Make sure that nothing is interfering with your app files (specially in Windows), in my case this problem arise due to a text editor that was holding some XML file and Android Studio wasn't able to modify it.
If you want to avoid a DirectoryNotFoundException
you will need to ensure that the directory of the file does indeed exist. File.Exists
accomplishes this. Another way would be to utilize the Path
and Directory
utility classes like so:
string file = @"C:\subfolder\test.txt";
if (Directory.Exists(Path.GetDirectoryName(file)))
{
File.Delete(file);
}
The accepted answer succeeds quickly but is very slow to fail when there is no connection. So I wanted to build a robust connection check that would fail faster.
Pinging was said to not be supported in all environments, so I started with the accepted answer and added a WebClient from here with a custom timeout. You can pick any timeout, but 3 seconds worked for me while connected via wifi. I tried adding a fast iteration (1 second), then a slow iteration (3 seconds) if the first one fails. But that made no sense since both iterations would always fail (when not connected) or always succeed (when connected).
I'm connecting to AWS since I want to upload a file when the connection test passes.
public static class AwsHelpers
{
public static bool GetCanConnectToAws()
{
try
{
using (var client = new WebClientWithShortTimeout())
using (client.OpenRead("https://aws.amazon.com"))
return true;
}
catch
{
return false;
}
}
}
public class WebClientWithShortTimeout: WebClient
{
protected override WebRequest GetWebRequest(Uri uri)
{
var webRequest = base.GetWebRequest(uri);
webRequest.Timeout = 5000;
return webRequest;
}
}
Correct expression is
"source " + (DT_STR,4,1252)DATEPART( "yyyy" , getdate() ) + "-" +
RIGHT("0" + (DT_STR,4,1252)DATEPART( "mm" , getdate() ), 2) + "-" +
RIGHT("0" + (DT_STR,4,1252)DATEPART( "dd" , getdate() ), 2) +".CSV"
As mentioned in many sites, there are various reasons for this. For me it was due to the length of Source and Destination (Path length). I tried xcopy in the command prompt and I was unable to type the complete source and path (after some characters it wont allow you to type). I then reduced the path length and was able to run. Hope this helps.
You need to make the second element a 1-tuple, eg:
a = ('2',)
b = 'z'
new = a + (b,)
^
for start of the string pattern,
?
for allowing 0 or 1 time repeat. ie., s?
s can exist 1 time or no need to exist at all.
/
is a special character in regex so it needs to be escaped by a backslash \/
/^https?:\/\//.test('https://www.bbc.co.uk/sport/cricket'); // true
/^https?:\/\//.test('http://www.bbc.co.uk/sport/cricket'); // true
/^https?:\/\//.test('ftp://www.bbc.co.uk/sport/cricket'); // false
May be you created a new xml file in Layout Directory that file name containing a Capital Letter which is not allowed in xml file under Layout Directory.
Hope this help.
"Assuming that you have nodejs installed",
mini-http is a pretty easy command-line tool to create http server,
install the package globally npm install mini-http -g
then using your cmd (terminal) run mini-http -p=3000
in your project directory
And boom! you created a server on port 3000 now go check http://localhost:3000
Note: specifying a port is not required you can simply run mini-http
or mh
to start the server
You are facing issue in
s1.name="Paolo";
because, in the LHS, you're using an array type, which is not assignable.
To elaborate, from C11
, chapter §6.5.16
assignment operator shall have a modifiable lvalue as its left operand.
and, regarding the modifiable lvalue, from chapter §6.3.2.1
A modifiable lvalue is an lvalue that does not have array type, [...]
You need to use strcpy()
to copy into the array.
That said, data s1 = {"Paolo", "Rossi", 19};
works fine, because this is not a direct assignment involving assignment operator. There we're using a brace-enclosed initializer list to provide the initial values of the object. That follows the law of initialization, as mentioned in chapter §6.7.9
Each brace-enclosed initializer list has an associated current object. When no designations are present, subobjects of the current object are initialized in order according to the type of the current object: array elements in increasing subscript order, structure members in declaration order, and the first named member of a union.[....]
Excel 2003, doesn't included 1M row features, Introduced in 2007 onwards.
In Excel2007, save as "normal" Excel file, not a backwards compatible one.
You may have to close and re-open Excel to get the full 1M rows
Thilip
function Map() {
this.keys = new Array();
this.data = new Object();
this.put = function (key, value) {
if (this.data[key] == null) {
this.keys.push(key);
}
this.data[key] = value;
};
this.get = function (key) {
return this.data[key];
};
this.remove = function (key) {
this.keys.remove(key);
this.data[key] = null;
};
this.each = function (fn) {
if (typeof fn != 'function') {
return;
}
var len = this.keys.length;
for (var i = 0; i < len; i++) {
var k = this.keys[i];
fn(k, this.data[k], i);
}
};
this.entrys = function () {
var len = this.keys.length;
var entrys = new Array(len);
for (var i = 0; i < len; i++) {
entrys[i] = {
key: this.keys[i],
value: this.data[i]
};
}
return entrys;
};
this.isEmpty = function () {
return this.keys.length == 0;
};
this.size = function () {
return this.keys.length;
};
}
Check via Google, there are lots of examples, see here for one.
Inlined for ease of viewing:
import win32com.client
def send_mail_via_com(text, subject, recipient, profilename="Outlook2003"):
s = win32com.client.Dispatch("Mapi.Session")
o = win32com.client.Dispatch("Outlook.Application")
s.Logon(profilename)
Msg = o.CreateItem(0)
Msg.To = recipient
Msg.CC = "moreaddresses here"
Msg.BCC = "address"
Msg.Subject = subject
Msg.Body = text
attachment1 = "Path to attachment no. 1"
attachment2 = "Path to attachment no. 2"
Msg.Attachments.Add(attachment1)
Msg.Attachments.Add(attachment2)
Msg.Send()
Please Try This one:
Try Adding input
Css like this:
-webkit-appearance: none;
border-radius: 0;
I was able to get Jenkins to build a tag by setting the Refspec and Branch Specifier as detailed in this blog post.
I also had to set the Repository Name (to "origin" in my case) so that I could reference it in the Refspec (otherwise it would apparently use a randomly generated name).
CSS word-wrap:break-word;
, tested in FireFox 3.6.3
You can enable and disable the submit button based on the javascript validation below is the validation code. Working Example Here
<script>
function validate() {
var valid = true;
valid = checkEmpty($("#name"));
valid = valid && checkEmail($("#email"));
$("#san-button").attr("disabled",true);
if(valid) {
$("#san-button").attr("disabled",false);
}
}
function checkEmpty(obj) {
var name = $(obj).attr("name");
$("."+name+"-validation").html("");
$(obj).css("border","");
if($(obj).val() == "") {
$(obj).css("border","#FF0000 1px solid");
$("."+name+"-validation").html("Required");
return false;
}
return true;
}
function checkEmail(obj) {
var result = true;
var name = $(obj).attr("name");
$("."+name+"-validation").html("");
$(obj).css("border","");
result = checkEmpty(obj);
if(!result) {
$(obj).css("border","#FF0000 1px solid");
$("."+name+"-validation").html("Required");
return false;
}
var email_regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,3})+$/;
result = email_regex.test($(obj).val());
if(!result) {
$(obj).css("border","#FF0000 1px solid");
$("."+name+"-validation").html("Invalid");
return false;
}
return result;
}
</script>
var methods = [];
for (var m in obj) {
if (typeof obj[m] == "function") {
methods.push(m);
}
}
alert(methods.join(","));
This way, you will get all methods that you can call on obj
. This includes the methods that it "inherits" from its prototype (like getMethods()
in java). If you only want to see those methods defined directly by obj
you can check with hasOwnProperty
:
var methods = [];
for (var m in obj) {
if (typeof obj[m] == "function" && obj.hasOwnProperty(m)) {
methods.push(m);
}
}
alert(methods.join(","));
You can use double quotes instead of single quotes:
theAnchorText = "I'm home";
Alternatively, escape the apostrophe:
theAnchorText = 'I\'m home';
The backslash tells JavaScript (this has nothing to do with jQuery, by the way) that the next character should be interpreted as "special". In this case, an apostrophe after a backslash means to use a literal apostrophe but not to end the string.
There are also other characters you can put after a backslash to indicate other special characters. For example, you can use \n
for a new line, or \t
for a tab.
None of the solutions above worked for me. This one works for me:
$(document).ready(function()
{
$('body').tooltip({
selector: '[data-toggle="tooltip"]',
html: true
});
});
You can write like this:
span{
margin-left:10px;
}
span:first-child{
margin-left:0;
}
If you want to use std::string
reliably, you must #include <string>
.
I'm not sure how necessary this is, and it adds a call to getElementById
, but if you're really keen on getting inline JavaScript out of your code, you can pass it as an HTML attribute, namely:
<span class="metadata" id="metadata-size-of-widget" title="<?php echo json_encode($size_of_widget) ?>"></span>
And then in your JavaScript:
var size_of_widget = document.getElementById("metadata-size-of-widget").title;
From the docs:
"a UNIQUE index permits multiple NULL values for columns that can contain NULL"
This applies to all engines but BDB.
Have you tried creating a windows shortcut for sql plus and set the working directory?
Try this:
//Vista or higher check
if (System.Environment.OSVersion.Version.Major >= 6)
{
p.StartInfo.Verb = "runas";
}
Alternatively, go the manifest route for your application.
You have a bug right there
result = methodInfo.Invoke(methodInfo, parametersArray);
it should be
result = methodInfo.Invoke(classInstance, parametersArray);
You should use jquery validation because if you use type="number"
then you can also enter "E" character in input type, which is not correct.
Solution:
HTML
<input class="form-control floatNumber" name="energy1_total_power_generated" type="text" required="" >
JQuery
//integer value validation
$('input.floatNumber').on('input', function() {
this.value = this.value.replace(/[^0-9.]/g,'').replace(/(\..*)\./g, '$1');
});
I had tried to change SDK Version:
Check below image: In that I changed 27 from Android P
Adding more to Jason's more generalized way of retrieving the POST data or GET data
from flask_restful import reqparse
def parse_arg_from_requests(arg, **kwargs):
parse = reqparse.RequestParser()
parse.add_argument(arg, **kwargs)
args = parse.parse_args()
return args[arg]
form_field_value = parse_arg_from_requests('FormFieldValue')
Week 1 is defined as being the week that starts on a Monday and contains the first Thursday of the year.
Swift 3:
//This gives month as three letters (Jun, Dec, etc)
let justMonth = DateFormatter()
justMonth.dateFormat = "MMM"
myFirstLabel.text = justMonth.string(from: myDate)
//This gives the day of month, with no preceding 0s (6,14,29)
let justDay = DateFormatter()
justDay.dateFormat = "d"
mySecondLabel.text = justDay.string(from: myDate)
//This gives year as two digits, preceded by an apostrophe ('09, '16, etc)
let justYear = DateFormatter()
justYear.dateFormat = "yy"
myThirdLabel.text = "'\(justYear.string(from: lastCompDate))"
For more formats, check out this link to a codingExplorer table with all the available formats. Each date component has several options, for example:
Year:
Pretty much every component has 2-4 options, using the first letter to express the format (day is "d", hour is "h", etc). However, month is a capital "M", because the lower case "m" is reserved for minute. There are some other exceptions though, so check out the link!
It can be detected by storing the previous scrollTop
value and comparing the current scrollTop value with it.
JavaScript :
var lastScrollTop = 0;
// element should be replaced with the actual target element on which you have applied scroll, use window in case of no target element.
element.addEventListener("scroll", function(){ // or window.addEventListener("scroll"....
var st = window.pageYOffset || document.documentElement.scrollTop; // Credits: "https://github.com/qeremy/so/blob/master/so.dom.js#L426"
if (st > lastScrollTop){
// downscroll code
} else {
// upscroll code
}
lastScrollTop = st <= 0 ? 0 : st; // For Mobile or negative scrolling
}, false);
In A1 of your new sheet, put this:
=OFFSET(Sheet1!$A$1,(ROW()-1)*7,0)
... and copy down. If you start somewhere other than row 1, change ROW() to ROW(A1) or some other cell on row 1, then copy down again.
If you want to copy the nth line but multiple columns, use the formula:
=OFFSET(Sheet1!A$1,(ROW()-1)*7,0)
This can be copied right too.
I would suggest using String.format() if you need the value as a String
in your code.
For example, you can use String.format()
in the following way:
float myFloat = 2.001f;
String formattedString = String.format("%.02f", myFloat);
Here's one I made on a 1 Million point set with 3 categories (colored Red, Green, and Blue). Here's a link to the repository if you'd like to try the function. Github Repo
histplot(
X,
Y,
labels,
bins=2000,
range=((-3,3),(-3,3)),
normalize_each_label=True,
colors = [
[1,0,0],
[0,1,0],
[0,0,1]],
gain=50)
php.ini
extension_dir=C:\path\to\server\php\ext
is set and adjust the path (set your PHP extension dir)extension=php_mbstring.dll
is set (uncommented)If this doesn't work and the php_mbstring.dll file is missing, then the PHP installation of this stack is simply broken.
If you have a SOCK_STREAM
socket, recv
just gets "up to the first 3000 bytes" from the stream. There is no clear guidance on how big to make the buffer: the only time you know how big a stream is, is when it's all done;-).
If you have a SOCK_DGRAM
socket, and the datagram is larger than the buffer, recv
fills the buffer with the first part of the datagram, returns -1, and sets errno to EMSGSIZE. Unfortunately, if the protocol is UDP, this means the rest of the datagram is lost -- part of why UDP is called an unreliable protocol (I know that there are reliable datagram protocols but they aren't very popular -- I couldn't name one in the TCP/IP family, despite knowing the latter pretty well;-).
To grow a buffer dynamically, allocate it initially with malloc
and use realloc
as needed. But that won't help you with recv
from a UDP source, alas.
SELECT *
FROM table_name
WHERE CONCAT( SUBSTRING(json_date, 11, 4 ) , '-', SUBSTRING( json_date, 7, 2 ) , '-', SUBSTRING( json_date, 3, 2 ) ) >= NOW();
In short you have to do like this
repositories {
maven { url "http://maven.springframework.org/release" }
maven { url "https://maven.fabric.io/public" }
}
Detail:
You need to specify each maven URL in its own curly braces. Here is what I got working with skeleton dependencies for the web services project I’m going to build up:
apply plugin: 'java'
sourceCompatibility = 1.7
version = '1.0'
repositories {
maven { url "http://maven.springframework.org/release" }
maven { url "http://maven.restlet.org" }
mavenCentral()
}
dependencies {
compile group:'org.restlet.jee', name:'org.restlet', version:'2.1.1'
compile group:'org.restlet.jee', name:'org.restlet.ext.servlet',version.1.1'
compile group:'org.springframework', name:'spring-web', version:'3.2.1.RELEASE'
compile group:'org.slf4j', name:'slf4j-api', version:'1.7.2'
compile group:'ch.qos.logback', name:'logback-core', version:'1.0.9'
testCompile group:'junit', name:'junit', version:'4.11'
}
This is the is simplest solution that worked for me.
<div
contentEditable='true'
onInput={e => console.log('Text inside div', e.currentTarget.textContent)}
>
Text inside div
</div>
By using itemStateChanged(ItemListener)
you can track selecting and deselecting checkbox (and do whatever you want based on it):
myCheckBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED) {//checkbox has been selected
//do something...
} else {//checkbox has been deselected
//do something...
};
}
});
Java Swing itemStateChanged docu should help too. By using isSelected()
method you can just test if actual is checkbox selected:
if(myCheckBox.isSelected()){_do_something_if_selected_}
Use getattr
to get an attribute from a name in a string. In other words, get the instance as
instance = getattr(modul, class_name)()
You can use method reference like this:
user.ifPresent(ClassNameWhereMethodIs::doSomethingWithUser);
Method ifPresent()
get Consumer
object as a paremeter and (from JavaDoc): "If a value is present, invoke the specified consumer with the value." Value it is your variable user
.
Or if this method doSomethingWithUser
is in the User
class and it is not static
, you can use method reference like this:
user.ifPresent(this::doSomethingWithUser);
It's used to load modules. Let's use a simple example.
In file circle_object.js
:
var Circle = function (radius) {
this.radius = radius
}
Circle.PI = 3.14
Circle.prototype = {
area: function () {
return Circle.PI * this.radius * this.radius;
}
}
We can use this via require
, like:
node> require('circle_object')
{}
node> Circle
{ [Function] PI: 3.14 }
node> var c = new Circle(3)
{ radius: 3 }
node> c.area()
The require()
method is used to load and cache JavaScript modules. So, if you want to load a local, relative JavaScript module into a Node.js application, you can simply use the require()
method.
Example:
var yourModule = require( "your_module_name" ); //.js file extension is optional