$("form").submit(function(event) {_x000D_
_x000D_
var firstfield_value = event.currentTarget[0].value;_x000D_
_x000D_
var secondfield_value = event.currentTarget[1].value; _x000D_
_x000D_
alert(firstfield_value);_x000D_
alert(secondfield_value);_x000D_
event.preventDefault(); _x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form action="" method="post" >_x000D_
<input type="text" name="field1" value="value1">_x000D_
<input type="text" name="field2" value="value2">_x000D_
</form>
_x000D_
Current answers are perfectly correct on how to create the aggregations, but none actually address the column alias/renaming that is also requested in the question.
Typically, this is how I handle this case:
val dimensionFields = List("col1")
val metrics = List("col2", "col3", "col4")
val columnOfInterests = dimensions ++ metrics
val df = spark.read.table("some_table").
.select(columnOfInterests.map(c => col(c)):_*)
.groupBy(dimensions.map(d => col(d)): _*)
.agg(metrics.map( m => m -> "sum").toMap)
.toDF(columnOfInterests:_*) // that's the interesting part
The last line essentially renames every columns of the aggregated dataframe to the original fields, essentially changing sum(col2)
and sum(col3)
to simply col2
and col3
.
Try this:
wget -nd -r -P /save/location -A jpeg,jpg,bmp,gif,png http://www.somedomain.com
Here is some more information:
-nd
prevents the creation of a directory hierarchy (i.e. no directories).
-r
enables recursive retrieval. See Recursive Download for more information.
-P
sets the directory prefix where all files and directories are saved to.
-A
sets a whitelist for retrieving only certain file types. Strings and patterns are accepted, and both can be used in a comma separated list (as seen above). See Types of Files for more information.
Using regex is a solution, but it is too complicated for that case.
You can simply split text into list of words. Use split(separator, num) method for that. It returns a list of all the words in the string, using separator as the separator. If separator is unspecified it splits on all whitespace (optionally you can limit the number of splits to num).
list_of_words = mystring.split()
if word in list_of_words:
print 'success'
This will not work for string with commas etc. For example:
mystring = "One,two and three"
# will split into ["One,two", "and", "three"]
If you also want to split on all commas etc. use separator argument like this:
# whitespace_chars = " \t\n\r\f" - space, tab, newline, return, formfeed
list_of_words = mystring.split( \t\n\r\f,.;!?'\"()")
if word in list_of_words:
print 'success'
json
is a built-in module, you don't need to install it with pip
.
Hope this helps;
df1 = data.frame(CustomerId=c(1:10),
Hobby = c(rep("sing", 4), rep("pingpong", 3), rep("hiking", 3)),
Product=c(rep("Toaster",3),rep("Phone", 2), rep("Radio",3), rep("Stereo", 2)))
df2 = data.frame(CustomerId=c(2,4,6, 8, 10),State=c(rep("Alabama",2),rep("Ohio",1), rep("Cal", 2)),
like=c("sing", 'hiking', "pingpong", 'hiking', "sing"))
df3 = merge(df1, df2, by.x=c("CustomerId", "Hobby"), by.y=c("CustomerId", "like"))
Assuming df1$Hobby
and df2$like
mean the same thing.
Short (un-precise) definition:
Compiled language: Entire program is translated to machine code at once, then the machine code is run by the CPU.
Interpreted language: Program is read line-by-line and as soon as a line is read the machine instructions for that line are executed by the CPU.
But really, few languages these days are purely compiled or purely interpreted, it often is a mix. For a more detailed description with pictures, see this thread:
What is the difference between compilation and interpretation?
Or my later blog post:
https://orangejuiceliberationfront.com/the-difference-between-compiler-and-interpreter/
Had the same issue and just figured, website is running under MAMP's php, but when you call in command, it runs mac's(if no bash path modified). you will have issue when mac doesn't have those extensions.
run php -i to find out loaded extensions, and install those one you missed. or run '/Applications/MAMP/bin/php/php5.3.6/bin/php artisan {your command}' to use MAMP's
This works for input coming from a textarea
str.replace(new RegExp('\r?\n','g'), '<br />');
You Need to take same height and width
and simply use the border-radius:360px;
Here is what made the error disappear for me:
Close eclipse, open up a terminal window and run:
$ mvn clean eclipse:clean eclipse:eclipse
Are you using Maven? If so,
To add it: Right-click on the project, Maven → Disable Maven Nature Right-click on the project, Configure → Convert to Maven Project.
And then clean
Edit 1:
If that doesn't resolve the issue try right-clicking on your project and select properties. Select Java Build Path → Library tab. Look for a JVM. If it's not there, click to add Library and add the default JVM. If VM is there, click edit and select the default JVM. Hopefully, that works.
Edit 2:
You can also try going into the folder where you have all your projects and delete the .metadata
for eclipse (be aware that you'll have to re-import all the projects afterwards! Also all the environment settings you've set would also have to be redone). After it was deleted just import the project again, and hopefully, it works.
Oracle 10g Express Edition ships with Oracle Application Express (Apex) built-in. You're running this in its SQL Commands window, which doesn't support SQL*Plus syntax.
That doesn't matter, because (as you have discovered) the BEGIN...END syntax does work in Apex.
I would agree with most of the answers saying that its a browser settings but still you can achieve what you want via COM. Keep in mind that most browsers will still have issue with that and even IE will raise the COM security bar to users. So unless its not something you are offering within organisation, don't do it.
Your function is failing because the groupby dataframe you end up with has a hierarchical index and two columns (Letter and N) so when you do .hist()
it's trying to make a histogram of both columns hence the str error.
This is the default behavior of pandas plotting functions (one plot per column) so if you reshape your data frame so that each letter is a column you will get exactly what you want.
df.reset_index().pivot('index','Letter','N').hist()
The reset_index()
is just to shove the current index into a column called index
. Then pivot
will take your data frame, collect all of the values N
for each Letter
and make them a column. The resulting data frame as 400 rows (fills missing values with NaN
) and three columns (A, B, C
). hist()
will then produce one histogram per column and you get format the plots as needed.
There is a shell option cdable_vars
:
cdable_vars
If this is set, an argument to thecd
builtin command that is not a directory is assumed to be the name of a variable whose value is the directory to change to.
You could add this to your .bashrc
:
shopt -s cdable_vars
export myFold=$HOME/Files/Scripts/Main
Notice that I've replaced the tilde with $HOME
; quotes prevent tilde expansion and Bash would complain that there is no directory ~/Files/Scripts/Main
.
Now you can use this as follows:
cd myFold
No $
required. That's the whole point, actually – as shown in other answers, cd "$myFold"
works without the shell option. cd myFold
also works if the path in myFold
contains spaces, no quoting required.
This usually even works with tab autocompletion as the _cd
function in bash_completion
checks if cdable_vars
is set – but not every implementation does it in the same manner, so you might have to source bash_completion
again in your .bashrc
(or edit /etc/profile
to set the shell option).
Other shells have similar options, for example Zsh (cdablevars
).
Its nothing more easy.
run command: ./gradlew clean -PjobId=9999
and
in gradle use: println(project.gradle.startParameter.projectProperties)
You will get clue.
ScheduledExecutorService
over Timer
I wish to offer you an alternative to Timer
using - ScheduledThreadPoolExecutor, an implementation of the ScheduledExecutorService interface. It has some advantages over the Timer class, according to "Java in Concurrency":
A
Timer
creates only a single thread for executing timer tasks. If a timer task takes too long to run, the timing accuracy of otherTimerTask
can suffer. If a recurringTimerTask
is scheduled to run every 10 ms and another Timer-Task takes 40 ms to run, the recurring task either (depending on whether it was scheduled at fixed rate or fixed delay) gets called four times in rapid succession after the long-running task completes, or "misses" four invocations completely. Scheduled thread pools address this limitation by letting you provide multiple threads for executing deferred and periodic tasks.
Another problem with Timer is that it behaves poorly if a TimerTask
throws an unchecked exception. Also, called "thread leakage"
The Timer thread doesn't catch the exception, so an unchecked exception thrown from a
TimerTask
terminates the timer thread. Timer also doesn't resurrect the thread in this situation; instead, it erroneously assumes the entire Timer was cancelled. In this case, TimerTasks that are already scheduled but not yet executed are never run, and new tasks cannot be scheduled.
And another recommendation if you need to build your own scheduling service, you may still be able to take advantage of the library by using a DelayQueue
, a BlockingQueue
implementation that provides the scheduling functionality of ScheduledThreadPoolExecutor
. A DelayQueue
manages a collection of Delayed objects. A Delayed has a delay time associated with it: DelayQueue
lets you take an element only if its delay has expired. Objects are returned from a DelayQueue
ordered by the time associated with their delay.
Props can change when a component's parent renders the component again with different properties. I think this is mostly an optimization so that no new component needs to be instantiated.
>>> a = ()
>>> type(a)
<type 'tuple'>
>>> a = []
>>> type(a)
<type 'list'>
>>> a = {}
>>> type(a)
<type 'dict'>
>>> a = ['Stem', 'constitute', 'Sedge', 'Eflux', 'Whim', 'Intrigue']
>>> a.sort()
>>> a
['Eflux', 'Intrigue', 'Sedge', 'Stem', 'Whim', 'constitute']
>>>
You may be trying to use a JSON object:
var myMappings = { "name": "10%", "phone": "10%", "address": "50%", etc.. }
To access:
myMappings.name;
myMappings.phone;
etc..
you can also use textbox events -
<input id="txt1" type="text" onchange="SetDefault($(this).val());" onkeyup="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();">
function SetDefault(Text){
alert(Text);
}
The reason is that in your second example i
is the word itself, not the index of the word. So
for w1 in words:
if w1[0] == w1[len(w1) - 1]:
c += 1
print c
would the equivalent of your code.
If you can count on having a period of time where the table is in a stable state with no new inserts going on, this should do it (untested):
DECLARE
last_used NUMBER;
curr_seq NUMBER;
BEGIN
SELECT MAX(pk_val) INTO last_used FROM your_table;
LOOP
SELECT your_seq.NEXTVAL INTO curr_seq FROM dual;
IF curr_seq >= last_used THEN EXIT;
END IF;
END LOOP;
END;
This enables you to get the sequence back in sync with the table, without dropping/recreating/re-granting the sequence. It also uses no DDL, so no implicit commits are performed. Of course, you're going to have to hunt down and slap the folks who insist on not using the sequence to populate the column...
In case somebody prefers sed
and removing without wildcard expansion:
sed -e "s/^\(.*\)$/rm -f -- \'\1\'/" deletelist.txt | /bin/sh
Reminder: use absolute pathnames in the file or make sure you are in the right directory.
And for completeness the same with awk
:
awk '{printf "rm -f -- '\''%s'\''\n",$1}' deletelist.txt | /bin/sh
Wildcard expansion will work if the single quotes are remove, but this is dangerous in case the filename contains spaces. This would need to add quotes around the wildcards.
The data.table
package introduced the IDate
class some time ago and zoo
-package-like functions to retrieve months, days, etc (Check ?IDate
). so, you can extract the desired info now in the following ways:
require(data.table)
df <- data.frame(id = 1:3,
date = c("2004-02-06" , "2006-03-14" , "2007-07-16"))
setDT(df)
df[ , date := as.IDate(date) ] # instead of as.Date()
df[ , yrmn := paste0(year(date), '-', month(date)) ]
df[ , yrmn2 := format(date, '%Y-%m') ]
As the Python documentation says:
sys.maxsize
The largest positive integer supported by the platform’s Py_ssize_t type, and thus the maximum size lists, strings, dicts, and many other containers can have.
In my computer (Linux x86_64):
>>> import sys
>>> print sys.maxsize
9223372036854775807
mysql -s -N -username -p information_schema -e 'SELECT Variable_Value FROM GLOBAL_VARIABLES WHERE Variable_Name = "datadir"'
The command will select the value only from MySQL's internal information_schema database and disables the tabular output and column headers.
Output on Linux [mine result]:
/var/lib/mysql
or
mysql> select @@datadir;
on MYSQL CLI
and then
cd /var/lib/mysql && rm -rf test/NOTEMPTY
change path based on your result
IANAL but as I see it....
While you can combine GPL and MIT code, the GPL is tainting. Which means the package as a whole gets the limitations of the GPL. As that is more restrictive you can no longer use it in commercial (or rather closed source) software. Which also means if you have a MIT/BSD/ASL project you will not want to add dependencies to GPL code.
Adding a GPL dependency does not change the license of your code but it will limit what people can do with the artifact of your project. This is also why the ASF does not allow dependencies to GPL code for their projects.
A simple program's compilation workflow is simple, I can draw it as a small graph: source -> [compilation] -> object [linking] -> executable. There are files (source, object, executable) in this graph, and rules (make's terminology). That graph is definied in the Makefile.
When you launch make, it reads Makefile, and checks for changed files. If there's any, it triggers the rule, which depends on it. The rule may produce/update further files, which may trigger other rules and so on. If you create a good makefile, only the necessary rules (compiler/link commands) will run, which stands "to next" from the modified file in the dependency path.
Pick an example Makefile, read the manual for syntax (anyway, it's clear for first sight, w/o manual), and draw the graph. You have to understand compiler options in order to find out the names of the result files.
The make graph should be as complex just as you want. You can even do infinite loops (don't do)! You can tell make, which rule is your target, so only the left-standing files will be used as triggers.
Again: draw the graph!.
Try this one:
Color color = new Color (10,10,10)
myPaint.setColor(color.getRGB());
To handle this problem in a clean way, I suggest to use brew
and jenv
.
JAVA_VERSION=11
brew reinstall jenv
brew reinstall openjdk@${JAVA_VERSION}
jenv add /usr/local/opt/openjdk@${JAVA_VERSION}/
jenv global ${JAVA_VERSION}
~/.bashrc
or ~/.zshrc
export PATH="$HOME/.jenv/bin:$PATH"
eval "$(jenv init -)"
export JAVA_HOME="$HOME/.jenv/versions/`jenv version-name`"
Then restart your shell and try to execute java -version
Note: If you have this problem, your current JDK version is not existent or misconfigured (or may be you have only JRE).
In host computer/server go to Sql server management studio --> open Security Section on left hand --> right click on Login, select New Login and then create a new account for your database which you want to connect to.
Check the TCP/IP Protocol is Enable. go to All programs --> Microsoft SQL server 2008 --> Configuration Tools --> open Sql server configuration manager. On the left hand select client protocols (based on your operating system 32/64 bit). On the right hand, check TCP/IP Protocol be Enabled.
In Remote computer/server, open Data source administrator. Control panel --> Administrative tools --> Data sources (ODBC).
In User DSN or System DSN , click Add button and select Sql Server driver and then press Finish.
Enter Name.
Enter Server, note that: if you want to enter host computer address, you should enter that`s IP address without "\\". eg. 192.168.1.5 and press Next.
Select With SQL Server authentication using a login ID and password entered by the user.
At the bellow enter your login ID and password which you created on first step. and then click Next.
If shown Database is your database, click Next and then Finish.
What I did based on the other answers was
NEWLINE=$'\n'
my_var="__between eggs and bacon__"
echo "spam${NEWLINE}eggs${my_var}bacon${NEWLINE}knight"
# which outputs:
spam
eggs__between eggs and bacon__bacon
knight
In Device Developer option
Check Install Via USB is ON compulsory.
In my case, it was caused from an incompatibility with OpenJDK 9 (which I haven't investigated).
If you don't need JDK 9, a temporary work-around would be to purge it from your machine:
sudo apt-get remove --purge openjdk-9-jdk openjdk-9-jre
sudo apt-get remove --purge openjdk-9-jdk-headless openjdk-9-jre-headless
For-loop in C:
for(int x = 0; x<=3; x++)
{
//Do something!
}
The same loop in 8086 assembler:
xor cx,cx ; cx-register is the counter, set to 0
loop1 nop ; Whatever you wanna do goes here, should not change cx
inc cx ; Increment
cmp cx,3 ; Compare cx to the limit
jle loop1 ; Loop while less or equal
That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:
mov cx,4 ; 4 iterations
loop1 nop ; Whatever you wanna do goes here, should not change cx
loop loop1 ; loop instruction decrements cx and jumps to label if not 0
If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction
times 4 nop
Do-while-loop in C:
int x=1;
do{
//Do something!
}
while(x==1)
The same loop in assembler:
mov ax,1
loop1 nop ; Whatever you wanna do goes here
cmp ax,1 ; Check wether cx is 1
je loop1 ; And loop if equal
While-loop in C:
while(x==1){
//Do something
}
The same loop in assembler:
jmp loop1 ; Jump to condition first
cloop1 nop ; Execute the content of the loop
loop1 cmp ax,1 ; Check the condition
je cloop1 ; Jump to content of the loop if met
For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.
Before Java 5.0, use -Xdebug
and -Xrunjdwp
arguments. These options will still work in later versions, but it will run in interpreted mode instead of JIT, which will be slower.
From Java 5.0, it is better to use the -agentlib:jdwp
single option:
-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=1044
Options on -Xrunjdwp
or agentlib:jdwp
arguments are :
transport=dt_socket
: means the way used to connect to JVM (socket is a good choice, it can be used to debug a distant computer)address=8000
: TCP/IP port exposed, to connect from the debugger, suspend=y
: if 'y', tell the JVM to wait until debugger is attached to begin execution, otherwise (if 'n'), starts execution right away.This should do the trick:
<table width="400" border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="50" height="40" valign="top" rowspan="3">
<img alt="" src="" width="40" height="40" style="margin: 0; border: 0; padding: 0; display: block;">
</td>
<td width="350" height="40" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<a href="" style="color: #D31145; font-weight: bold; text-decoration: none;">LAST FIRST</a><br>
REALTOR | P 123.456.789
</td>
</tr>
<tr>
<td width="350" height="70" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<img alt="" src="" width="200" height="60" style="margin: 0; border: 0; padding: 0; display: block;">
</td>
</tr>
<tr>
<td width="350" height="20" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 10px; color: #000000;">
all your minor text here | all your minor text here | all your minor text here
</td>
</tr>
</table>
UPDATE: Adjusted code per the comments:
After viewing your jsFiddle, an important thing to note about tables is that table cell widths in each additional row all have to be the same width as the first, and all cells must add to the total width of your table.
Here is an example that will NOT WORK:
<table width="600" border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="200" bgcolor="#252525">
</td>
<td width="400" bgcolor="#454545">
</td>
</tr>
<tr>
<td width="300" bgcolor="#252525">
</td>
<td width="300" bgcolor="#454545">
</td>
</tr>
</table>
Although the 2nd row does add up to 600, it (and any additional rows) must have the same 200-400 split as the first row, unless you are using colspans. If you use a colspan, you could have one row, but it needs to have the same width as the cells it is spanning, so this works:
<table width="600" border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="200" bgcolor="#252525">
</td>
<td width="400" bgcolor="#454545">
</td>
</tr>
<tr>
<td width="600" colspan="2" bgcolor="#353535">
</td>
</tr>
</table>
Not a full tutorial, but I hope that helps steer you in the right direction in the future.
Here is the code you are after:
<table width="900" border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="57" height="43" valign="top" rowspan="2">
<img alt="Rashel Adragna" src="http://zoparealtygroup.com/wp-content/uploads/2013/10/sig_head.png" width="47" height="43" style="margin: 0; border: 0; padding: 0; display: block;">
</td>
<td width="843" height="43" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<a href="" style="color: #D31145; font-weight: bold; text-decoration: none;">RASHEL ADRAGNA</a><br>
REALTOR | P 855.900.24KW
</td>
</tr>
<tr>
<td width="843" height="64" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<img alt="Zopa Realty Group logo" src="http://zoparealtygroup.com/wp-content/uploads/2013/10/sig_logo.png" width="177" height="54" style="margin: 0; border: 0; padding: 0; display: block;">
</td>
</tr>
<tr>
<td width="843" colspan="2" height="20" valign="bottom" align="center" style="font-family: Helvetica, Arial, sans-serif; font-size: 10px; color: #000000;">
all your minor text here | all your minor text here | all your minor text here
</td>
</tr>
</table>
You'll note that I've added an extra 10px to some of your table cells. This in combination with align/valigns act as padding between your cells. It is a clever way to aviod actually having to add padding, margins or empty padding cells.
The documentation on split()
says:
Splits this string around matches of the given regular expression.
(Emphasis mine.)
A dot is a special character in regular expression syntax. Use Pattern.quote()
on the parameter to split() if you want the split to be on a literal string pattern:
String[] words = temp.split(Pattern.quote("."));
I had the same error when trying to add an image to a module inside a larger project turns out the Image.asset widget takes a packages parameter that you can specify, after specifying it worked just fine
Try putting your code inside a main function in testMain.py
import parallelTestModule
if __name__ == '__main__':
extractor = parallelTestModule.ParallelExtractor()
extractor.runInParallel(numProcesses=2, numThreads=4)
See the docs:
"For an explanation of why (on Windows) the if __name__ == '__main__'
part is necessary, see Programming guidelines."
which say
"Make sure that the main module can be safely imported by a new Python interpreter without causing unintended side effects (such a starting a new process)."
... by using if __name__ == '__main__'
I had the same error and nothing of previous have helped, so I tried to follow original documentation of Open Graph Protocol and I added prefix attribute to my html tag and everything became awesome.
<html prefix="og: http://ogp.me/ns#">
Perhaps not 100% answering the question, but i stumbled onto this thread in the hope of solving a session problem when ajax-posting a fileupload from the assetmanager of the innovastudio editor. Eventually the solution was simple: they have a flash-uploader. Disabling that (setting
var flashUpload = false;
in asset.php) and the lights started blinking again.
As these problems can be very hard to debug i found that putting something like the following in the upload handler will set you (well, me in this case) on the right track:
$sn=session_name();
error_log("session_name: $sn ");
if(isset($_GET[$sn])) error_log("session as GET param");
if(isset($_POST[$sn])) error_log("session as POST param");
if(isset($_COOKIE[$sn])) error_log("session as Cookie");
if(isset($PHPSESSID)) error_log("session as Global");
A dive into the log and I quickly spotted the missing session, where no cookie was sent.
This
url = new URL("http://10.0.2.2:8080/HelloServlet/PDRS?param1="+lat+"¶m2="+lon);
must work. For whatever strange reason1, you need ?
before the first parameter and &
before the following ones.
Using a compound parameter like
url = new URL("http://10.0.2.2:8080/HelloServlet/PDRS?param1="+lat+"_"+lon);
would work, too, but is surely not nice. You can't use a space there as it's prohibited in an URL, but you could encode it as %20
or +
(but this is even worse style).
1 Stating that ?
separates the path and the parameters and that &
separates parameters from each other does not explain anything about the reason. Some RFC says "use ? there and & there", but I can't see why they didn't choose the same character.
In Python 2.6, using chain.from_iterable()
:
>>> from itertools import chain
>>> list(chain.from_iterable(mi.image_set.all() for mi in h.get_image_menu()))
It avoids creating of intermediate list.
Even if you don't like goto, do not use an exception to exit a loop. The following sample shows how ugly it could be:
try {
while ( ... ) {
switch( ... ) {
case ...:
throw 777; // I'm afraid of goto
}
}
}
catch ( int )
{
}
I would use goto
as in this answer. In this case goto
will make code more clear then any other option. I hope that this question will be helpful.
But I think that using goto
is the only option here because of the string while(true)
. You should consider refactoring of your loop. I'd suppose the following solution:
bool end_loop = false;
while ( !end_loop ) {
switch( msg->state ) {
case MSGTYPE: // ...
break;
// ... more stuff ...
case DONE:
end_loop = true; break;
}
}
Or even the following:
while ( msg->state != DONE ) {
switch( msg->state ) {
case MSGTYPE: // ...
break;
// ... more stuff ...
}
Use six
:
from six.moves.urllib.parse import quote
six
will simplify compatibility problems between Python 2 and Python 3, such as different import paths.
I don't know if this is still actual for you, but I still leave my comment so maybe it will help somebody else. I had same issue, and the solution proposed by @dighan on bountysource.com/issues/ solved it for me.
So here is the code that solved my problem:
var media = document.getElementById("YourVideo");
const playPromise = media.play();
if (playPromise !== null){
playPromise.catch(() => { media.play(); })
}
It still throws an error into console, but at least the video is playing :)
The following worked for me
cd /usr/local/bin
mv python python.old
ln -s python3 python
With the arrival of the HTTPClient
API, not only was the Http
API replaced, but a new one was added, the HttpInterceptor
API.
AFAIK one of its goals is to add default behavior to all the HTTP outgoing requests and incoming responses.
So assumming that you want to add a default error handling behavior, adding .catch()
to all of your possible http.get/post/etc methods is ridiculously hard to maintain.
This could be done in the following way as example using a HttpInterceptor
:
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse, HTTP_INTERCEPTORS } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { _throw } from 'rxjs/observable/throw';
import 'rxjs/add/operator/catch';
/**
* Intercepts the HTTP responses, and in case that an error/exception is thrown, handles it
* and extract the relevant information of it.
*/
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
/**
* Intercepts an outgoing HTTP request, executes it and handles any error that could be triggered in execution.
* @see HttpInterceptor
* @param req the outgoing HTTP request
* @param next a HTTP request handler
*/
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req)
.catch(errorResponse => {
let errMsg: string;
if (errorResponse instanceof HttpErrorResponse) {
const err = errorResponse.message || JSON.stringify(errorResponse.error);
errMsg = `${errorResponse.status} - ${errorResponse.statusText || ''} Details: ${err}`;
} else {
errMsg = errorResponse.message ? errorResponse.message : errorResponse.toString();
}
return _throw(errMsg);
});
}
}
/**
* Provider POJO for the interceptor
*/
export const ErrorInterceptorProvider = {
provide: HTTP_INTERCEPTORS,
useClass: ErrorInterceptor,
multi: true,
};
// app.module.ts
import { ErrorInterceptorProvider } from 'somewhere/in/your/src/folder';
@NgModule({
...
providers: [
...
ErrorInterceptorProvider,
....
],
...
})
export class AppModule {}
Some extra info for OP: Calling http.get/post/etc without a strong type isn't an optimal use of the API. Your service should look like this:
// These interfaces could be somewhere else in your src folder, not necessarily in your service file
export interface FooPost {
// Define the form of the object in JSON format that your
// expect from the backend on post
}
export interface FooPatch {
// Define the form of the object in JSON format that your
// expect from the backend on patch
}
export interface FooGet {
// Define the form of the object in JSON format that your
// expect from the backend on get
}
@Injectable()
export class DataService {
baseUrl = 'http://localhost'
constructor(
private http: HttpClient) {
}
get(url, params): Observable<FooGet> {
return this.http.get<FooGet>(this.baseUrl + url, params);
}
post(url, body): Observable<FooPost> {
return this.http.post<FooPost>(this.baseUrl + url, body);
}
patch(url, body): Observable<FooPatch> {
return this.http.patch<FooPatch>(this.baseUrl + url, body);
}
}
Returning Promises
from your service methods instead of Observables
is another bad decision.
And an extra piece of advice: if you are using TYPEscript, then start using the type part of it. You lose one of the biggest advantages of the language: to know the type of the value that you are dealing with.
If you want a, in my opinion, good example of an angular service, take a look at the following gist.
If you are using SQL Server 2005+, then you can use the PIVOT
function to transform the data from rows into columns.
It sounds like you will need to use dynamic sql if the weeks are unknown but it is easier to see the correct code using a hard-coded version initially.
First up, here are some quick table definitions and data for use:
CREATE TABLE #yt
(
[Store] int,
[Week] int,
[xCount] int
);
INSERT INTO #yt
(
[Store],
[Week], [xCount]
)
VALUES
(102, 1, 96),
(101, 1, 138),
(105, 1, 37),
(109, 1, 59),
(101, 2, 282),
(102, 2, 212),
(105, 2, 78),
(109, 2, 97),
(105, 3, 60),
(102, 3, 123),
(101, 3, 220),
(109, 3, 87);
If your values are known, then you will hard-code the query:
select *
from
(
select store, week, xCount
from yt
) src
pivot
(
sum(xcount)
for week in ([1], [2], [3])
) piv;
See SQL Demo
Then if you need to generate the week number dynamically, your code will be:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(Week)
from yt
group by Week
order by Week
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT store,' + @cols + ' from
(
select store, week, xCount
from yt
) x
pivot
(
sum(xCount)
for week in (' + @cols + ')
) p '
execute(@query);
See SQL Demo.
The dynamic version, generates the list of week
numbers that should be converted to columns. Both give the same result:
| STORE | 1 | 2 | 3 |
---------------------------
| 101 | 138 | 282 | 220 |
| 102 | 96 | 212 | 123 |
| 105 | 37 | 78 | 60 |
| 109 | 59 | 97 | 87 |
Here is a solution under 19API lvl:
First of all. Make a Gson obj. --> Gson gson = new Gson();
Second step is get your jsonObj as String with StringRequest(instead of JsonObjectRequest)
YoursObjArray[] yoursObjArray = gson.fromJson(response, YoursObjArray[].class);
you could put the style in container div menu with:
<div style="position:relative; z-index:10">
...
<!--html menu-->
...
</div>
before
after
An application is CPU-bound when the arithmetic/logical/floating-point (A/L/FP) performance during the execution is mostly near the theoretical peak-performance of the processor (data provided by the manufacturer and determined by the characteristics of the processor: number of cores, frequency, registers, ALUs, FPUs, etc.).
The peek performance is very difficult to be achieved in real-world applications, for not saying impossible. Most of the applications access memory in different parts of the execution and the processor is not doing A/L/FP operations during several cycles. This is called Von Neumann Limitation due to the distance that exists between the memory and the processor.
If you want to be near the CPU peak-performance a strategy could be to try to reuse most of the data in the cache memory in order to avoid requiring data from the main memory. An algorithm that exploits this feature is the matrix-matrix multiplication (if both matrices can be stored in the cache memory). This happens because if the matrices are size n x n
then you need to do about 2 n^3
operations using only 2 n^2
FP numbers of data. On the other hand matrix addition, for example, is a less CPU-bound or a more memory-bound application than the matrix multiplication since it requires only n^2
FLOPs with the same data.
In the following figure the FLOPs obtained with a naive algorithms for the matrix addition and the matrix multiplication in an Intel i5-9300H, is shown:
Note that as expected the performance of the matrix multiplication in bigger than the matrix addition. These results can be reproduced by running test/gemm
and test/matadd
available in this repository.
I suggest also to see the video given by J. Dongarra about this effect.
I am so glad to solve this problem:
HttpPost httppost = new HttpPost(postData);
CookieStore cookieStore = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", getSessionId());
//cookie.setDomain("your domain");
cookie.setPath("/");
cookieStore.addCookie(cookie);
client.setCookieStore(cookieStore);
response = client.execute(httppost);
So Easy!
Like others have already noted, you can use :empty
in jQuery like this:
$('#cartContent:empty').remove();
It will remove the #cartContent
div if it is empty.
But this and other techniques that people are suggesting here may not do what you want because if it has any text nodes containing whitespace it is not considered empty. So this is not empty:
<div> </div>
while you may want to consider it empty.
I had this problem some time ago and I wrote this tiny jQuery plugin - just add it to your code:
jQuery.expr[':'].space = function(elem) {
var $elem = jQuery(elem);
return !$elem.children().length && !$elem.text().match(/\S/);
}
and now you can use
$('#cartContent:space').remove();
which will remove the div if it is empty or contains only whitespace. Of course you can not only remove it but do anything you like, like
$('#cartContent:space').append('<p>It is empty</p>');
and you can use :not
like this:
$('#cartContent:not(:space)').append('<p>It is not empty</p>');
I came out with this test that reliably did what I wanted and you can take it out of the plugin to use it as a standalone test:
This one will work for jQuery objects:
function testEmpty($elem) {
return !$elem.children().length && !$elem.text().match(/\S/);
}
This one will work for DOM nodes:
function testEmpty(elem) {
var $elem = jQuery(elem);
return !$elem.children().length && !$elem.text().match(/\S/);
}
This is better than using .trim
because the above code first tests if the tested element has any child elements and if it does it tries to find the first non-whitespace character and then stops, without the need to read or mutate the string if it has even one character that is not whitespace.
Hope it helps.
::========================================================================
::== CREATE UNIQUE DATETIME STRING IN FORMAT YYYYMMDD-HHMMSS
::======= ================================================================
FOR /f %%a IN ('WMIC OS GET LocalDateTime ^| FIND "."') DO SET DTS=%%a
SET DATETIME=%DTS:~0,8%-%DTS:~8,6%
The first line always outputs in this format regardles of timezone:
20150515150941.077000+120
This leaves you with just formatting the output to fit your wishes.
Your error on the snippet of data you posted is a little cryptic, in that because there are no common values, the join operation fails because the values don't overlap it requires you to supply a suffix for the left and right hand side:
In [173]:
df_a.join(df_b, on='mukey', how='left', lsuffix='_left', rsuffix='_right')
Out[173]:
mukey_left DI PI mukey_right niccdcd
index
0 100000 35 14 NaN NaN
1 1000005 44 14 NaN NaN
2 1000006 44 14 NaN NaN
3 1000007 43 13 NaN NaN
4 1000008 43 13 NaN NaN
merge
works because it doesn't have this restriction:
In [176]:
df_a.merge(df_b, on='mukey', how='left')
Out[176]:
mukey DI PI niccdcd
0 100000 35 14 NaN
1 1000005 44 14 NaN
2 1000006 44 14 NaN
3 1000007 43 13 NaN
4 1000008 43 13 NaN
This applies to "IntelliJ IDEA-2019.2.4" on Mac.
The fact that your method does not use the self
argument (which is a reference to the instance that the method is attached to) doesn't mean you can leave it out. It always has to be there, because Python is always going to try to pass it in.
As I am not allowed to comment on user1908688's answer, here a hint for MariaDB users:
SELECT *
FROM (
SELECT *
ORDER BY date ASC, time ASC
LIMIT 18446744073709551615
) AS sub
GROUP BY sub.name
https://mariadb.com/kb/en/mariadb/why-is-order-by-in-a-from-subquery-ignored/
It may be that it's not loading the template you expect. I added a new class that inherited from UpdateView
- I thought it would automatically pick the template from what I named my class, but it actually loaded it based on the model
property on the class, which resulted in another (wrong) template being loaded. Once I explicitly set template_name
for the new class, it worked fine.
(This is for the benefit of others who may refer)
You can simply use cin and a char array. The cin input is delimited by the first whitespace it encounters.
#include<iostream>
using namespace std;
main()
{
char word[50];
cin>>word;
while(word){
//Do stuff with word[]
cin>>word;
}
}
On Snow Leopard (OS X 10.6.8), running 'man lsof' yields:
lsof -i 4 -a
(actual manual entry is 'lsof -i 4 -a -p 1234')
The previous answers didn't work on Snow Leopard, but I was trying to use 'netstat -nlp' until I saw the use of 'lsof' in the answer by pts.
my_hash = {:a => 5}
my_hash[:key] = "value"
Ping can be used with a variety of protocols. The protocol value can be appletalk, clns, ip (the default), novell, apollo, vines, decnet, or xns. Some protocols require another Cisco router at the remote end to answer ping packets. ... (Cisco field manual: router configuration, By Dave Hucaby, Steve McQuerry. Page 64)
... For IP. ping uses ICMP type 8 requests and ICMP type 0 replies. The traceroute (by using UDP) command can be used to discover the routers along the path that packets are taking to a destination. ... (Page 63)
The best way to do this is to first generate a .c file, and then compile it with tcc to a .pyd file
Note: Windows-onlyRequirements
Install:
sudo pip install -U cython
To obfuscate your .py file:
pyobfuscate.py myfile.py >obfuscated.py
To generate a .c file,
Add an Optionalinit<filename>()
function to your .py file
cython --embed file.py
cp Python.h tcc\include
tcc file.c -o file.pyd -shared -I\path\to\Python\include -L\path\to\Python\lib
import .pyd file into app.exe
May help someone that get this problem:
I edit studio64.exe.vmoptions
file, but failed to save.
So I opened this file with Notepad++ in Run as Administrator
mode and then saved successfully.
git format-patch commit_Id~1..commit_Id
git apply patch-file-name
Fast and simple solution.
None of the provided examples on here worked for me. They were either for Python 2 (uurllib2) or those for Python 3 return the error "ImportError: No module named request". I google the error message and it apparently requires me to install a the module - which is obviously unacceptable for such a simple task.
This code worked for me:
import json,urllib
data = urllib.urlopen("https://api.github.com/users?since=0").read()
d = json.loads(data)
print (d)
I think the simplest solution is:
window.scrollTo({top: 0, behavior: 'smooth'});
If you wanted instant scrolling then just use:
window.scrollTo({top: 0});
Can be used as a function:
// Scroll To Top
function scrollToTop() {
window.scrollTo({top: 0, behavior: 'smooth'});
}
Or as an onclick handler:
<button onclick='window.scrollTo({top: 0, behavior: "smooth"});'>Scroll to Top</button>
Here is an example of showing the line number of where exception takes place.
import sys
try:
print(5/0)
except Exception as e:
print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e)
print('And the rest of program continues')
I found a tool in Github that could possibly be a solution to this question. https://incarnate.github.io/curl-to-php/ I hope that will be useful
__getitem__
minimal ...
example in a custom class
When the magic syntax ...
gets passed to []
in a custom class, __getitem__()
receives a Ellipsis
class object.
The class can then do whatever it wants with this Singleton object.
Example:
class C(object):
def __getitem__(self, k):
return k
# Single argument is passed directly.
assert C()[0] == 0
# Multiple indices generate a tuple.
assert C()[0, 1] == (0, 1)
# Slice notation generates a slice object.
assert C()[1:2:3] == slice(1, 2, 3)
# Ellipsis notation generates the Ellipsis class object.
# Ellipsis is a singleton, so we can compare with `is`.
assert C()[...] is Ellipsis
# Everything mixed up.
assert C()[1, 2:3:4, ..., 6] == (1, slice(2,3,4), Ellipsis, 6)
The Python built-in list
class chooses to give it the semantic of a range, and any sane usage of it should too of course.
Personally, I'd just stay away from it in my APIs, and create a separate, more explicit method instead.
Tested in Python 3.5.2 and 2.7.12.
The problem is your query returned false
meaning there was an error in your query. After your query you could do the following:
if (!$result) {
die(mysqli_error($link));
}
Or you could combine it with your query:
$results = mysqli_query($link, $query) or die(mysqli_error($link));
That will print out your error.
Also... you need to sanitize your input. You can't just take user input and put that into a query. Try this:
$query = "SELECT * FROM shopsy_db WHERE name LIKE '%" . mysqli_real_escape_string($link, $searchTerm) . "%'";
In reply to: Table 'sookehhh_shopsy_db.sookehhh_shopsy_db' doesn't exist
Are you sure the table name is sookehhh_shopsy_db? maybe it's really like users or something.
The other option for using PHP scripts sans extension is
Options +MultiViews
Or even just following in the directories .htaccess
:
DefaultType application/x-httpd-php
The latter allows having all filenames without extension script
being treated as PHP scripts. While MultiViews makes the webserver look for alternatives, when just the basename is provided (there's a performance hit with that however).
I think you need to push a revert commit. So pull
from github again, including the commit you want to revert, then use git revert
and push the result.
If you don't care about other people's clones of your github repository being broken, you can also delete and recreate the master branch on github after your reset
: git push origin :master
.
Try this
textarea::-webkit-input-placeholder { color: #999;}
This is an extremely broad scope question, and a lot of the pros/cons will be contextual to the situation.
In all cases, these storage mechanisms will be specific to an individual browser on an individual computer/device. Any requirement to store data on an ongoing basis across sessions will need to involve your application server side - most likely using a database, but possibly XML or a text/CSV file.
localStorage, sessionStorage, and cookies are all client storage solutions. Session data is held on the server where it remains under your direct control.
localStorage and sessionStorage are relatively new APIs (meaning, not all legacy browsers will support them) and are near identical (both in APIs and capabilities) with the sole exception of persistence. sessionStorage (as the name suggests) is only available for the duration of the browser session (and is deleted when the tab or window is closed) - it does, however, survive page reloads (source DOM Storage guide - Mozilla Developer Network).
Clearly, if the data you are storing needs to be available on an ongoing basis then localStorage is preferable to sessionStorage - although you should note both can be cleared by the user so you should not rely on the continuing existence of data in either case.
localStorage and sessionStorage are perfect for persisting non-sensitive data needed within client scripts between pages (for example: preferences, scores in games). The data stored in localStorage and sessionStorage can easily be read or changed from within the client/browser so should not be relied upon for storage of sensitive or security-related data within applications.
This is also true for cookies, these can be trivially tampered with by the user, and data can also be read from them in plain text - so if you are wanting to store sensitive data then the session is really your only option. If you are not using SSL, cookie information can also be intercepted in transit, especially on an open wifi.
On the positive side cookies can have a degree of protection applied from security risks like Cross-Site Scripting (XSS)/Script injection by setting an HTTP only flag which means modern (supporting) browsers will prevent access to the cookies and values from JavaScript (this will also prevent your own, legitimate, JavaScript from accessing them). This is especially important with authentication cookies, which are used to store a token containing details of the user who is logged on - if you have a copy of that cookie then for all intents and purposes you become that user as far as the web application is concerned, and have the same access to data and functionality the user has.
As cookies are used for authentication purposes and persistence of user data, all cookies valid for a page are sent from the browser to the server for every request to the same domain - this includes the original page request, any subsequent Ajax requests, all images, stylesheets, scripts, and fonts. For this reason, cookies should not be used to store large amounts of information. The browser may also impose limits on the size of information that can be stored in cookies. Typically cookies are used to store identifying tokens for authentication, session, and advertising tracking. The tokens are typically not human readable information in and of themselves, but encrypted identifiers linked to your application or database.
In terms of capabilities, cookies, sessionStorage, and localStorage only allow you to store strings - it is possible to implicitly convert primitive values when setting (these will need to be converted back to use them as their type after reading) but not Objects or Arrays (it is possible to JSON serialise them to store them using the APIs). Session storage will generally allow you to store any primitives or objects supported by your Server Side language/framework.
As HTTP is a stateless protocol - web applications have no way of identifying a user from previous visits on returning to the web site - session data usually relies on a cookie token to identify the user for repeat visits (although rarely URL parameters may be used for the same purpose). Data will usually have a sliding expiry time (renewed each time the user visits), and depending on your server/framework data will either be stored in-process (meaning data will be lost if the web server crashes or is restarted) or externally in a state server or database. This is also necessary when using a web-farm (more than one server for a given website).
As session data is completely controlled by your application (server side) it is the best place for anything sensitive or secure in nature.
The obvious disadvantage of server-side data is scalability - server resources are required for each user for the duration of the session, and that any data needed client side must be sent with each request. As the server has no way of knowing if a user navigates to another site or closes their browser, session data must expire after a given time to avoid all server resources being taken up by abandoned sessions. When using session data you should, therefore, be aware of the possibility that data will have expired and been lost, especially on pages with long forms. It will also be lost if the user deletes their cookies or switches browsers/devices.
Some web frameworks/developers use hidden HTML inputs to persist data from one page of a form to another to avoid session expiration.
localStorage, sessionStorage, and cookies are all subject to "same-origin" rules which means browsers should prevent access to the data except the domain that set the information to start with.
For further reading on client storage technologies see Dive Into Html 5.
I suggest building an HttpWebRequest to programmatically execute your POST and then redirect after reading the Response if applicable.
1) The function returns a cell for a table view yes? So, the returned object is of type UITableViewCell
. These are the objects that you see in the table's rows. This function basically returns a cell, for a table view.
But you might ask, how the function would know what cell to return for what row, which is answered in the 2nd question
2)NSIndexPath
is essentially two things-
Because your table might be divided to many sections and each with its own rows, this NSIndexPath
will help you identify precisely which section and which row. They are both integers. If you're a beginner, I would say try with just one section.
It is called if you implement the UITableViewDataSource
protocol in your view controller. A simpler way would be to add a UITableViewController
class. I strongly recommend this because it Apple has some code written for you to easily implement the functions that can describe a table. Anyway, if you choose to implement this protocol yourself, you need to create a UITableViewCell
object and return it for whatever row. Have a look at its class reference to understand re-usablity because the cells that are displayed in the table view are reused again and again(this is a very efficient design btw).
As for when you have two table views, look at the method. The table view is passed to it, so you should not have a problem with respect to that.
Yes, it is a hash mapping or hash table. You can read a description of python's dict implementation, as written by Tim Peters, here.
That's why you can't use something 'not hashable' as a dict key, like a list:
>>> a = {}
>>> b = ['some', 'list']
>>> hash(b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list objects are unhashable
>>> a[b] = 'some'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list objects are unhashable
You can read more about hash tables or check how it has been implemented in python and why it is implemented that way.
Check your namespaces. I had and issue with that. I found that out by adding another web service to the project to dup it like you did yours and noticed the namespace was different. I had renamed it at the beginning of the project and it looks like its persisted.
Use the 'And' keyword for a logical and. Like this:
If Not ((filename = testFileName) And (fileName <> "")) Then
You can use a byte literal in Java... sort of.
byte f = 0;
f = 0xa;
0xa
(int literal) gets automatically cast to byte. It's not a real byte literal (see JLS & comments below), but if it quacks like a duck, I call it a duck.
What you can't do is this:
void foo(byte a) {
...
}
foo( 0xa ); // will not compile
You have to cast as follows:
foo( (byte) 0xa );
But keep in mind that these will all compile, and they are using "byte literals":
void foo(byte a) {
...
}
byte f = 0;
foo( f = 0xa ); //compiles
foo( f = 'a' ); //compiles
foo( f = 1 ); //compiles
Of course this compiles too
foo( (byte) 1 ); //compiles
The easiest way to get rid of the the ugly frame in newer versions of matplotlib:
import matplotlib.pyplot as plt
plt.box(False)
If you really must always use the object oriented approach, then do: ax.set_frame_on(False)
.
I'm using XAMPP with Apache2.4, I had this same issue. I wanted to leave the default xampp/htdocs folder in place, be able to access it from locahost and have a Virtual Host to point to my dev area...
The full contents of my C:\xampp\apache\conf\extra\http-vhosts.conf
file is below...
# Virtual Hosts
#
# Required modules: mod_log_config
# If you want to maintain multiple domains/hostnames on your
# machine you can setup VirtualHost containers for them. Most configurations
# use only name-based virtual hosts so the server doesn't need to worry about
# IP addresses. This is indicated by the asterisks in the directives below.
#
# Please see the documentation at
# <URL:http://httpd.apache.org/docs/2.4/vhosts/>
# for further details before you try to setup virtual hosts.
#
# You may use the command line option '-S' to verify your virtual host
# configuration.
#
# Use name-based virtual hosting.
#
##NameVirtualHost *:80
#
# VirtualHost example:
# Almost any Apache directive may go into a VirtualHost container.
# The first VirtualHost section is used for all requests that do not
# match a ##ServerName or ##ServerAlias in any <VirtualHost> block.
#
##<VirtualHost *:80>
##ServerAdmin [email protected]
##DocumentRoot "C:/xampp/htdocs/dummy-host.example.com"
##ServerName dummy-host.example.com
##ServerAlias www.dummy-host.example.com
##ErrorLog "logs/dummy-host.example.com-error.log"
##CustomLog "logs/dummy-host.example.com-access.log" common
##</VirtualHost>
##<VirtualHost *:80>
##ServerAdmin [email protected]
##DocumentRoot "C:/xampp/htdocs/dummy-host2.example.com"
##ServerName dummy-host2.example.com
##ErrorLog "logs/dummy-host2.example.com-error.log"
##CustomLog "logs/dummy-host2.example.com-access.log" common
##</VirtualHost>
<VirtualHost *:80>
DocumentRoot "C:\xampp\htdocs"
ServerName localhost
</VirtualHost>
<VirtualHost *:80>
DocumentRoot "C:\nick\static"
ServerName dev.middleweek.co.uk
<Directory "C:\nick\static">
Allow from all
Require all granted
</Directory>
</VirtualHost>
I then updated my C:\windows\System32\drivers\etc\hosts
file like this...
# Copyright (c) 1993-2009 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
# 102.54.94.97 rhino.acme.com # source server
# 38.25.63.10 x.acme.com # x client host
# localhost name resolution is handled within DNS itself.
# 127.0.0.1 localhost
# ::1 localhost
127.0.0.1 dev.middleweek.co.uk
127.0.0.1 localhost
Restart your machine for good measure, open the XAMPP Control Panel and start Apache.
Now open your custom domain in your browser, in the above example, it'll be http://dev.middleweek.co.uk
Hope that helps someone!
And if you want to be able to view directory listings under your new Virtual host, then edit your VirtualHost block in C:\xampp\apache\conf\extra\http-vhosts.conf
to include "Options Indexes" like this...
<VirtualHost *:80>
DocumentRoot "C:\nick\static"
ServerName dev.middleweek.co.uk
<Directory "C:\nick\static">
Allow from all
Require all granted
Options Indexes
</Directory>
</VirtualHost>
Cheers, Nick
def is_prime(x):
n = 2
if x < n:
return False
else:
while n < x:
print n
if x % n == 0:
return False
break
n = n + 1
else:
return True
Product "Clean" was the solution for me.
you can use unique property by using len function
len(df['hID'].unique()) 5
Well previously, I used the approach that you can find inside the WebElement
:
WebElement baseTable = driver.findElement(By.tagName("table"));
WebElement tableRow = baseTable.findElement(By.xpath("//tr[2]")); //should be the third row
webElement cellIneed = tableRow.findElement(By.xpath("//td[2]"));
String valueIneed = cellIneed.getText();
Please note that I find inside the found WebElement
instance.
The above is Java code, assuming that driver
variable is healthy instance of WebDriver
From the documentation:
Paths associated with the default
provider
are generally interoperable with thejava.io.File
class. Paths created by other providers are unlikely to be interoperable with the abstract path names represented byjava.io.File
. ThetoPath
method may be used to obtain a Path from the abstract path name represented by a java.io.File object. The resulting Path can be used to operate on the same file as thejava.io.File
object. In addition, thetoFile
method is useful to construct aFile
from theString
representation of aPath
.
(emphasis mine)
So, for toFile
:
Returns a
File
object representing this path.
And toPath
:
Returns a
java.nio.file.Path
object constructed from the this abstract path.
If you prefer to use a GUI to create the keys
For a walkthrough on putty gen for the above steps, please see http://ask-leo.com/how_do_i_create_and_use_public_keys_with_ssh.html
Just add these lines before headers.
Accurate format of .doc/docx
files will be retrieved:
if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');
ob_clean();
There are two cases:
const reference --good idea, sometimes, especially for heavy objects or proxy classes, compiler optimization
non-const reference --bad idea, sometimes, breaks encapsulations
Both share same issue -- can potentially point to destroyed object...
I would recommend using smart pointers for many situations where you require to return a reference/pointer.
Also, note the following:
There is a formal rule - the C++ Standard (section 13.3.3.1.4 if you are interested) states that a temporary can only be bound to a const reference - if you try to use a non-const reference the compiler must flag this as an error.
I have the same problem. I avoid it with remove.packages("Package making this confusion")
and it works. In my case, I don't need the second package, so that is not a very good idea.
If you have java 8 installed it might be related to the following issue: https://support.oracle.com/knowledge/Middleware/2412304_1.html
Simply removing/renaming the "C:\Program Files (x86)\Common Files\Oracle\Java\javapath" worked for me.
$("#myDiv").hide();
will set the css display to none. if you need to set visibility to hidden as well, could do this via
$("#myDiv").css("visibility", "hidden");
or combine both in a chain
$("#myDiv").hide().css("visibility", "hidden");
or write everything with one css() function
$("#myDiv").css({
display: "none",
visibility: "hidden"
});
@Prasand Kumar, here's a complete sort routine based on Prasand's concepts:
Public Sub ArrayListSort(ByRef SortArray As Variant)
'
'Uses the sort capabilities of a System.Collections.ArrayList object to sort an array of values of any simple
'data-type.
'
'AUTHOR: Peter Straton
'
'CREDIT: Derived from Prasand Kumar's post at: https://stackoverflow.com/questions/152319/vba-array-sort-function
'
'*************************************************************************************************************
Static ArrayListObj As Object
Dim i As Long
Dim LBnd As Long
Dim UBnd As Long
LBnd = LBound(SortArray)
UBnd = UBound(SortArray)
'If necessary, create the ArrayList object, to be used to sort the specified array's values
If ArrayListObj Is Nothing Then
Set ArrayListObj = CreateObject("System.Collections.ArrayList")
Else
ArrayListObj.Clear 'Already allocated so just clear any old contents
End If
'Add the ArrayList elements from the array of values to be sorted. (There appears to be no way to do this
'using a single assignment statement.)
For i = LBnd To UBnd
ArrayListObj.Add SortArray(i)
Next i
ArrayListObj.Sort 'Do the sort
'Transfer the sorted ArrayList values back to the original array, which can be done with a single assignment
'statement. But the result is always zero-based so then, if necessary, adjust the resulting array to match
'its original index base.
SortArray = ArrayListObj.ToArray
If LBnd <> 0 Then ReDim Preserve SortArray(LBnd To UBnd)
End Sub
This can be done safely using promises
function loadScript(src) {
return new Promise(function(resolve, reject) {
let script = document.createElement('script');
script.src = src;
script.onload = () => resolve(script);
script.onerror = () => reject(new Error("Script load error: " + src));
document.head.append(script);
});
}
and use like this
let promise = loadScript("https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.2.0/lodash.js");
promise.then(
script => alert(`${script.src} is loaded!`),
error => alert(`Error: ${error.message}`)
);
Here is part of my program related to plotting confidence interval.
ads = 1
require(stats); require(graphics)
library(splines)
x_raw <- seq(1,10,0.1)
y <- cos(x_raw)+rnorm(len_data,0,0.1)
y[30] <- 1.4 # outlier point
len_data = length(x_raw)
N <- len_data
summary(fm1 <- lm(y~bs(x_raw, df=5), model = TRUE, x =T, y = T))
ht <-seq(1,10,length.out = len_data)
plot(x = x_raw, y = y,type = 'p')
y_e <- predict(fm1, data.frame(height = ht))
lines(x= ht, y = y_e)
sigma_e <- sqrt(sum((y-y_e)^2)/N)
print(sigma_e)
H<-fm1$x
A <-solve(t(H) %*% H)
y_e_minus <- rep(0,N)
y_e_plus <- rep(0,N)
y_e_minus[N]
for (i in 1:N)
{
tmp <-t(matrix(H[i,])) %*% A %*% matrix(H[i,])
tmp <- 1.96*sqrt(tmp)
y_e_minus[i] <- y_e[i] - tmp
y_e_plus[i] <- y_e[i] + tmp
}
plot(x = x_raw, y = y,type = 'p')
polygon(c(ht,rev(ht)),c(y_e_minus,rev(y_e_plus)),col = rgb(1, 0, 0,0.5), border = NA)
#plot(x = x_raw, y = y,type = 'p')
lines(x= ht, y = y_e_plus, lty = 'dashed', col = 'red')
lines(x= ht, y = y_e)
lines(x= ht, y = y_e_minus, lty = 'dashed', col = 'red')
You can use a simple, low-cost USB port reader like this test connects directly to your Android device; it has a utility app and an SDK you can use for app development: https://www.atlasrfidstore.com/sls-rfid-smartmicro-android-micro-usb-reader/
openssl s_client -connect api.cscglobal.com:443 < /dev/null 2>/dev/null | openssl x509 -text -in /dev/stdin | grep "Signature Algorithm" | cut -d ":" -f2 | uniq | sed '/^$/d' | sed -e 's/^[ \t]*//'
Here you can also find more examples for values that data-toggle
can have assigned. Just visit the page and then CTRL+F
to search for data-toggle
.
A pretty straightforward solution that worked for me is to use .reindex
on df.columns
:
df = df[df.columns.reindex(['mean', 0, 1, 2, 3, 4])[0]]
As the OP has asked the question if the key exists or not.
A more elegant solution that will return boolean using ES6 reduce function can be
const magenicVendorExists = vendors.reduce((accumulator, vendor) => (accumulator||vendor.Name === "Magenic"), false);
Note: The initial parameter of reduce is a false
and if the array has the key it will return true.
Hope it helps for better and cleaner code implementation
If your method is returning something back, you can solve this error by putting
.Result
to the end of the job and
.Wait()
if it doesn't return anything.
To answer Chris Conway, on Linux (at least) you would do this:
echo $(basename $(readlink -nf $0))
readlink prints out the value of a symbolic link. If it isn't a symbolic link, it prints the file name. -n tells it to not print a newline. -f tells it to follow the link completely (if a symbolic link was a link to another link, it would resolve that one as well).
The str.split()
method without an argument splits on whitespace:
>>> "many fancy word \nhello \thi".split()
['many', 'fancy', 'word', 'hello', 'hi']
If you have your hex value, and your just wondering what the value for the alpha would be, this snippet may help:
const alphaToHex = (alpha => {_x000D_
if (alpha > 1 || alpha < 0 || isNaN(alpha)) {_x000D_
throw new Error('The argument must be a number between 0 and 1');_x000D_
}_x000D_
return Math.ceil(255 * alpha).toString(16).toUpperCase();_x000D_
})_x000D_
_x000D_
console.log(alphaToHex(0.45));
_x000D_
Hi I'm also relatively new but I can give you basic help.
UPDATE 12.01.2016:
The bold line is the current branch.
You can also just double click a branch to use checkout.
And here some helpful links:
I had similar problem with margin collapse because of parent having position
set to relative. Here are list of commands you can use to disable margin collapsing.
Just try to assign any parent-fix*
class to div.container
element, or any class children-fix*
to div.margin
. Pick the one that fits your needs best.
When
div.absolute
with red background will be positioned at the very top of the page.div.absolute
will be positioned at the same Y coordinate as div.margin
html, body { margin: 0; padding: 0; }_x000D_
_x000D_
.container {_x000D_
width: 100%;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.absolute {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 50px;_x000D_
right: 50px;_x000D_
height: 100px;_x000D_
border: 5px solid #F00;_x000D_
background-color: rgba(255, 0, 0, 0.5);_x000D_
}_x000D_
_x000D_
.margin {_x000D_
width: 100%;_x000D_
height: 20px;_x000D_
background-color: #444;_x000D_
margin-top: 50px;_x000D_
color: #FFF;_x000D_
}_x000D_
_x000D_
/* Here are some examples on how to disable margin _x000D_
collapsing from within parent (.container) */_x000D_
.parent-fix1 { padding-top: 1px; }_x000D_
.parent-fix2 { border: 1px solid rgba(0,0,0, 0);}_x000D_
.parent-fix3 { overflow: auto;}_x000D_
.parent-fix4 { float: left;}_x000D_
.parent-fix5 { display: inline-block; }_x000D_
.parent-fix6 { position: absolute; }_x000D_
.parent-fix7 { display: flex; }_x000D_
.parent-fix8 { -webkit-margin-collapse: separate; }_x000D_
.parent-fix9:before { content: ' '; display: table; }_x000D_
_x000D_
/* Here are some examples on how to disable margin _x000D_
collapsing from within children (.margin) */_x000D_
.children-fix1 { float: left; }_x000D_
.children-fix2 { display: inline-block; }
_x000D_
<div class="container parent-fix1">_x000D_
<div class="margin children-fix">margin</div>_x000D_
<div class="absolute"></div>_x000D_
</div>
_x000D_
Here is jsFiddle with example you can edit
Open the project's properties---> Java Build Path ---> Libraries tab ---> Add External Jars
will allow you to add jars.
You need to download commonsIO from here.
No, but you could have something like:
bool b;
b = b.YourExtensionMethod();
If you're using multiple slides, and you can use jQuery, you can do the follow to deal with multiple sliders easily:
function updateRangeInput(elem) {_x000D_
$(elem).next().val($(elem).val());_x000D_
}
_x000D_
input { padding: 8px; border: 1px solid #ddd; color: #555; display: block; }_x000D_
input[type=text] { width: 100px; }_x000D_
input[type=range] { width: 400px; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<input type="range" min="0" max="100" oninput="updateRangeInput(this)" value="0">_x000D_
<input type="text" value="0">_x000D_
_x000D_
<input type="range" min="0" max="100" oninput="updateRangeInput(this)" value="50">_x000D_
<input type="text" value="50">
_x000D_
Also, by using oninput
on the <input type='range'>
you'll receive events while dragging the range.
if you try to close the window just after the print() call, it may close the window immediately and print() will don't work. This is what you should not do:
window.open();
...
window.print();
window.close();
This solution will work in Firefox, because on print() call, it waits until printing is done and then it continues processing javascript and close() the window. IE will fail with this because it calls the close() function without waiting for the print() call is done. The popup window will be closed before printing is done.
One way to solve it is by using the "onafterprint" event but I don' recommend it to you becasue these events only works in IE.
The best way is closing the popup window once the print dialog is closed (printing is done or cancelled). At this moment, the popup window will be focussed and you can use the "onfocus" event for closing the popup.
To do this, just insert this javascript embedded code in your popup window:
<script type="text/javascript">
window.print();
window.onfocus=function(){ window.close();}
</script>
Hope this hepls ;-)
Update:
For new chrome browsers it may still close too soon see here. I've implemented this change and it works for all current browsers: 2/29/16
setTimeout(function () { window.print(); }, 500);
window.onfocus = function () { setTimeout(function () { window.close(); }, 500); }
Simply use this:
white-space: pre-wrap; /* CSS3 */
white-space: -moz-pre-wrap; /* Firefox */
white-space: -pre-wrap; /* Opera <7 */
white-space: -o-pre-wrap; /* Opera 7 */
word-wrap: break-word; /* IE */
For me it worked after manually copying the sqljdbc4-2.jar into WEB-INF/lib folder. So please have a try on this too.
echo '<pre>';
var_dump($_SESSION);
echo '</pre>';
Or you can use print_r
if you don't care about types. If you use print_r
, you can make the second argument TRUE
so it will return instead of echo, useful for...
echo '<pre>' . print_r($_SESSION, TRUE) . '</pre>';
debugPrint()
(and CustomDebugStringConvertible
protocol)!Don't forget about debugPrint()
which works like print()
but most suitable for debugging.
Examples:
print("Hello World!")
becomes Hello World
debugPrint("Hello World!")
becomes "Hello World"
(Quotes!)print(1..<6)
becomes 1..<6
debugPrint(1..<6)
becomes Range(1..<6)
Any class can customize their debug string representation via CustomDebugStringConvertible
protocol.
The toggle tells Bootstrap what to do and the target tells Bootstrap which element is going to open. So whenever a link like that is clicked, a modal with an id of “basicModal” will appear.
With RHEL 7 / CentOS 7, firewalld was introduced to manage iptables. IMHO, firewalld is more suited for workstations than for server environments.
It is possible to go back to a more classic iptables setup. First, stop and mask the firewalld service:
systemctl stop firewalld
systemctl mask firewalld
Then, install the iptables-services package:
yum install iptables-services
Enable the service at boot-time:
systemctl enable iptables
Managing the service
systemctl [stop|start|restart] iptables
Saving your firewall rules can be done as follows:
service iptables save
or
/usr/libexec/iptables/iptables.init save
GNU linker, in my case companion of GCC 8.1.0, well detects not re-declared pure virtual methods, but above certain complexity of class design it fails to identify missing implementation of methods and answers with a flat "V-Table Missing",
or even tends to report missing implementation, in spite it is there.
The only solution then is to verify consistency of declaration of implementation manually, method by method.
If your SQL Server version supports the function FORMAT you could do it like this:
select format(getdate(), 'yyyy-MM-dd HH:mm:ss.fff')
There have been methodologies in all languages advocating for use of a single return statement in any function. However impossible it may be in certain code, some people do strive for that, however, it may end up making your code more complex (as in more lines of code), but on the other hand, somewhat easier to follow (as in logic flow).
This will not mess up garbage collection in any way!!
The better way to do it is to set a boolean value, if you want to listen to him.
boolean flag = false;
for(int i=0; i<array.length; ++i){
if(array[i] == valueToFind) {
flag = true;
break;
}
}
return flag;
Order Collection Limit :
$orderCollection = Mage::getResourceModel('sales/order_collection');
$orderCollection->getSelect()->limit(10);
foreach ($orderCollection->getItems() as $order) :
$orderModel = Mage::getModel('sales/order');
$order = $orderModel->load($order['entity_id']);
echo $order->getId().'<br>';
endforeach;
Simply convert the date to a string, and then concatenate the substrings you want out of it.
let time = date.toLocaleTimeString();
console.log(time.substr(0, 4) + time.substr(7, 3))
//=> 5:45 PM
I would suggest using the below method if you are trying to read the json data only.
URL requestUrl=new URL(url);
URLConnection con = requestUrl.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder sb=new StringBuilder();
int cp;
try {
while((cp=rd.read())!=-1){
sb.append((char)cp);
}
catch(Exception e){
}
String json=sb.toString();
I know this question has been answered but the answers i found here didn't work for my scenario ( or for Windows ).
I am using windows 10 laptop with PHP 7.2 in Xampp v3.2.4.
$command = 'php Cron.php send_email "'. $id .'"';
if ( substr(php_uname(), 0, 7) == "Windows" )
{
//windows
pclose(popen("start /B " . $command . " 1> temp/update_log 2>&1 &", "r"));
}
else
{
//linux
shell_exec( $command . " > /dev/null 2>&1 &" );
}
This worked perfectly for me.
I hope it will help someone with windows. Cheers.
Instead of gdb
, run gdbtui
. Or run gdb
with the -tui
switch. Or press C-x C-a after entering gdb
. Now you're in GDB's TUI mode.
Enter layout asm
to make the upper window display assembly -- this will automatically follow your instruction pointer, although you can also change frames or scroll around while debugging. Press C-x s to enter SingleKey mode, where run continue up down finish
etc. are abbreviated to a single key, allowing you to walk through your program very quickly.
+---------------------------------------------------------------------------+ B+>|0x402670 <main> push %r15 | |0x402672 <main+2> mov %edi,%r15d | |0x402675 <main+5> push %r14 | |0x402677 <main+7> push %r13 | |0x402679 <main+9> mov %rsi,%r13 | |0x40267c <main+12> push %r12 | |0x40267e <main+14> push %rbp | |0x40267f <main+15> push %rbx | |0x402680 <main+16> sub $0x438,%rsp | |0x402687 <main+23> mov (%rsi),%rdi | |0x40268a <main+26> movq $0x402a10,0x400(%rsp) | |0x402696 <main+38> movq $0x0,0x408(%rsp) | |0x4026a2 <main+50> movq $0x402510,0x410(%rsp) | +---------------------------------------------------------------------------+ child process 21518 In: main Line: ?? PC: 0x402670 (gdb) file /opt/j64-602/bin/jconsole Reading symbols from /opt/j64-602/bin/jconsole...done. (no debugging symbols found)...done. (gdb) layout asm (gdb) start (gdb)
$("#message > span").text("your text");
or
$("#message").find("span").text("your text");
or
$("span","#message").text("your text");
or
$("#message > a.close-notify").siblings('span').text("your text");
Can you try to change your json without data
key like below?
[{"target_id":9503123,"target_type":"user"}]
When you clone a repository with git clone
, it automatically creates a remote connection called origin
pointing back to the cloned repository. This is useful for developers creating a local copy of a central repository since it provides an easy way to pull upstream changes or publish local commits. This behavior is also why most Git-based projects call their central repository origin.
You can use pandas it has some built in functions for comparison. So if you want to select values of "A" that are met by the conditions of "B" and "C" (assuming you want back a DataFrame pandas object)
df[['A']][df.B.gt(50) & df.C.ne(900)]
df[['A']]
will give you back column A in DataFrame format.
pandas 'gt' function will return the positions of column B that are greater than 50 and 'ne' will return the positions not equal to 900.
On laravel 8.* I following steps work for me :
Run command composer remove package-name
on terminal
Remove Provider
and aliases
from Config/app.php
Remove related file from Config folder.
Remove from your code where you used .
This should work:
select * from syscat.tables
I don't know how stubhub's api works, but generally it should look like this:
s = requests.Session()
data = {"login":"my_login", "password":"my_password"}
url = "http://example.net/login"
r = s.post(url, data=data)
Now your session contains cookies provided by login form. To access cookies of this session simply use
s.cookies
Any further actions like another requests will have this cookie
You can't: It's a security feature in all modern browsers.
For IE8, it's off by default, but can be reactivated using a security setting:
When a file is selected by using the input type=file object, the value of the value property depends on the value of the "Include local directory path when uploading files to a server" security setting for the security zone used to display the Web page containing the input object.
The fully qualified filename of the selected file is returned only when this setting is enabled. When the setting is disabled, Internet Explorer 8 replaces the local drive and directory path with the string C:\fakepath\ in order to prevent inappropriate information disclosure.
In all other current mainstream browsers I know of, it is also turned off. The file name is the best you can get.
More detailed info and good links in this question. It refers to getting the value server-side, but the issue is the same in JavaScript before the form's submission.
The fragment already has startActivityForResult
, which would call onActivityResult
in the fragment if you use it, instead of getActivity()
...
TLDR; Performance-wise Any
seems to be slower (if I have set this up properly to evaluate both values at almost same time)
var list1 = Generate(1000000);
var forceListEval = list1.SingleOrDefault(o => o == "0123456789012");
if (forceListEval != "sdsdf")
{
var s = string.Empty;
var start2 = DateTime.Now;
if (!list1.Exists(o => o == "0123456789012"))
{
var end2 = DateTime.Now;
s += " Exists: " + end2.Subtract(start2);
}
var start1 = DateTime.Now;
if (!list1.Any(o => o == "0123456789012"))
{
var end1 = DateTime.Now;
s +=" Any: " +end1.Subtract(start1);
}
if (!s.Contains("sdfsd"))
{
}
testing list generator:
private List<string> Generate(int count)
{
var list = new List<string>();
for (int i = 0; i < count; i++)
{
list.Add( new string(
Enumerable.Repeat("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 13)
.Select(s =>
{
var cryptoResult = new byte[4];
new RNGCryptoServiceProvider().GetBytes(cryptoResult);
return s[new Random(BitConverter.ToInt32(cryptoResult, 0)).Next(s.Length)];
})
.ToArray()));
}
return list;
}
With 10M records
" Any: 00:00:00.3770377 Exists: 00:00:00.2490249"
With 5M records
" Any: 00:00:00.0940094 Exists: 00:00:00.1420142"
With 1M records
" Any: 00:00:00.0180018 Exists: 00:00:00.0090009"
With 500k, (I also flipped around order in which they get evaluated to see if there is no additional operation associated with whichever runs first.)
" Exists: 00:00:00.0050005 Any: 00:00:00.0100010"
With 100k records
" Exists: 00:00:00.0010001 Any: 00:00:00.0020002"
It would seem Any
to be slower by magnitude of 2.
Edit: For 5 and 10M records I changed the way it generates the list and Exists
suddenly became slower than Any
which implies there's something wrong in the way I am testing.
New testing mechanism:
private static IEnumerable<string> Generate(int count)
{
var cripto = new RNGCryptoServiceProvider();
Func<string> getString = () => new string(
Enumerable.Repeat("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 13)
.Select(s =>
{
var cryptoResult = new byte[4];
cripto.GetBytes(cryptoResult);
return s[new Random(BitConverter.ToInt32(cryptoResult, 0)).Next(s.Length)];
})
.ToArray());
var list = new ConcurrentBag<string>();
var x = Parallel.For(0, count, o => list.Add(getString()));
return list;
}
private static void Test()
{
var list = Generate(10000000);
var list1 = list.ToList();
var forceListEval = list1.SingleOrDefault(o => o == "0123456789012");
if (forceListEval != "sdsdf")
{
var s = string.Empty;
var start1 = DateTime.Now;
if (!list1.Any(o => o == "0123456789012"))
{
var end1 = DateTime.Now;
s += " Any: " + end1.Subtract(start1);
}
var start2 = DateTime.Now;
if (!list1.Exists(o => o == "0123456789012"))
{
var end2 = DateTime.Now;
s += " Exists: " + end2.Subtract(start2);
}
if (!s.Contains("sdfsd"))
{
}
}
Edit2: Ok so to eliminate any influence from generating test data I wrote it all to file and now read it from there.
private static void Test()
{
var list1 = File.ReadAllLines("test.txt").Take(500000).ToList();
var forceListEval = list1.SingleOrDefault(o => o == "0123456789012");
if (forceListEval != "sdsdf")
{
var s = string.Empty;
var start1 = DateTime.Now;
if (!list1.Any(o => o == "0123456789012"))
{
var end1 = DateTime.Now;
s += " Any: " + end1.Subtract(start1);
}
var start2 = DateTime.Now;
if (!list1.Exists(o => o == "0123456789012"))
{
var end2 = DateTime.Now;
s += " Exists: " + end2.Subtract(start2);
}
if (!s.Contains("sdfsd"))
{
}
}
}
10M
" Any: 00:00:00.1640164 Exists: 00:00:00.0750075"
5M
" Any: 00:00:00.0810081 Exists: 00:00:00.0360036"
1M
" Any: 00:00:00.0190019 Exists: 00:00:00.0070007"
500k
" Any: 00:00:00.0120012 Exists: 00:00:00.0040004"
When submitting a form, you tell your browser to send, via the HTTP protocol, a message on the network, properly enveloped in a TCP/IP protocol message structure. An HTML page has a way to send data to the server: by using <form>
s.
When a form is submitted, an HTTP Request is created and sent to the server, the message will contain the field names in the form and the values filled in by the user. This transmission can happen with POST
or GET
HTTP methods.
POST
tells your browser to build an HTTP message and put all content in the body of the message (a very useful way of doing things, more safe and also flexible).GET
will submit the form data in the querystring. It has some constraints about data representation and length.Attribute enctype
has sense only when using POST
method. When specified, it instructs the browser to send the form by encoding its content in a specific way. From MDN - Form enctype:
When the value of the method attribute is post, enctype is the MIME type of content that is used to submit the form to the server.
application/x-www-form-urlencoded
: This is the default. When the form is sent, all names and values are collected and URL Encoding is performed on the final string.multipart/form-data
: Characters are NOT encoded. This is important when the form has a file upload control. You want to send the file binary and this ensures that bitstream is not altered.text/plain
: Spaces get converted, but no more encoding is performed.When submitting forms, some security concerns can arise as stated in RFC 7578 Section 7: Multipart form data - Security considerations:
All form-processing software should treat user supplied form-data
with sensitivity, as it often contains confidential or personally
identifying information. There is widespread use of form "auto-fill" features in web browsers; these might be used to trick users to
unknowingly send confidential information when completing otherwise
innocuous tasks. multipart/form-data does not supply any features
for checking integrity, ensuring confidentiality, avoiding user
confusion, or other security features; those concerns must be
addressed by the form-filling and form-data-interpreting applications.Applications that receive forms and process them must be careful not to supply data back to the requesting form-processing site that was not intended to be sent.
It is important when interpreting the filename of the Content-
Disposition header field to not inadvertently overwrite files in the
recipient's file space.
This concerns you if you are a developer and your server will process forms submitted by users which might end up containing sensitive information.
mongoose.connect('mongodb://localhost:27017/').then(() => {
console.log("Connected to Database");
}).catch((err) => {
console.log("Not Connected to Database ERROR! ", err);
});
Better just connect to the localhost Mongoose Database only and create your own collections. Don't forget to mention the port number. (Default: 27017)
For the best view, download Mongoose-compass for MongoDB UI.
Best practice: one form per product is definitely the way to go.
Benefits:
In your specific situation
If you only ever intend to have one form element, in this case a submit
button, one form for all should work just fine.
My recommendation Do one form per product, and change your markup to something like:
<form method="post" action="">
<input type="hidden" name="product_id" value="123">
<button type="submit" name="action" value="add_to_cart">Add to Cart</button>
</form>
This will give you a much cleaner and usable POST
. No parsing. And it will allow you to add more parameters in the future (size, color, quantity, etc).
Note: There's no technical benefit to using
<button>
vs.<input>
, but as a programmer I find it cooler to work withaction=='add_to_cart'
thanaction=='Add to Cart'
. Besides, I hate mixing presentation with logic. If one day you decide that it makes more sense for the button to say "Add" or if you want to use different languages, you could do so freely without having to worry about your back-end code.
1) PYTHONPATH
is an environment variable which you can set to add additional directories where python will look for modules and packages. e.g.:
# make python look in the foo subdirectory of your home directory for
# modules and packages
export PYTHONPATH=${PYTHONPATH}:${HOME}/foo
Here I use the sh
syntax. For other shells (e.g. csh
,tcsh
), the syntax would be slightly different. To make it permanent, set the variable in your shell's init file (usually ~/.bashrc).
2) Ubuntu comes with python already installed. There may be reasons for installing other (independent) python versions, but I've found that to be rarely necessary.
3) The folder where your modules live is dependent on PYTHONPATH
and where the directories were set up when python was installed. For the most part, the installed stuff you shouldn't care about where it lives -- Python knows where it is and it can find the modules. Sort of like issuing the command ls
-- where does ls
live? /usr/bin
? /bin
? 99% of the time, you don't need to care -- Just use ls
and be happy that it lives somewhere on your PATH
so the shell can find it.
4) I'm not sure I understand the question. 3rd party modules usually come with install instructions. If you follow the instructions, python should be able to find the module and you shouldn't have to care about where it got installed.
5) Configure PYTHONPATH
to include the directory where your module resides and python will be able to find your module.
I was searching to solve the following error message:
unicodedecodeerror: 'ascii' codec can't decode byte 0xe2 in position 5454: ordinal not in range(128)
I finally got it fixed by specifying 'encoding':
f = open('../glove/glove.6B.100d.txt', encoding="utf-8")
Wish it could help you too.
just remove the alignItems: 'center'
in the container styles and add textAlign: "center"
to the line1
style like given below.
It will work well
container: {
flex: 1,
justifyContent: 'center',
backgroundColor: '#F5FCFF',
borderWidth: 1,
}
line1: {
backgroundColor: '#FDD7E4',
textAlign:'center'
},
I think the proper way to use **kwargs
in Python when it comes to default values is to use the dictionary method setdefault
, as given below:
class ExampleClass:
def __init__(self, **kwargs):
kwargs.setdefault('val', value1)
kwargs.setdefault('val2', value2)
In this way, if a user passes 'val' or 'val2' in the keyword args
, they will be used; otherwise, the default values that have been set will be used.
Always state the workbook, worksheet and the cell/range.
For example:
Thisworkbook.Worksheets("fred").cells(1,1)
Workbooks("bob").Worksheets("fred").cells(1,1)
Because end users will always just click buttons and as soon as the focus moves off of the workbook the code wants to work with then things go completely wrong.
And never use the index of a workbook.
Workbooks(1).Worksheets("fred").cells(1,1)
You don't know what other workbooks will be open when the user runs your code.
Using Math.floor()
is one way of doing this.
More information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor
No, #region does not exist in the T-SQL language.
You can get code-folding using begin-end blocks:
-- my region begin -- code goes here end
I'm not sure I'd recommend using them for this unless the code cannot be acceptably refactored by other means though!
There`s my solution. It will compare arrays which also have objects and arrays. Elements can be stay in any positions. Example:
const array1 = [{a: 1}, {b: 2}, { c: 0, d: { e: 1, f: 2, } }, [1,2,3,54]];
const array2 = [{a: 1}, {b: 2}, { c: 0, d: { e: 1, f: 2, } }, [1,2,3,54]];
const arraysCompare = (a1, a2) => {
if (a1.length !== a2.length) return false;
const objectIteration = (object) => {
const result = [];
const objectReduce = (obj) => {
for (let i in obj) {
if (typeof obj[i] !== 'object') {
result.push(`${i}${obj[i]}`);
} else {
objectReduce(obj[i]);
}
}
};
objectReduce(object);
return result;
};
const reduceArray1 = a1.map(item => {
if (typeof item !== 'object') return item;
return objectIteration(item).join('');
});
const reduceArray2 = a2.map(item => {
if (typeof item !== 'object') return item;
return objectIteration(item).join('');
});
const compare = reduceArray1.map(item => reduceArray2.includes(item));
return compare.reduce((acc, item) => acc + Number(item)) === a1.length;
};
console.log(arraysCompare(array1, array2));
Johnny's solution is good. I found that adding min-width:100%, really helps images fill the entire circle. You could do this with a combination of JavaScript to get optimal results or use ImageMagick - http://www.imagemagick.org/script/index.php if you're really serious about getting it right.
.image-cropper {_x000D_
_x000D_
width: 35px;_x000D_
_x000D_
height: 35px;_x000D_
_x000D_
position: relative;_x000D_
_x000D_
overflow: hidden;_x000D_
_x000D_
border-radius: 50%;_x000D_
_x000D_
}_x000D_
_x000D_
.image-cropper__image {_x000D_
_x000D_
display: inline;_x000D_
_x000D_
margin: 0 auto;_x000D_
_x000D_
height: 100%;_x000D_
_x000D_
min-width: 100%;_x000D_
_x000D_
}
_x000D_
<div class="image-cropper">_x000D_
<img src="#" class="image-cropper__image">_x000D_
</div>
_x000D_
On android 2.2 you can input multiple language and switch by sliding on the spacebar. Go in the settings under "language and keyboard" and then "Android Keyboard", "Input language".
Hope this helps.
Array notaion is the best way of combining styles in react native.
This shows how to combine 2 Style objects,
<Text style={[styles.base, styles.background]} >Test </Text>
this shows how to combine Style object and property,
<Text style={[styles.base, {color: 'red'}]} >Test </Text>
This will work on any react native application.
Any best practices here?
Use the Maven advanced reactor options, more specifically:
-pl, --projects
Build specified reactor projects instead of all projects
-am, --also-make
If project list is specified, also build projects required by the list
So just cd
into the parent P directory and run:
mvn install -pl B -am
And this will build B and the modules required by B.
Note that you need to use a colon if you are referencing an artifactId
which differs from the directory name:
mvn install -pl :B -am
As described here: https://stackoverflow.com/a/26439938/480894
Maybe your JSON Object
is right,but the response that you received is not your valid data.Just like when you connect the invalid WiFi
,you may received a strange response < html>.....< /html>
that GSON
can not parse.
you may need to do some try..catch..
for this strange response to avoid crash.
I just started using STS Eclipse with first time using Maven. The project I setup already had its own settings.xml. If this is the case, you'll want to update your settings.xml file in run configuration.
right click the pom.xml and "Run As" -> "Run Configurations..."
where it says "User settings" click on the File button and add the settings.xml.
I think this is specific to your project but my "Goals" is set to "clean install" and I checked on "Skip Tests."
In ASP.NET Core, there are configuration providers for reading configurations from almost anywhere such as files e.g. JSON, INI or XML, environment variables, Azure key vault, command-line arguments, etc. and many more sources. I have written a step by step guide to show you how can you configure your application settings in various files such as JSON, INI or XML and how can you read those settings from your application code. I will also demonstrate how can you read application settings as custom .NET types (classes) and how can you use the built-in ASP.NET Core dependency injection to read your configuration settings in multiple classes, services or even projects available in your solution.
dt = dt.AsEnumerable().GroupBy(r => r.Field<int>("ID")).Select(g => g.First()).CopyToDataTable();
Review your first line. Your stack trace is clearly not from the code you've pasted here, so I don't know precisely what you've done.
>>> my_set=([1,2,3,4])
>>> my_set
[1, 2, 3, 4]
>>> type(my_set)
<type 'list'>
>>> list(my_set)
[1, 2, 3, 4]
>>> type(_)
<type 'list'>
What you wanted was set([1, 2, 3, 4])
.
>>> my_set = set([1, 2, 3, 4])
>>> my_set
set([1, 2, 3, 4])
>>> type(my_set)
<type 'set'>
>>> list(my_set)
[1, 2, 3, 4]
>>> type(_)
<type 'list'>
The "not callable" exception means you were doing something like set()()
- attempting to call a set
instance.
To cause the keyboard to appear, use
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
This method is more reliable than invoking the InputMethodManager directly.
To close it, use
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
I had similar issue. To debug the problem, I've run Wireshark and capture request generated by my code. Then I used XML Spy trial to create a SOAP request (assuming you have WSDL) and compared those two.
This should give you a hint what goes wrong.
The Abstract Factory pattern is used in various places.
E.g., DatagramSocketImplFactory
, PreferencesFactory
. There are many more---search the Javadoc for interfaces which have the word "Factory" in their name.
Also there are quite a few instances of the Factory pattern, too.
If I understand you need following code. (passing expression lambda by parameter) The Method
public static void Method(Expression<Func<int, bool>> predicate) {
int[] number={1,2,3,4,5,6,7,8,9,10};
var newList = from x in number
.Where(predicate.Compile()) //here compile your clausuly
select x;
newList.ToList();//return a new list
}
Calling method
Method(v => v.Equals(1));
You can do the same in their class, see this is example.
public string Name {get;set;}
public static List<Class> GetList(Expression<Func<Class, bool>> predicate)
{
List<Class> c = new List<Class>();
c.Add(new Class("name1"));
c.Add(new Class("name2"));
var f = from g in c.
Where (predicate.Compile())
select g;
f.ToList();
return f;
}
Calling method
Class.GetList(c=>c.Name=="yourname");
I hope this is useful
PHP 7.1.0 has introduced the iterable
pseudo-type and the is_iterable()
function, which is specially designed for such a purpose:
This […] proposes a new
iterable
pseudo-type. This type is analogous tocallable
, accepting multiple types instead of one single type.
iterable
accepts anyarray
or object implementingTraversable
. Both of these types are iterable usingforeach
and can be used withyield
from within a generator.
function foo(iterable $iterable) {
foreach ($iterable as $value) {
// ...
}
}
This […] also adds a function
is_iterable()
that returns a boolean:true
if a value is iterable and will be accepted by theiterable
pseudo-type,false
for other values.
var_dump(is_iterable([1, 2, 3])); // bool(true)
var_dump(is_iterable(new ArrayIterator([1, 2, 3]))); // bool(true)
var_dump(is_iterable((function () { yield 1; })())); // bool(true)
var_dump(is_iterable(1)); // bool(false)
var_dump(is_iterable(new stdClass())); // bool(false)
You can also use the function is_array($var)
to check if the passed variable is an array:
<?php
var_dump( is_array(array()) ); // true
var_dump( is_array(array(1, 2, 3)) ); // true
var_dump( is_array($_SERVER) ); // true
?>
Read more in How to check if a variable is an array in PHP?
I am also looking for an answer to this question, (to clarify, I want to be able to draw an image with user defined opacity such as how you can draw shapes with opacity) if you draw with primitive shapes you can set fill and stroke color with alpha to define the transparency. As far as I have concluded right now, this does not seem to affect image drawing.
//works with shapes but not with images
ctx.fillStyle = "rgba(255, 255, 255, 0.5)";
I have concluded that setting the globalCompositeOperation
works with images.
//works with images
ctx.globalCompositeOperation = "lighter";
I wonder if there is some kind third way of setting color so that we can tint images and make them transparent easily.
EDIT:
After further digging I have concluded that you can set the transparency of an image by setting the globalAlpha
parameter BEFORE you draw the image:
//works with images
ctx.globalAlpha = 0.5
If you want to achieve a fading effect over time you need some kind of loop that changes the alpha value, this is fairly easy, one way to achieve it is the setTimeout
function, look that up to create a loop from which you alter the alpha over time.
This link goes to the best comparison chart around, directly from the Microsoft. It compares ALL aspects of all MS SQL server editions. To compare three editions you are asking about, just focus on the last three columns of every table in there.
Summary compiled from the above document:
* = contains the feature SQLEXPR SQLEXPRWT SQLEXPRADV ---------------------------------------------------------------------------- > SQL Server Core * * * > SQL Server Management Studio - * * > Distributed Replay – Admin Tool - * * > LocalDB - * * > SQL Server Data Tools (SSDT) - - * > Full-text and semantic search - - * > Specification of language in query - - * > some of Reporting services features - - *
Just to clarify, there is a big difference between these two actions, as suggested by Jean-François Corbett.
One action is to copy / load the actual data FROM the Range("A2:A9")
INTO a Variant Array called vArray
(Changed to avoid confusion between Variant Array and Sheet both called Src):
vArray = Sheets("Src").Range("A2:A9").Value
while the other simply sets up a Range variable (SrcRange) with the ADDRESS of the range Sheets("Src").Range("A2:A9")
:
Set SrcRange = Sheets("Src").Range("A2:A9")
In this case, the data is not copied, and remains where it is, but can now be accessed in much the same way as an Array. That is often perfectly adequate, but if you need to repeatedly access, test or calculate with that data, loading it into an Array first will be MUCH faster.
For example, say you want to check a "database" (large sheet) against a list of known Suburbs and Postcodes. Both sets of data are in separate sheets, but if you want it to run fast, load the suburbs and postcodes into an Array (lives in memory), then run through each line of the main database, testing against the array data. This will be much faster than if you access both from their original sheets.
I'd create the array and then append the object literals to it.
var myColumnDefs = [];
for ( var i=0 ; i < oFullResponse.results.length; i++) {
console.log(oFullResponse.results[i].label);
myColumnDefs[myColumnDefs.length] = {key:oFullResponse.results[i].label, sortable:true, resizeable:true};
}
Its just because of the load time angular takes to give you the current state.
If you try to get the current state by using $timeout
function then it will give you correct result in $state.current.name
$timeout(function(){
$rootScope.currState = $state.current.name;
})
Anyone who is interested in returning anything with any statuscode with returning ResponseMessage:
//CreateResponse(HttpStatusCode, T value)
return ResponseMessage(Request.CreateResponse(HttpStatusCode.XX, object));
E0_copy
is not a deep copy. You don't make a deep copy using list()
(Both list(...)
and testList[:]
are shallow copies).
You use copy.deepcopy(...)
for deep copying a list.
deepcopy(x, memo=None, _nil=[])
Deep copy operation on arbitrary Python objects.
See the following snippet -
>>> a = [[1, 2, 3], [4, 5, 6]]
>>> b = list(a)
>>> a
[[1, 2, 3], [4, 5, 6]]
>>> b
[[1, 2, 3], [4, 5, 6]]
>>> a[0][1] = 10
>>> a
[[1, 10, 3], [4, 5, 6]]
>>> b # b changes too -> Not a deepcopy.
[[1, 10, 3], [4, 5, 6]]
Now see the deepcopy
operation
>>> import copy
>>> b = copy.deepcopy(a)
>>> a
[[1, 10, 3], [4, 5, 6]]
>>> b
[[1, 10, 3], [4, 5, 6]]
>>> a[0][1] = 9
>>> a
[[1, 9, 3], [4, 5, 6]]
>>> b # b doesn't change -> Deep Copy
[[1, 10, 3], [4, 5, 6]]
I was also looking to list repositories in SVN. I did something like this on shell prompt:
~$ svn list https://www.repo.rr.com/svn/main/team/gaurav
Test/
Test2/
Test3/
Test4/
Test5/
Test6/
It is better to include stdlib.h
. Since without stdlibg it takes long as long
what about using the official API?
According to the API doc:
DESTROY: Removes the datepicker functionality completely. This will return the element back to its pre-init state.
Use:
$("#txtSearch").datepicker("destroy");
to restore the input to its normal behaviour and
$("#txtSearch").datepicker(/*options*/);
again to show the datapicker again.
A TextBlock does not actually inherit from Control so it does not have properties that you would generally associate with a Control. Your best bet for adding a border in a style is to replace the TextBlock with a Label
See this link for more on the differences between a TextBlock and other Controls
Here is my current code, the 2nd line works if I comment the 3rd line, but don't work if I leave it how it is.
var page_title = $(this).val().replace(/[^a-zA-Z0-9\s]/g, '');
page_title = page_title.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
page_title = page_title.replace(/([\s]+)/g, '-');
String[] str = new String[0];
?
First, you may want to install glances:
sudo apt-get install python-pip build-essential python-dev lm-sensors
sudo pip install psutil logutils bottle batinfo https://bitbucket.org/gleb_zhulik/py3sensors/get/tip.tar.gz zeroconf netifaces pymdstat influxdb elasticsearch potsdb statsd pystache docker-py pysnmp pika py-cpuinfo bernhard
sudo pip install glances
Then run it in the terminal!
glances
In your Python code, add at the begin of the file, the following:
import os
import gc # Garbage Collector
After using the "Big" variable (for example: myBigVar) for which, you would like to release memory, write in your python code the following:
del myBigVar
gc.collect()
In another terminal, run your python code and observe in the "glances" terminal, how the memory is managed in your system!
Good luck!
P.S. I assume you are working on a Debian or Ubuntu system
Git
is all about commits.
And Head
points to the commit which you currently checked out.
$ git cat-file -t HEAD
commit
Whenever you checkout a branch, the HEAD points to the latest commit on that branch. Contents of HEAD can checked as below (for master branch):
$ cat .git/refs/heads/master
b089141cc8a7d89d606b2f7c15bfdc48640a8e25
Set the traditional property to true before making the get call. i.e.:
jQuery.ajaxSettings.traditional = true
$.get('/controller/MyAction', { vals: arrayOfValues }, function (data) {...
The problem is in the network layer. Here are the status codes explained:
Connection refused
: The peer is not listening on the respective network port you're trying to connect to. This usually means that either a firewall is actively denying the connection or the respective service is not started on the other site or is overloaded.
Connection timed out
: During the attempt to establish the TCP connection, no response came from the other side within a given time limit. In the context of urllib this may also mean that the HTTP response did not arrive in time. This is sometimes also caused by firewalls, sometimes by network congestion or heavy load on the remote (or even local) site.
That said, it is probably not a problem in your script, but on the remote site. If it's occuring occasionally, it indicates that the other site has load problems or the network path to the other site is unreliable.
Also, as it is a problem with the network, you cannot tell what happened on the other side. It is possible that the packets travel fine in the one direction but get dropped (or misrouted) in the other.
It is also not a (direct) DNS problem, that would cause another error (Name or service not known or something similar). It could however be the case that the DNS is configured to return different IP addresses on each request, which would connect you (DNS caching left aside) to different addresses hosts on each connection attempt. It could in turn be the case that some of these hosts are misconfigured or overloaded and thus cause the aforementioned problems.
As suggested in the another answer, using a packet analyzer can help to debug the issue. You won't see much however except the packets reflecting exactly what the error message says.
To rule out network congestion as a problem you could use a tool like mtr
or traceroute
or even ping
to see if packets get lost to the remote site. Note that, if you see loss in mtr (and any traceroute tool for that matter), you must always consider the first host where loss occurs (in the route from yours to remote) as the one dropping packets, due to the way ICMP works. If the packets get lost only at the last hop over a long time (say, 100 packets), that host definetly has an issue. If you see that this behaviour is persistent (over several days), you might want to contact the administrator.
Loss in a middle of the route usually corresponds to network congestion (possibly due to maintenance), and there's nothing you could do about it (except whining at the ISP about missing redundance).
If network congestion is not a problem (i.e. not more than, say, 5% of the packets get lost), you should contact the remote server administrator to figure out what's wrong. He may be able to see relevant infos in system logs. Running a packet analyzer on the remote site might also be more revealing than on the local site. Checking whether the port is open using netstat -tlp
is definetly recommended then.
I like to use:
(strlen(string) + 1 ) * sizeof(char)
This will give you the buffer size in bytes. You can use this with snprintf() may help:
const char* message = "%s, World!";
char* string = (char*)malloc((strlen(message)+1))*sizeof(char));
snprintf(string, (strlen(message)+1))*sizeof(char), message, "Hello");
Cheers! Function: size_t strlen (const char *s)
You can have a look at the source code (here it is v1.7.2).
Except for the animation that we can set, this also keep in memory the old display style (which is not in all cases block
, it can also be inline
, table-cell
, ...).
For Angular 8 or posterior @ViewChild have an additional parameter called opts, which have two properties: read and static, read is optional. You can use it like so:
// ...
@ViewChild('mydiv', { static: false }) public mydiv: ElementRef;
constructor() {
// ...
<div #mydiv></div>
NOTE: Static: false is not required anymore in Angular 9. (just { static: true }
when you are going to use that variable inside ngOnInit)
This seemed to have worked for me!
Mat a_image = imread(argv[1]);
cvtColor(a_image, a_image, CV_BGR2GRAY);
GaussianBlur(a_image, a_image, Size(7,7), 1.5, 1.5);
threshold(a_image, a_image, 100, 255, CV_THRESH_BINARY);
UPDATE: In iPhone OS 3.0 and later UITableViewCell
now has a backgroundColor
property that makes this really easy (especially in combination with the [UIColor colorWithPatternImage:]
initializer). But I'll leave the 2.0 version of the answer here for anyone that needs it…
It's harder than it really should be. Here's how I did this when I had to do it:
You need to set the UITableViewCell's backgroundView property to a custom UIView that draws the border and background itself in the appropriate colors. This view needs to be able to draw the borders in 4 different modes, rounded on the top for the first cell in a section, rounded on the bottom for the last cell in a section, no rounded corners for cells in the middle of a section, and rounded on all 4 corners for sections that contain one cell.
Unfortunately I couldn't figure out how to have this mode set automatically, so I had to set it in the UITableViewDataSource's -cellForRowAtIndexPath method.
It's a real PITA but I've confirmed with Apple engineers that this is currently the only way.
Update Here's the code for that custom bg view. There's a drawing bug that makes the rounded corners look a little funny, but we moved to a different design and scrapped the custom backgrounds before I had a chance to fix it. Still this will probably be very helpful for you:
//
// CustomCellBackgroundView.h
//
// Created by Mike Akers on 11/21/08.
// Copyright 2008 __MyCompanyName__. All rights reserved.
//
#import <UIKit/UIKit.h>
typedef enum {
CustomCellBackgroundViewPositionTop,
CustomCellBackgroundViewPositionMiddle,
CustomCellBackgroundViewPositionBottom,
CustomCellBackgroundViewPositionSingle
} CustomCellBackgroundViewPosition;
@interface CustomCellBackgroundView : UIView {
UIColor *borderColor;
UIColor *fillColor;
CustomCellBackgroundViewPosition position;
}
@property(nonatomic, retain) UIColor *borderColor, *fillColor;
@property(nonatomic) CustomCellBackgroundViewPosition position;
@end
//
// CustomCellBackgroundView.m
//
// Created by Mike Akers on 11/21/08.
// Copyright 2008 __MyCompanyName__. All rights reserved.
//
#import "CustomCellBackgroundView.h"
static void addRoundedRectToPath(CGContextRef context, CGRect rect,
float ovalWidth,float ovalHeight);
@implementation CustomCellBackgroundView
@synthesize borderColor, fillColor, position;
- (BOOL) isOpaque {
return NO;
}
- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
// Initialization code
}
return self;
}
- (void)drawRect:(CGRect)rect {
// Drawing code
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(c, [fillColor CGColor]);
CGContextSetStrokeColorWithColor(c, [borderColor CGColor]);
if (position == CustomCellBackgroundViewPositionTop) {
CGContextFillRect(c, CGRectMake(0.0f, rect.size.height - 10.0f, rect.size.width, 10.0f));
CGContextBeginPath(c);
CGContextMoveToPoint(c, 0.0f, rect.size.height - 10.0f);
CGContextAddLineToPoint(c, 0.0f, rect.size.height);
CGContextAddLineToPoint(c, rect.size.width, rect.size.height);
CGContextAddLineToPoint(c, rect.size.width, rect.size.height - 10.0f);
CGContextStrokePath(c);
CGContextClipToRect(c, CGRectMake(0.0f, 0.0f, rect.size.width, rect.size.height - 10.0f));
} else if (position == CustomCellBackgroundViewPositionBottom) {
CGContextFillRect(c, CGRectMake(0.0f, 0.0f, rect.size.width, 10.0f));
CGContextBeginPath(c);
CGContextMoveToPoint(c, 0.0f, 10.0f);
CGContextAddLineToPoint(c, 0.0f, 0.0f);
CGContextStrokePath(c);
CGContextBeginPath(c);
CGContextMoveToPoint(c, rect.size.width, 0.0f);
CGContextAddLineToPoint(c, rect.size.width, 10.0f);
CGContextStrokePath(c);
CGContextClipToRect(c, CGRectMake(0.0f, 10.0f, rect.size.width, rect.size.height));
} else if (position == CustomCellBackgroundViewPositionMiddle) {
CGContextFillRect(c, rect);
CGContextBeginPath(c);
CGContextMoveToPoint(c, 0.0f, 0.0f);
CGContextAddLineToPoint(c, 0.0f, rect.size.height);
CGContextAddLineToPoint(c, rect.size.width, rect.size.height);
CGContextAddLineToPoint(c, rect.size.width, 0.0f);
CGContextStrokePath(c);
return; // no need to bother drawing rounded corners, so we return
}
// At this point the clip rect is set to only draw the appropriate
// corners, so we fill and stroke a rounded rect taking the entire rect
CGContextBeginPath(c);
addRoundedRectToPath(c, rect, 10.0f, 10.0f);
CGContextFillPath(c);
CGContextSetLineWidth(c, 1);
CGContextBeginPath(c);
addRoundedRectToPath(c, rect, 10.0f, 10.0f);
CGContextStrokePath(c);
}
- (void)dealloc {
[borderColor release];
[fillColor release];
[super dealloc];
}
@end
static void addRoundedRectToPath(CGContextRef context, CGRect rect,
float ovalWidth,float ovalHeight)
{
float fw, fh;
if (ovalWidth == 0 || ovalHeight == 0) {// 1
CGContextAddRect(context, rect);
return;
}
CGContextSaveGState(context);// 2
CGContextTranslateCTM (context, CGRectGetMinX(rect),// 3
CGRectGetMinY(rect));
CGContextScaleCTM (context, ovalWidth, ovalHeight);// 4
fw = CGRectGetWidth (rect) / ovalWidth;// 5
fh = CGRectGetHeight (rect) / ovalHeight;// 6
CGContextMoveToPoint(context, fw, fh/2); // 7
CGContextAddArcToPoint(context, fw, fh, fw/2, fh, 1);// 8
CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 1);// 9
CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 1);// 10
CGContextAddArcToPoint(context, fw, 0, fw, fh/2, 1); // 11
CGContextClosePath(context);// 12
CGContextRestoreGState(context);// 13
}
https://developers.google.com/chrome-developer-tools/docs/settings
Don't need a regex
.
string[: string.find(' ')]
There is many way to watch multiple values :
//angular 1.1.4
$scope.$watchCollection(['foo', 'bar'], function(newValues, oldValues){
// do what you want here
});
or more recent version
//angular 1.3
$scope.$watchGroup(['foo', 'bar'], function(newValues, oldValues, scope) {
//do what you want here
});
Read official doc for more informations : https://docs.angularjs.org/api/ng/type/$rootScope.Scope
AFAIK there is no native jquery function that does this. Best option would be to process the conversion on the server. How you do this depends on what language you are using (.net, php etc.). You can pass the content of the div to the function that handles the conversion, which would return a pdf to the user.
Delete your "body background image code" then paste this code:
html {
background: url(../img/background.jpg) no-repeat center center fixed #000;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
You're close, but you want name to be an XAttribute
rather than XElement
:
XDocument doc = XDocument.Load(spath);
XElement root = new XElement("Snippet");
root.Add(new XAttribute("name", "name goes here"));
root.Add(new XElement("SnippetCode", "SnippetCode"));
doc.Element("Snippets").Add(root);
doc.Save(spath);
Here's one way of achieving this. You need to add incremental attribute to your html or it won't work.
window.onload = function() {_x000D_
var tf = document.getElementById('textField');_x000D_
var button = document.getElementById('b');_x000D_
button.disabled = true;_x000D_
var onKeyChange = function textChange() {_x000D_
button.disabled = (tf.value === "") ? true : false;_x000D_
}_x000D_
tf.addEventListener('keyup', onKeyChange);_x000D_
tf.addEventListener('search', onKeyChange);_x000D_
_x000D_
}
_x000D_
<input id="textField" type="search" placeholder="search" incremental="incremental">_x000D_
<button id="b">Go!</button>
_x000D_
Your src property is an object because you are setting the src element to be the entire image you created in JavaScript.
Try
document["pic1"].src = searchPic.src;
Highly recommend something more like this:
public class Person {
public string Name {get; set;}
public string Email {get; set;}
}
var people = new List<Person>();
Easier to read, easy to code.
Before I get to my reiterated answer; I am confessing that the only answer I would accept here is this one by KM. above. I down voted the other answers because none of them actually answered the question asked or they were not adequate. PRINT output does indeed show up in the Message window, but that is not what was asked at all.
Why doesn't the PRINT statement output show during my Stored Procedure execution?
The short version of this answer is that you are sending your sproc's execution over to the SQL server and it isn't going to respond until it is finished with the whole transaction. Here is a better answer located at this external link.
Don't do these things
Alternative to PRINT inside of a Stored Procedure
Really this is kind of an icky work around in my opinion because the syntax is confusing in the context that it is being used in, but who knows maybe it will be updated in the future by Microsoft. I just don't like the idea of raising an error for the sole purpose of printing out debug info...
It seems like the only way around this issue is to use, as has been explained numerous times already RAISERROR WITH NOWAIT. I am providing an example and pointing out a small problem with this approach:
ALTER
--CREATE
PROCEDURE [dbo].[PrintVsRaiseErrorSprocExample]
AS
BEGIN
SET NOCOUNT ON;
-- This will print immediately
RAISERROR ('RE Start', 0, 1) WITH NOWAIT
SELECT 1;
-- Five second delay to simulate lengthy execution
WAITFOR DELAY '00:00:05'
-- This will print after the five second delay
RAISERROR ('RE End', 0, 1) WITH NOWAIT
SELECT 2;
END
GO
EXEC [dbo].[PrintVsRaiseErrorSprocExample]
Both SELECT statement results will only show after the execution is finished and the print statements will show in the order shown above.
Potential problem with this approach
Let's say you have both your PRINT statement and RAISERROR statement one after the other, then they both print. I'm sure this has something to do with buffering, but just be aware that this can happen.
ALTER
--CREATE
PROCEDURE [dbo].[PrintVsRaiseErrorSprocExample2]
AS
BEGIN
SET NOCOUNT ON;
-- Both the PRINT and RAISERROR statements will show
PRINT 'P Start';
RAISERROR ('RE Start', 0, 1) WITH NOWAIT
SELECT 1;
WAITFOR DELAY '00:00:05'
-- Both the PRINT and RAISERROR statements will show
PRINT 'P End'
RAISERROR ('RE End', 0, 1) WITH NOWAIT
SELECT 2;
END
GO
EXEC [dbo].[PrintVsRaiseErrorSprocExample2]
Therefore the work around here is, don't use both PRINT and RAISERROR, just choose one over the other. If you want your output to show during the execution of a sproc then use RAISERROR WITH NOWAIT.
On Windows 10
insert at beggining this:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
Strange, but it works for me! (Together with input()
at the end, of course)
The problem of some methods like navigator.onLine
is that they are not compatible with some browsers and mobile versions, an option that helped me a lot was to use the classic XMLHttpRequest
method and also foresee the possible case that the file was stored in cache with response XMLHttpRequest.status
is greater than 200 and less than 304.
Here is my code:
var xhr = new XMLHttpRequest();
//index.php is in my web
xhr.open('HEAD', 'index.php', true);
xhr.send();
xhr.addEventListener("readystatechange", processRequest, false);
function processRequest(e) {
if (xhr.readyState == 4) {
//If you use a cache storage manager (service worker), it is likely that the
//index.php file will be available even without internet, so do the following validation
if (xhr.status >= 200 && xhr.status < 304) {
console.log('On line!');
} else {
console.log('Offline :(');
}
}
}