I have been in stuck with similar problem. Finally figured out the what was the root cause in my particular case. If you read the data from multiple XML files that lie in same folder you will parse also .DS_Store file. Before parsing add this condition
for file in files:
if file.endswith('.xml'):
run_your_code...
This trick helped me as well
Use <br/>
. For example:
Change log, upgrade version
Dependency | Old version | New version |
---------- | ----------- | -----------
Spring Boot | `1.3.5.RELEASE` | `1.4.3.RELEASE`
Gradle | `2.13` | `3.2.1`
Gradle plugin <br/>`com.gorylenko.gradle-git-properties` | `1.4.16` | `1.4.17`
`org.webjars:requirejs` | `2.2.0` | `2.3.2`
`org.webjars.npm:stompjs` | `2.3.3` | `2.3.3`
`org.webjars.bower:sockjs-client` | `1.1.0` | `1.1.1`
As drewm himself said this is due to the subsequent redirect after the POST to the script has in fact succeeded. (I might have added this as a comment to his answer but you need 50 reputation to comment and I'm new round here - daft rule IMHO)
BUT it also applies if you're trying to redirect to a page, not just a directory - at least it did for me. I was trying to redirect to /thankyou.html. What fixes this is using an absolute URL, i.e. http://example.com/thankyou.html
I have just come across this from Common Crawl.
Might be the answer we are all looking for!!
More "gentle" mode from the documentation:
docker run -dit --restart unless-stopped <image_name>
I have two get methods with same or no parameters
[Route("api/ControllerName/FirstList")]
[HttpGet]
public IHttpActionResult FirstList()
{
}
[Route("api/ControllerName/SecondList")]
[HttpGet]
public IHttpActionResult SecondList()
{
}
Just define custom routes in AppStart=>WebApiConfig.cs
=> under register method
config.Routes.MapHttpRoute(
name: "GetFirstList",
routeTemplate: "api/Controllername/FirstList"
);
config.Routes.MapHttpRoute(
name: "GetSecondList",
routeTemplate: "api/Controllername/SecondList"
);
Download and install packages and dependencies
Usage:
go get [-d] [-f] [-t] [-u] [-v] [-fix] [-insecure] [build flags] [packages]
Get downloads the packages named by the import paths, along with their dependencies. It then installs the named packages, like 'go install'.
The -d flag instructs get to stop after downloading the packages; that is, it instructs get not to install the packages.
The -f flag, valid only when -u is set, forces get -u not to verify that each package has been checked out from the source control repository implied by its import path. This can be useful if the source is a local fork of the original.
The -fix flag instructs get to run the fix tool on the downloaded packages before resolving dependencies or building the code.
The -insecure flag permits fetching from repositories and resolving custom domains using insecure schemes such as HTTP. Use with caution.
The -t flag instructs get to also download the packages required to build the tests for the specified packages.
The -u flag instructs get to use the network to update the named packages and their dependencies. By default, get uses the network to check out missing packages but does not use it to look for updates to existing packages.
The -v flag enables verbose progress and debug output.
Get also accepts build flags to control the installation. See 'go help build'.
When checking out a new package, get creates the target directory GOPATH/src/. If the GOPATH contains multiple entries, get uses the first one. For more details see: 'go help gopath'.
When checking out or updating a package, get looks for a branch or tag that matches the locally installed version of Go. The most important rule is that if the local installation is running version "go1", get searches for a branch or tag named "go1". If no such version exists it retrieves the default branch of the package.
When go get checks out or updates a Git repository, it also updates any git submodules referenced by the repository.
Get never checks out or updates code stored in vendor directories.
For more about specifying packages, see 'go help packages'.
For more about how 'go get' finds source code to download, see 'go help importpath'.
This text describes the behavior of get when using GOPATH to manage source code and dependencies. If instead the go command is running in module-aware mode, the details of get's flags and effects change, as does 'go help get'. See 'go help modules' and 'go help module-get'.
See also: go build, go install, go clean.
For example, showing verbose output,
$ go get -v github.com/capotej/groupcache-db-experiment/...
github.com/capotej/groupcache-db-experiment (download)
github.com/golang/groupcache (download)
github.com/golang/protobuf (download)
github.com/capotej/groupcache-db-experiment/api
github.com/capotej/groupcache-db-experiment/client
github.com/capotej/groupcache-db-experiment/slowdb
github.com/golang/groupcache/consistenthash
github.com/golang/protobuf/proto
github.com/golang/groupcache/lru
github.com/capotej/groupcache-db-experiment/dbserver
github.com/capotej/groupcache-db-experiment/cli
github.com/golang/groupcache/singleflight
github.com/golang/groupcache/groupcachepb
github.com/golang/groupcache
github.com/capotej/groupcache-db-experiment/frontend
$
You use the -classpath
argument. You can use either a relative or absolute path. What that means is you can use a path relative to your current directory, OR you can use an absolute path that starts at the root /
.
Example:
bash$ java -classpath path/to/jar/file MyMainClass
In this example the main
function is located in MyMainClass
and would be included somewhere in the jar file.
For compiling you need to use javac
Example:
bash$ javac -classpath path/to/jar/file MyMainClass.java
You can also specify the classpath via the environment variable, follow this example:
bash$ export CLASSPATH="path/to/jar/file:path/tojar/file2"
bash$ javac MyMainClass.java
For any normally complex java project you should look for the ant script named build.xml
Use the show_source();
function of PHP. Check for more details in show_source. This is a better method I guess.
Try this using regular expression:
import re
data['result'] = data['result'].map(lambda x: re.sub('[-+A-Za-z]',x)
You probably meant document.getElementsByClassName()
(and then grabbing the first item off the resulting node list):
var stopMusicExt = document.getElementsByClassName("stopButton")[0];
stopButton.onclick = function() {
var ta = document.getElementsByClassName("stopButton")[0];
document['player'].stopMusicExt(ta.value);
ta.value = "";
};
You may still get the error
document.getElementsByClassName
is not a function
in older browsers, though, in which case you can provide a fallback implementation if you need to support those older browsers.
Have you tried just "TYPE1"? I suppose Spring uses reflection to determine the type of "type" anyway, so the fully qualified name is redundant. Spring generally doesn't subscribe to redundancy!
If it were an "ordered factor" things would be different. Which is not to say I like "ordered factors", I don't, only to say that some relationships are defined for 'ordered factors' that are not defined for "factors". Factors are thought of as ordinary categorical variables. You are seeing the natural sort order of factors which is alphabetical lexical order for your locale. If you want to get an automatic coercion to "numeric" for every column, ... dates and factors and all, then try:
sapply(df, function(x) max(as.numeric(x)) ) # not generally a useful result
Or if you want to test for factors first and return as you expect then:
sapply( df, function(x) if("factor" %in% class(x) ) {
max(as.numeric(as.character(x)))
} else { max(x) } )
@Darrens comment does work better:
sapply(df, function(x) max(as.character(x)) )
max
does succeed with character vectors.
You want to use the TRUNCATE
command.
https://dev.mysql.com/doc/refman/8.0/en/mathematical-functions.html#function_truncate
Seems to work.
var widthRange = new Array();
widthRange[46] = { sel:46, min:0, max:52 };
widthRange[66] = { sel:66, min:52, max:70 };
widthRange[90] = { sel:90, min:70, max:94 };
for (var key in widthRange)
{
document.write(widthRange[key].sel + "<br />");
document.write(widthRange[key].min + "<br />");
document.write(widthRange[key].max + "<br />");
}
The simpler solution will be to user pyftpd library. This library allows you to spin Python FTP server in one line. It doesn’t come installed by default though, but we can install it using simple apt command
apt-get install python-pyftpdlib
now from the directory you want to serve just run the pythod module
python -m pyftpdlib -p 21
var string ='my string'
var new_string = string.replace('string','new string');
alert(string);
alert(new_string);
self
is the self-reference in a Class. Your code is not in a class, you only have functions defined. You have to wrap your methods in a class, like below. To use the method main()
, you first have to instantiate an object of your class and call the function on the object.
Further, your function setavalue
should be in __init___
, the method called when instantiating an object. The next step you probably should look at is supplying the name as an argument to init, so you can create arbitrarily named objects of the Name
class ;)
class Name:
def __init__(self):
self.myname = "harry"
def printaname(self):
print "Name", self.myname
def main(self):
self.printaname()
if __name__ == "__main__":
objName = Name()
objName.main()
Have a look at the Classes chapter of the Python tutorial an at Dive into Python for further references.
It's about your way of reading it. not
operator is dynamic, that's why you are able to apply it in
if not x == 'val':
But !=
could be read in a better context as an operator which does the opposite of what ==
does.
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder){
return builder.build();
}
mikej's answer was very precise and helpful, but the the thing i also wanted to know was how to get current method name in rails.
found out it's possible with self.current_method
easily found at http://www.ruby-forum.com/topic/75258
typedef enum state {DEAD,ALIVE} State;
| | | | | |^ terminating semicolon, required!
| | | type specifier | | |
| | | | ^^^^^ declarator (simple name)
| | | |
| | ^^^^^^^^^^^^^^^^^^^^^^^
| |
^^^^^^^-- storage class specifier (in this case typedef)
The typedef
keyword is a pseudo-storage-class specifier. Syntactically, it is used in the same place where a storage class specifier like extern
or static
is used. It doesn't have anything to do with storage. It means that the declaration doesn't introduce the existence of named objects, but rather, it introduces names which are type aliases.
After the above declaration, the State
identifier becomes an alias for the type enum state {DEAD,ALIVE}
. The declaration also provides that type itself. However that isn't typedef
doing it. Any declaration in which enum state {DEAD,ALIVE}
appears as a type specifier introduces that type into the scope:
enum state {DEAD, ALIVE} stateVariable;
If enum state
has previously been introduced the typedef
has to be written like this:
typedef enum state State;
otherwise the enum
is being redefined, which is an error.
Like other declarations (except function parameter declarations), the typedef
declaration can have multiple declarators, separated by a comma. Moreover, they can be derived declarators, not only simple names:
typedef unsigned long ulong, *ulongptr;
| | | | | 1 | | 2 |
| | | | | | ^^^^^^^^^--- "pointer to" declarator
| | | | ^^^^^^------------- simple declarator
| | ^^^^^^^^^^^^^-------------------- specifier-qualifier list
^^^^^^^---------------------------------- storage class specifier
This typedef
introduces two type names ulong
and ulongptr
, based on the unsigned long
type given in the specifier-qualifier list. ulong
is just a straight alias for that type. ulongptr
is declared as a pointer to unsigned long
, thanks to the *
syntax, which in this role is a kind of type construction operator which deliberately mimics the unary *
for pointer dereferencing used in expressions. In other words ulongptr
is an alias for the "pointer to unsigned long
" type.
Alias means that ulongptr
is not a distinct type from unsigned long *
. This is valid code, requiring no diagnostic:
unsigned long *p = 0;
ulongptr q = p;
The variables q
and p
have exactly the same type.
The aliasing of typedef
isn't textual. For instance if user_id_t
is a typedef
name for the type int
, we may not simply do this:
unsigned user_id_t uid; // error! programmer hoped for "unsigned int uid".
This is an invalid type specifier list, combining unsigned
with a typedef name. The above can be done using the C preprocessor:
#define user_id_t int
unsigned user_id_t uid;
whereby user_id_t
is macro-expanded to the token int
prior to syntax analysis and translation. While this may seem like an advantage, it is a false one; avoid this in new programs.
Among the disadvantages that it doesn't work well for derived types:
#define silly_macro int *
silly_macro not, what, you, think;
This declaration doesn't declare what
, you
and think
as being of type "pointer to int" because the macro-expansion is:
int * not, what, you, think;
The type specifier is int
, and the declarators are *not
, what
, you
and think
. So not
has the expected pointer type, but the remaining identifiers do not.
And that's probably 99% of everything about typedef
and type aliasing in C.
Oh My Goodness! Look at the size of my temporary table space! Or... how to shrink temporary tablespaces in Oracle.
Yes I ran a query to see how big my temporary tablespace is:
SQL> SELECT tablespace_name, file_name, bytes
2 FROM dba_temp_files WHERE tablespace_name like 'TEMP%';
TABLESPACE_NAME FILE_NAME BYTES
----------------- -------------------------------- --------------
TEMP /the/full/path/to/temp01.dbf 13,917,200,000
The first question you have to ask is why the temporary tablespace is so large. You may know the answer to this off the top of your head. It may be due to a large query that you just run with a sort that was a mistake (I have done that more than once.) It may be due to some other exceptional circumstance. If that is the case then all you need to do to clean up is to shrink the temporary tablespace and move on in life.
But what if you don't know? Before you decide to shrink you may need to do some investigation into the causes of the large tablespace. If this happens on a regular basis then it is possible that your database just needs that much space.
The dynamic performance view
V$TEMPSEG_USAGE
can be very useful in determining the cause.
Maybe you just don't care about the cause and you just need to shrink it. This is your third day on the job. The data in the database is only 200MiB if data and the temporary tablespace is 13GiB - Just shrink it and move on. If it grows again then we will look into the cause. In the mean time I am out of space on that disk volume and I just need the space back.
Let's take a look at shrinking it. It will depend a little on what version
of Oracle you are running and how the temporary tablespace was set up.
Oracle will do it's best to keep you from making any horrendous mistakes
so we will just try the commands and if they don't work we will shrink
in a new way.
First let's try to shrink the datafile. If we can do that then we get back the space and we can worry about why it grew tomorrow.
SQL>
SQL> alter database tempfile '/the/full/path/to/temp01.dbf' resize 256M;
alter database tempfile '/the/full/path/to/temp01.dbf' resize 256M
*
ERROR at line 1:
ORA-03297: file contains used data beyond requested RESIZE value
Depending on the error message you may want to try this with different sizes that are smaller than the current site of the file. I have had limited success with this. Oracle will only shrink the file if the temporary tablespace is at the head of the file and if it is smaller than the size you specify. Some old Oracle documentation (they corrected this) said that you could issue the command and the error message would tell you what size you could shrink to. By the time I started working as a DBA this was not true. You just had to guess and re-run the command a bunch of times and see if it worked.
Alright. That didn't work. How about this.
SQL> alter tablespace YOUR_TEMP_TABLESPACE_NAME shrink space keep 256M;
If you are in 11g (Maybee in 10g too) this is it! If it works you may want to go back to the previous command and give it some more tries.
But what if that fails. If the temporary tablespace is the default temporary that was set up when the database was installed then you may need to do a lot more work. At this point I usually re-evaluate if I really need that space back. After all disk space only costs $X.XX a GiB. Usually I don't want to make changes like this during production hours. That means working at 2AM AGAIN! (Not that I really object to working at 2AM - it is just that... Well I like to sleep too. And my wife likes to have me at home at 2AM... not roaming the downtown streets at 4AM trying to remember where I parked my car 3 hours earlier. I have heard of that "telecommuting" thing. I just worry that I will get half way through and then my internet connectivity will fail - then I have to rush downtown to fix it all before folks show up in the morning to use the database.)
Ok... Back to the serious stuff... If the temporary tablespace you want to shrink is your default temporary tablespace, you will have to first create a new temporary tablespace, set it as the default temporary tablespace then drop your old default temporary tablespace and recreate it. Afterwords drop the second temporary table created.
SQL> CREATE TEMPORARY TABLESPACE temp2
2 TEMPFILE '/the/full/path/to/temp2_01.dbf' SIZE 5M REUSE
3 AUTOEXTEND ON NEXT 1M MAXSIZE unlimited
4 EXTENT MANAGEMENT LOCAL UNIFORM SIZE 1M;
Tablespace created.
SQL> ALTER DATABASE DEFAULT TEMPORARY TABLESPACE temp2;
Database altered.
SQL> DROP TABLESPACE temp INCLUDING CONTENTS AND DATAFILES;
Tablespace dropped.
SQL> CREATE TEMPORARY TABLESPACE temp
2 TEMPFILE '/the/full/path/to/temp01.dbf' SIZE 256M REUSE
3 AUTOEXTEND ON NEXT 128M MAXSIZE unlimited
4 EXTENT MANAGEMENT LOCAL UNIFORM SIZE 1M;
Tablespace created.
SQL> ALTER DATABASE DEFAULT TEMPORARY TABLESPACE temp;
Database altered.
SQL> DROP TABLESPACE temp2 INCLUDING CONTENTS AND DATAFILES;
Tablespace dropped.
Hopefully one of these things will help!
The following code works fine:
@using (Html.BeginForm("Upload", "Upload", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<fieldset>
Select a file <input type="file" name="file" />
<input type="submit" value="Upload" />
</fieldset>
}
and generates as expected:
<form action="/Upload/Upload" enctype="multipart/form-data" method="post">
<fieldset>
Select a file <input type="file" name="file" />
<input type="submit" value="Upload" />
</fieldset>
</form>
On the other hand if you are writing this code inside the context of other server side construct such as an if
or foreach
you should remove the @
before the using
. For example:
@if (SomeCondition)
{
using (Html.BeginForm("Upload", "Upload", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<fieldset>
Select a file <input type="file" name="file" />
<input type="submit" value="Upload" />
</fieldset>
}
}
As far as your server side code is concerned, here's how to proceed:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/content/pics"), fileName);
file.SaveAs(path);
}
return RedirectToAction("Upload");
}
Edit AppServiceProvider.php will be found at app/Providers/AppServiceProvider.php and add
use Illuminate\Support\Facades\Schema;
public function boot()
{
Schema::defaultStringLength(191);
}
Then run
composer update
On your terminal. It helped me, may be it will work for you as well.
The JavaDoc explains it very well:
With this option set to a non-zero timeout, a read() call on the InputStream associated with this Socket will block for only this amount of time. If the timeout expires, a java.net.SocketTimeoutException is raised, though the Socket is still valid. The option must be enabled prior to entering the blocking operation to have effect. The timeout must be > 0. A timeout of zero is interpreted as an infinite timeout.
SO_TIMEOUT
is the timeout that a read()
call will block. If the timeout is reached, a java.net.SocketTimeoutException will be thrown. If you want to block forever put this option to zero (the default value), then the read()
call will block until at least 1 byte could be read.
You should always include all relevant code when asking a question. In this case, the print statement that is the center of your question. The print statement is probably the most crucial piece of information. The second most crucial piece of information is the error, which you also did not include. Next time, include both of those.
print $ids
should be a fairly hard statement to mess up, but it is possible. Possible reasons:
$ids
is undefined. Gives the warning undefined value in print
$ids
is out of scope. With use
strict
, gives fatal warning Global
variable $ids needs explicit package
name
, and otherwise the undefined
warning from above.print $ids $nIds
,
in which case perl thinks that $ids
is supposed to be a filehandle, and
you get an error such as print to
unopened filehandle
.Explanations
1: Should not happen. It might happen if you do something like this (assuming you are not using strict
):
my $var;
while (<>) {
$Var .= $_;
}
print $var;
Gives the warning for undefined value, because $Var
and $var
are two different variables.
2: Might happen, if you do something like this:
if ($something) {
my $var = "something happened!";
}
print $var;
my
declares the variable inside the current block. Outside the block, it is out of scope.
3: Simple enough, common mistake, easily fixed. Easier to spot with use warnings
.
4: Also a common mistake. There are a number of ways to correctly print two variables in the same print
statement:
print "$var1 $var2"; # concatenation inside a double quoted string
print $var1 . $var2; # concatenation
print $var1, $var2; # supplying print with a list of args
Lastly, some perl magic tips for you:
use strict;
use warnings;
# open with explicit direction '<', check the return value
# to make sure open succeeded. Using a lexical filehandle.
open my $fh, '<', 'file.txt' or die $!;
# read the whole file into an array and
# chomp all the lines at once
chomp(my @file = <$fh>);
close $fh;
my $ids = join(' ', @file);
my $nIds = scalar @file;
print "Number of lines: $nIds\n";
print "Text:\n$ids\n";
Reading the whole file into an array is suitable for small files only, otherwise it uses a lot of memory. Usually, line-by-line is preferred.
Variations:
print "@file"
is equivalent to
$ids = join(' ',@file); print $ids;
$#file
will return the last index
in @file
. Since arrays usually start at 0,
$#file + 1
is equivalent to scalar @file
. You can also do:
my $ids;
do {
local $/;
$ids = <$fh>;
}
By temporarily "turning off" $/
, the input record separator, i.e. newline, you will make <$fh>
return the entire file. What <$fh>
really does is read until it finds $/
, then return that string. Note that this will preserve the newlines in $ids
.
Line-by-line solution:
open my $fh, '<', 'file.txt' or die $!; # btw, $! contains the most recent error
my $ids;
while (<$fh>) {
chomp;
$ids .= "$_ "; # concatenate with string
}
my $nIds = $.; # $. is Current line number for the last filehandle accessed.
I had same problem with 'parallax' plugin.
I changed jQuery librery version to *jquery-1.6.4*
from *jquery-1.10.2*.
And error cleared.
When you set keys (primary or foreign) you are setting constraints on how they can be used, which in turn limits what you can do with them. If you really want to alter the column, you could re-create the table without the constraints, although I'd recommend against it. Generally speaking, if you have a situation in which you want to do something, but it is blocked by a constraint, it's best resolved by changing what you want to do rather than the constraint.
Try to use mousemove event lisentner
var audio = document.createElement("AUDIO")
document.body.appendChild(audio);
audio.src = "./audio/rain.m4a"
document.body.addEventListener("mousemove", function () {
audio.play()
})
"Upstream" would refer to the main repo that other people will be pulling from, e.g. your GitHub repo. The -u option automatically sets that upstream for you, linking your repo to a central one. That way, in the future, Git "knows" where you want to push to and where you want to pull from, so you can use git pull
or git push
without arguments. A little bit down, this article explains and demonstrates this concept.
In RedHat 7.0: /etc/httpd/conf/httpd.conf
jezrael's answer is good, but did not answer a question I had: Will getting the "sort" flag wrong mess up my data in any way? The answer is apparently "no", you are fine either way.
from pandas import DataFrame, concat
a = DataFrame([{'a':1, 'c':2,'d':3 }])
b = DataFrame([{'a':4,'b':5, 'd':6,'e':7}])
>>> concat([a,b],sort=False)
a c d b e
0 1 2.0 3 NaN NaN
0 4 NaN 6 5.0 7.0
>>> concat([a,b],sort=True)
a b c d e
0 1 NaN 2.0 3 NaN
0 4 5.0 NaN 6 7.0
Phil Haak has an example that I think is a bit more stable when dealing with paths with crazy "\" style directory separators. It also safely handles path concatenation. It comes for free in System.IO
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
However, you could also try "AppDomain.CurrentDomain.BaseDirector" instead of "Server.MapPath".
I was struggling with the same error message in SQL SERVER, since I had multiple joins, changing the order of the joins solved it for me.
To Send bold,italic,fixed width code you can use this :
# Sending a HTML formatted message
bot.send_message(chat_id=@yourchannelname,
text="*boldtext* _italictext_ `fixed width font` [link] (http://google.com).",
parse_mode=telegram.ParseMode.MARKDOWN)
make sure you have enabled the bot as your admin .Then only it can send message
I find that some of these answers are vague and complicated, I find the best way to figure out these things for sure is to just open up the console and test it yourself.
var x;
x == null // true
x == undefined // true
x === null // false
x === undefined // true
var y = null;
y == null // true
y == undefined // true
y === null // true
y === undefined // false
typeof x // 'undefined'
typeof y // 'object'
var z = {abc: null};
z.abc == null // true
z.abc == undefined // true
z.abc === null // true
z.abc === undefined // false
z.xyz == null // true
z.xyz == undefined // true
z.xyz === null // false
z.xyz === undefined // true
null = 1; // throws error: invalid left hand assignment
undefined = 1; // works fine: this can cause some problems
So this is definitely one of the more subtle nuances of JavaScript. As you can see, you can override the value of undefined
, making it somewhat unreliable compared to null
. Using the ==
operator, you can reliably use null
and undefined
interchangeably as far as I can tell. However, because of the advantage that null
cannot be redefined, I might would use it when using ==
.
For example, variable != null
will ALWAYS return false if variable
is equal to either null
or undefined
, whereas variable != undefined
will return false if variable
is equal to either null
or undefined
UNLESS undefined
is reassigned beforehand.
You can reliably use the ===
operator to differentiate between undefined
and null
, if you need to make sure that a value is actually undefined
(rather than null
).
Null
and Undefined
are two of the six built in types.4.3.9 undefined value
primitive value used when a variable has not been assigned a value
4.3.11 null value
primitive value that represents the intentional absence of any object value
The command line tools are not included with the latest version of Grunt (0.4 at time of writing) instead you need to install them separately.
This is a good idea because it means you can have different versions of Grunt running on different projects but still use the nice concise grunt
command to run them.
So first install the grunt cli tools globally:
npm install -g grunt-cli
(or possibly sudo npm install -g grunt-cli
).
You can establish that's working by typing grunt --version
Now you can install the current version of Grunt local to your project. So from your project's location...
npm install grunt --save-dev
The save-dev
switch isn't strictly necessary but is a good idea because it will mark grunt in its package.json devDependencies section as a development only module.
On Mac OS X el captain with brew, try:
brew install pkgconfig
This worked for me.
Expanding @lucasg's answer (inspired by the comment it received):
To get a formatted list output, you can do something along these lines:
l = [1,2,5]
print ", ".join('%02d'%x for x in l)
01, 02, 05
Now the ", "
provides the separator (only between items, not at the end) and the formatting string '02d'
combined with %x
gives a formatted string for each item x
- in this case, formatted as an integer with two digits, left-filled with zeros.
in kotlin do it as below by using html
HtmlCompat.fromHtml("<html><body><h1>This is Large Heading :-</h1><br>This is normal size<body></html>",HtmlCompat.FROM_HTML_MODE_LEGACY)
Additionally for what was said, if you want integer powers of two, then 1 << x
(or 1L << x
) is a faster way to calculate 2x than Math.pow(2,x)
or a multiplication loop, and is guaranteed to give you an int
(or long
) result.
It only uses the lowest 5 (or 6) bits of x
(i.e. x & 31
(or x & 63
)), though, shifting between 0 and 31 (or 63) bits.
It usually because in connection manager it may be still of 50 char , hence I have resolved the problem by going to Connection Manager--> Advanced and then change to 100 or may be 1000 if its big enough
https://paiza.io/projects/X1QjjBkA8mDo6oVh-J_63w
Check below code for converting json to array in PHP
,
If JSON is correct then json_decode()
works well, and will return an array,
But if malformed JSON, then It will return NULL
,
<?php
function jsonDecode1($json){
$arr = json_decode($json, true);
return $arr;
}
// In case of malformed JSON, it will return NULL
var_dump( jsonDecode1($json) );
If malformed JSON, and you are expecting only array, then you can use this function,
<?php
function jsonDecode2($json){
$arr = (array) json_decode($json, true);
return $arr;
}
// In case of malformed JSON, it will return an empty array()
var_dump( jsonDecode2($json) );
If malformed JSON, and you want to stop code execution, then you can use this function,
<?php
function jsonDecode3($json){
$arr = (array) json_decode($json, true);
if(empty(json_last_error())){
return $arr;
}
else{
throw new ErrorException( json_last_error_msg() );
}
}
// In case of malformed JSON, Fatal error will be generated
var_dump( jsonDecode3($json) );
You can use any function depends on your requirement,
If you want to know whether an object is an Integer
or something which can meaningfully be converted to an Integer (NOT including things like "hello"
, which to_i
will convert to 0
):
result = Integer(obj) rescue false
I solve the same problem with this SO answer.
Basically it binds the radio button to a boolean property of a Strongly Typed Model.
@Html.RadioButton("blah", !Model.blah) Yes
@Html.RadioButton("blah", Model.blah) No
Hope it helps!
To base64 it and put it in your clipboard:
file="test.docx"
base64 -w 0 $file | xclip -selection clipboard
If you want to benchmark, you can use os.clock as shown by the doc:
local x = os.clock()
local s = 0
for i=1,100000 do s = s + i end
print(string.format("elapsed time: %.2f\n", os.clock() - x))
class MyParent:
def sayHi():
print('Mamma says hi')
from path.to.MyParent import MyParent
class ChildClass(MyParent):
pass
An instance of ChildClass
will then inherit the sayHi()
method.
Yes, assignment will just copy the value of l1
(which is a reference) to l2
. They will both refer to the same object.
Creating a shallow copy is pretty easy though:
List<Integer> newList = new ArrayList<>(oldList);
(Just as one example.)
This is one way without using time a zone:
LocalDateTime now = LocalDateTime.now();
long epoch = (now.getLong(ChronoField.EPOCH_DAY) * 86400000) + now.getLong(ChronoField.MILLI_OF_DAY);
i came across this problem when i was trying to do pos tagging in nltk.
the way i got it correct is by making a new directory along with corpora directory named "taggers" and copying max_pos_tagger in directory taggers.
hope it works for you too. best of luck with it!!!.
You may want to check out the mySQL docs in regard to the date functions. http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
There is a YEAR() function just as there is a MONTH() function. If you're doing a comparison though is there a reason to chop up the date? Are you truly interested in ignoring day based differences and if so is this how you want to do it?
If you want a boolean value:
>>> a = [1, 2, 3, 4, 5]
>>> b = [9, 8, 7, 6, 5]
>>> set(b) == set(a) & set(b) and set(a) == set(a) & set(b)
False
>>> a = [3,1,2]
>>> b = [1,2,3]
>>> set(b) == set(a) & set(b) and set(a) == set(a) & set(b)
True
There are several problems here, so I'll start with my usual high-level advice: Start small and simple, add complexity a little at a time, test at every step, and never add to code that doesn't work. (I really ought to have that hotkeyed.)
You're mixing Make syntax and shell syntax in a way that is just dizzying. You should never have let it get this big without testing. Let's start from the outside and work inward.
UNAME := $(shell uname -m)
all:
$(info Checking if custom header is needed)
ifeq ($(UNAME), x86_64)
... do some things to build unistd_32.h
endif
@make -C $(KDIR) M=$(PWD) modules
So you want unistd_32.h built (maybe) before you invoke the second make
, you can make it a prerequisite. And since you want that only in a certain case, you can put it in a conditional:
ifeq ($(UNAME), x86_64)
all: unistd_32.h
endif
all:
@make -C $(KDIR) M=$(PWD) modules
unistd_32.h:
... do some things to build unistd_32.h
Now for building unistd_32.h
:
F1_EXISTS=$(shell [ -e /usr/include/asm/unistd_32.h ] && echo 1 || echo 0 )
ifeq ($(F1_EXISTS), 1)
$(info Copying custom header)
$(shell sed -e 's/__NR_/__NR32_/g' /usr/include/asm/unistd_32.h > unistd_32.h)
else
F2_EXISTS=$(shell [[ -e /usr/include/asm-i386/unistd.h ]] && echo 1 || echo 0 )
ifeq ($(F2_EXISTS), 1)
$(info Copying custom header)
$(shell sed -e 's/__NR_/__NR32_/g' /usr/include/asm-i386/unistd.h > unistd_32.h)
else
$(error asm/unistd_32.h and asm-386/unistd.h does not exist)
endif
endif
You are trying to build unistd.h
from unistd_32.h
; the only trick is that unistd_32.h
could be in either of two places. The simplest way to clean this up is to use a vpath
directive:
vpath unistd.h /usr/include/asm /usr/include/asm-i386
unistd_32.h: unistd.h
sed -e 's/__NR_/__NR32_/g' $< > $@
Use .loc
for label based indexing:
df.loc[df.A==0, 'B'] = np.nan
The df.A==0
expression creates a boolean series that indexes the rows, 'B'
selects the column. You can also use this to transform a subset of a column, e.g.:
df.loc[df.A==0, 'B'] = df.loc[df.A==0, 'B'] / 2
I don't know enough about pandas internals to know exactly why that works, but the basic issue is that sometimes indexing into a DataFrame returns a copy of the result, and sometimes it returns a view on the original object. According to documentation here, this behavior depends on the underlying numpy behavior. I've found that accessing everything in one operation (rather than [one][two]) is more likely to work for setting.
Just in case there is someone out there who's a bit new like me, double check that you are spelling your header folders correctly.
For example:
<#include "Component/BoxComponent.h"
This will result in the error. Instead, it needs to be:
<#include "Components/BoxComponent.h"
You can use escape sequences, if your terminal supports it. For example:
echo \[\033[32m\]Hello, \[\033[36m\]colourful \[\033[33mworld!\033[0m\]
The best way I have tried before is to use urlencode()
. Keep in mind, don't use it for the whole url; instead, use it only for the needed parts. For example, a request that has two 'text-fa' and 'text-en' fields and they contain a Persian and an English text, respectively, you might only need to encode the Persian text, not the English one.
However, there are better ways if the range of characters have to be encoded is more limited. One of these ways is using CURLOPT_ENCODING
, by passing it to curl_setopt()
:
curl_setopt($ch, CURLOPT_ENCODING, "");
Use this query to create the new table with the values from existing table
CREATE TABLE New_Table_name AS SELECT * FROM Existing_table_Name;
Now you can get all the values from existing table into newly created table.
What type of sql database are using (MSSQL, Oracle etc)? I believe what you have written is correct.
You could also write the first query like this:
SELECT s.sid, s.name
FROM Supplier s
WHERE (SELECT COUNT(DISTINCT pr.jid)
FROM Supplies su, Projects pr
WHERE su.sid = s.sid
AND pr.jid = su.jid) >= 2
It's a little more readable, and less mind-bending than trying to do it with GROUP BY. Performance may differ though.
You are encountering a problem because you cannot construct the ArrayList
and populate it at the same time. You either need to create it and then manually populate it as such:
ArrayList list = new ArrayList<Double>();
list.add(1.38);
...
Or, alternatively if it is more convenient for you, you can populate the ArrayList
from a primitive array containing your values. For example:
Double[] array = {1.38, 2.56, 4.3};
ArrayList<Double> list = new ArrayList<Double>(Arrays.asList(array));
IIS v10 (but this should be the same also for IIS 7.x)
Quick addition for people which are looking for respective max values
Max for maxAllowedContentLength
is: UInt32.MaxValue
4294967295 bytes
: ~4GB
Max for maxRequestLength
is: Int32.MaxValue
2147483647 bytes
: ~2GB
web.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<!-- ~ 2GB -->
<httpRuntime maxRequestLength="2147483647" />
</system.web>
<system.webServer>
<security>
<requestFiltering>
<!-- ~ 4GB -->
<requestLimits maxAllowedContentLength="4294967295" />
</requestFiltering>
</security>
</system.webServer>
</configuration>
Postgresql12
from sql file: pg_restore -d database < file.sql
from custom format file: pg_restore -Fc database < file.dump
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)
@Joel's answer is pretty close, but it will fail in the following cases:
// Whitespace strings:
IsNumeric(' ') == true;
IsNumeric('\t\t') == true;
IsNumeric('\n\r') == true;
// Number literals:
IsNumeric(-1) == false;
IsNumeric(0) == false;
IsNumeric(1.1) == false;
IsNumeric(8e5) == false;
Some time ago I had to implement an IsNumeric
function, to find out if a variable contained a numeric value, regardless of its type, it could be a String
containing a numeric value (I had to consider also exponential notation, etc.), a Number
object, virtually anything could be passed to that function, I couldn't make any type assumptions, taking care of type coercion (eg. +true == 1;
but true
shouldn't be considered as "numeric"
).
I think is worth sharing this set of +30 unit tests made to numerous function implementations, and also share the one that passes all my tests:
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
P.S. isNaN & isFinite have a confusing behavior due to forced conversion to number. In ES6, Number.isNaN & Number.isFinite would fix these issues. Keep that in mind when using them.
Update : Here's how jQuery does it now (2.2-stable):
isNumeric: function(obj) {
var realStringObj = obj && obj.toString();
return !jQuery.isArray(obj) && (realStringObj - parseFloat(realStringObj) + 1) >= 0;
}
Update : Angular 4.3:
export function isNumeric(value: any): boolean {
return !isNaN(value - parseFloat(value));
}
Your code is actually attempting to make a Cross-domain (CORS) request, not an ordinary POST
.
That is: Modern browsers will only allow Ajax calls to services in the same domain as the HTML page.
Example: A page in http://www.example.com/myPage.html
can only directly request services that are in http://www.example.com
, like http://www.example.com/testservice/etc
. If the service is in other domain, the browser won't make the direct call (as you'd expect). Instead, it will try to make a CORS request.
To put it shortly, to perform a CORS request, your browser:
OPTION
request to the target URLOPTION
contains the adequate headers (Access-Control-Allow-Origin
is one of them) to allow the CORS request, the browse will perform the call (almost exactly the way it would if the HTML page was at the same domain).
How to solve it? The simplest way is to enable CORS (enable the necessary headers) on the server.
If you don't have server-side access to it, you can mirror the web service from somewhere else, and then enable CORS there.
Am I missing something in the question or why else nobody mentioned reviver
parameter of JSON.parse
since 2011?
Here is simplistic code for solution that works: https://jsfiddle.net/Ldr2utrr/
function Foo()
{
this.a = 3;
this.b = 2;
this.test = function() {return this.a*this.b;};
}
var fooObj = new Foo();
alert(fooObj.test() ); //Prints 6
var fooJSON = JSON.parse(`{"a":4, "b": 3}`, function(key,value){
if(key!=="") return value; //logic of course should be more complex for handling nested objects etc.
let res = new Foo();
res.a = value.a;
res.b = value.b;
return res;
});
// Here you already get Foo object back
alert(fooJSON.test() ); //Prints 12
PS: Your question is confusing: >>That's great, but how can I take that JavaScript Object and turn it into a particular JavaScript Object (i.e. with a certain prototype)? contradicts to the title, where you ask about JSON parsing, but the quoted paragraph asks about JS runtime object prototype replacement.
you can run plain cat
without any arguments as mentioned by bro @Sa'ad to simply keep the container working [actually doing nothing but waiting for user input] (Jenkins' Docker plugin does the same thing)
If you call this function then you easily get the client's IP address. I have already used this in my existing project:
public function getUserIpAddr(){
$ipaddress = '';
if (isset($_SERVER['HTTP_CLIENT_IP']))
$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_X_FORWARDED']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_FORWARDED']))
$ipaddress = $_SERVER['HTTP_FORWARDED'];
else if(isset($_SERVER['REMOTE_ADDR']))
$ipaddress = $_SERVER['REMOTE_ADDR'];
else
$ipaddress = 'UNKNOWN';
return $ipaddress;
}
go 1.13
(exec from module root directory)
Update specified dependencies:
go get -u <package-name>
Update all direct and indirect dependencies to latest minor or patch upgrades (pre-releases are ignored):
go get -u ./...
# or
go get -u=patch ./...
Reference:
https://github.com/golang/go/wiki/Modules#daily-workflow
go help get
Have you followed these instructions:
http://www.squirrelsql.org/#installation
If so, are you running the batch file or the shell script to run it?
The next version of dplyr will support an improved version of select that also incorporates renaming:
> mtcars2 <- select( mtcars, disp2 = disp )
> head( mtcars2 )
disp2
Mazda RX4 160
Mazda RX4 Wag 160
Datsun 710 108
Hornet 4 Drive 258
Hornet Sportabout 360
Valiant 225
> changes( mtcars, mtcars2 )
Changed variables:
old new
disp 0x105500400
disp2 0x105500400
Changed attributes:
old new
names 0x106d2cf50 0x106d28a98
I answered too late but it has worked in my case.If you are facing this issue in your project please add the following line in your web.config :
<compilation batch="false" >
This worked in my case. If you already have compilation tag in your web.config then add only batch="false" property to it.
you can use position:relative;
inside #one div and position:absolute
inside #two div.
you can see it
I have spent few hours to solve this problem and other exceptions with deleting the directory. This is my solution
public static void DeleteDirectory(string target_dir)
{
DeleteDirectoryFiles(target_dir);
while (Directory.Exists(target_dir))
{
lock (_lock)
{
DeleteDirectoryDirs(target_dir);
}
}
}
private static void DeleteDirectoryDirs(string target_dir)
{
System.Threading.Thread.Sleep(100);
if (Directory.Exists(target_dir))
{
string[] dirs = Directory.GetDirectories(target_dir);
if (dirs.Length == 0)
Directory.Delete(target_dir, false);
else
foreach (string dir in dirs)
DeleteDirectoryDirs(dir);
}
}
private static void DeleteDirectoryFiles(string target_dir)
{
string[] files = Directory.GetFiles(target_dir);
string[] dirs = Directory.GetDirectories(target_dir);
foreach (string file in files)
{
File.SetAttributes(file, FileAttributes.Normal);
File.Delete(file);
}
foreach (string dir in dirs)
{
DeleteDirectoryFiles(dir);
}
}
This code has the small delay, which is not important for my application. But be careful, the delay may be a problem for you if you have a lot of subdirectories inside the directory you want to delete.
This should work. You can get body using response.json() if its a json response.
this.http.request('http://thecatapi.com/api/images/get?format=html&results_per_page=10').
subscribe((res: Response.json()) => {
console.log(res);
})
var element = $("#parentDiv .myClassNameOfInterest")
You're doing things in the wrong order.
You need to first add all JComponents to the JFrame, and only then call pack()
and then setVisible(true)
on the JFrame
If you later added JComponents that could change the GUI's size you will need to call pack()
again, and then repaint()
on the JFrame after doing so.
Here is some code telling about priority of all log4net levels:
TraceLevel(Level.All); //-2147483648
TraceLevel(Level.Verbose); // 10 000
TraceLevel(Level.Finest); // 10 000
TraceLevel(Level.Trace); // 20 000
TraceLevel(Level.Finer); // 20 000
TraceLevel(Level.Debug); // 30 000
TraceLevel(Level.Fine); // 30 000
TraceLevel(Level.Info); // 40 000
TraceLevel(Level.Notice); // 50 000
TraceLevel(Level.Warn); // 60 000
TraceLevel(Level.Error); // 70 000
TraceLevel(Level.Severe); // 80 000
TraceLevel(Level.Critical); // 90 000
TraceLevel(Level.Alert); // 100 000
TraceLevel(Level.Fatal); // 110 000
TraceLevel(Level.Emergency); // 120 000
TraceLevel(Level.Off); //2147483647
private static void TraceLevel(log4net.Core.Level level)
{
Debug.WriteLine("{0} = {1}", level, level.Value);
}
According to the manual page for rand(3), the rand family of functions have been obsoleted by random(3). This is due to the fact that the lower 12 bits of rand() go through a cyclic pattern. To get a random number, just seed the generator by calling srandom() with an unsigned seed, and then call random(). So, the equivalent of the code above would be
#import <stdlib.h>
#import <time.h>
srandom(time(NULL));
random() % 74;
You'll only need to call srandom() once in your program unless you want to change your seed. Although you said you didn't want a discussion of truly random values, rand() is a pretty bad random number generator, and random() still suffers from modulo bias, as it will generate a number between 0 and RAND_MAX. So, e.g. if RAND_MAX is 3, and you want a random number between 0 and 2, you're twice as likely to get a 0 than a 1 or a 2.
You can either post HTML form to URL, which is mapped to servlet or insert your data in HttpServletRequest object you pass to jsp page.
You might try using a library like redux-saga. It allows for a very clean way to sequence async functions, fire off actions, use delays and more. It is very powerful!
If you want to see whole history of a file with code changes :
svn log --diff [path_to_file] > log.txt
Ensure that virtualenv
is executable.
If virtualenv
is not found, running the full path (/usr/local/bin/virtualenv
) should work.
X <- data.frame(Variable1=c(11,14,12,15),Variable2=c(2,3,1,4))
> X
Variable1 Variable2
1 11 2
2 14 3
3 12 1
4 15 4
> X[X$Variable1!=11 & X$Variable1!=12, ]
Variable1 Variable2
2 14 3
4 15 4
> X[ ! X$Variable1 %in% c(11,12), ]
Variable1 Variable2
2 14 3
4 15 4
You can functionalize this however you like.
You can try wx library. It's a cross platform UI library. Here you can find the printing tutorial: https://web.archive.org/web/20160619163747/http://wiki.wxpython.org/Printing
Maybe I read the problem wrong, but I believe you already have inserted the course 11 records and simply need to update those that meet the criteria you listed with course 6's data.
If this is the case, you'll want to use an UPDATE
...FROM
statement:
UPDATE MyTable
SET
complete = 1,
complete_date = newdata.complete_date,
post_score = newdata.post_score
FROM
(
SELECT
userID,
complete_date,
post_score
FROM MyTable
WHERE
courseID = 6
AND complete = 1
AND complete_date > '8/1/2008'
) newdata
WHERE
CourseID = 11
AND userID = newdata.userID
map.forEach((key, value) -> System.out.println(key + " " + value));
Using java 8 features
when you press the button so it should call function that will alert message. so after alert put style visible
property .
you can achieve it using
function OpenAlert(){_x000D_
alert("Getting the message");_x000D_
document.getElementById("getMessage").style.visibility="hidden";_x000D_
_x000D_
}
_x000D_
<input type="button" id="getMessage" name="GetMessage" value="GetMessage" onclick="OpenAlert()"/>
_x000D_
Hope this will help . Happy to help
Android appends a sequence number to the package name to produce the final APK file name (it's possible that this varies with the version of Android OS). The following sequence of commands works on a non-rooted device:
Get the full path name of the APK file for the desired package.
adb shell pm path com.example.someapp
This gives the output as: package:/data/app/com.example.someapp-2.apk
.
Pull the APK file from the Android device to the development box.
adb pull /data/app/com.example.someapp-2.apk
The location of APK after successful pulling will be at ../sdk/platform-tools/base.apk on your pc/laptop.
What you could do is copy the code from tkinter.py
into a file called mytkinter.py
, then do this code:
import tkinter, mytkinter
root = tkinter.Tk()
window = mytkinter.Tk()
button = mytkinter.Button(window, text="Search", width = 7,
command=cmd)
button2 = tkinter.Button(root, text="Search", width = 7,
command=cmdtwo)
And you have two windows which don't collide!
Just turn the LIKE around
SELECT * FROM customers
WHERE 'Robert Bob Smith III, PhD.' LIKE CONCAT('%',name,'%')
Executing the following two commands solves the problem for me:
npm install -g @angular/cli
ng update --all --force
figure;
plot(something);
or
figure(2);
plot(something);
...
figure(3);
plot(something else);
...
etc.
It worked for me.
$f=fopen('php://memory','w');
$header=array("asdf ","asdf","asd","Calasdflee","Start Time","End Time" );
fputcsv($f,$header);
fputcsv($f,$header);
fputcsv($f,$header);
fseek($f,0);
header('content-type:text/csv');
header('Content-Disposition: attachment; filename="' . $filename . '";');
fpassthru($f);```
After lots of tweaking, here's a configuration that works generating files on Linux, reading on Windows+Excel, though the embedded newline format is not according to the standard:
In Perl, I used Text::CSV to do this as follows:
use Text::CSV;
open my $FO, ">:encoding(utf8)", $filename or die "Cannot create $filename: $!";
my $csv = Text::CSV->new({ binary => 1, eol => "\r\n" });
#for each row...:
$csv -> print ($FO, \@row);
// Get an global variable isApiCallingInProgress
// check isApiCallingInProgress
if (!isApiCallingInProgress) {
// set it to isApiCallingInProgress true
isApiCallingInProgress = true;
// set timeout
setTimeout(() => {
// Api call will go here
// then set variable again as false
isApiCallingInProgress = false;
}, 1000);
}
You can use the dynamic variable ViewBag
ViewBag.AnotherValue = valueToView;
I've been using something like this. Just set up a simple HTML page with an textinput. Make sure that the textinput always has focus. When you scan a barcode with your barcode scanner you will receive the code and after that a 'enter'. Realy simple then; just capture the incoming keystrokes and when the 'enter' comes in you can use AJAX to handle your code.
This would select 4 in your case
SELECT ID FROM TableA WHERE ID NOT IN (SELECT ID FROM TableB)
This would delete them
DELETE FROM TableA WHERE ID NOT IN (SELECT ID FROM TableB)
You would have to convert the int into a string.
# This program calculates a workers gross pay
hours = float(raw_input("Enter hours worked: \n"))
rate = float(raw_input("Enter your hourly rate of pay: \n"))
gross = hours * rate
print "Your gross pay for working " +str(hours)+ " at a rate of " + str(rate) + " hourly is $" + str(gross)
The targetNamespace
of your XML Schema does not match the namespace of the Root element (dot in Test.Namespace
vs. comma in Test,Namespace
)
Once you make the above agree, you have to consider that your element2
has an attribute order that is not in your XSD.
Check this.
https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html
(Use java.util.Objects.equals
because HashMap can contain null
)
Using JDK8+
/**
* Find any key matching a value.
*
* @param value The value to be matched. Can be null.
* @return Any key matching the value in the team.
*/
private Optional<String> findKey(Integer value){
return team1
.entrySet()
.stream()
.filter(e -> Objects.equals(e.getValue(), value))
.map(Map.Entry::getKey)
.findAny();
}
/**
* Find all keys matching a value.
*
* @param value The value to be matched. Can be null.
* @return all keys matching the value in the team.
*/
private List<String> findKeys(Integer value){
return team1
.entrySet()
.stream()
.filter(e -> Objects.equals(e.getValue(), value))
.map(Map.Entry::getKey)
.collect(Collectors.toList());
}
More "generic" and as safe as possible
/**
* Find any key matching the value, in the given map.
*
* @param mapOrNull Any map, null is considered a valid value.
* @param value The value to be searched.
* @param <K> Type of the key.
* @param <T> Type of the value.
* @return An optional containing a key, if found.
*/
public static <K, T> Optional<K> findKey(Map<K, T> mapOrNull, T value) {
return Optional.ofNullable(mapOrNull).flatMap(map -> map.entrySet()
.stream()
.filter(e -> Objects.equals(e.getValue(), value))
.map(Map.Entry::getKey)
.findAny());
}
Or if you are on JDK7.
private String findKey(Integer value){
for(String key : team1.keySet()){
if(Objects.equals(team1.get(key), value)){
return key; //return the first found
}
}
return null;
}
private List<String> findKeys(Integer value){
List<String> keys = new ArrayList<String>();
for(String key : team1.keySet()){
if(Objects.equals(team1.get(key), value)){
keys.add(key);
}
}
return keys;
}
The problem is that your img
s will always bump down to the next line because of the containing div
.
In order to get around this, you need to place the img
s in their own div
with a width
wide enough to hold all of them. Then you can use your styles as is.
So, when I set the img
s to 120px
each and place them inside a
div#insideDiv{
width:800px;
}
it all works.
Adjust width as necessary.
If you have the .dSYM and the .crash file in the same sub-folder, these are the steps you can take:
$ atos -arch arm64 -o TheElements.app.dSYM/Contents/Resources/DWARF/TheElements -l 0x1000e4000 0x00000001000effdc
-[AtomicElementViewController myTransitionDidStop:finished:context:]
Authoritative source: https://developer.apple.com/library/content/technotes/tn2151/_index.html#//apple_ref/doc/uid/DTS40008184-CH1-SYMBOLICATE_WITH_ATOS
I use the reflections in the toString() implementation of my preference class to see the class members and values (simple and quick debugging).
The simplified code I'm using:
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
Class<?> thisClass = null;
try {
thisClass = Class.forName(this.getClass().getName());
Field[] aClassFields = thisClass.getDeclaredFields();
sb.append(this.getClass().getSimpleName() + " [ ");
for(Field f : aClassFields){
String fName = f.getName();
sb.append("(" + f.getType() + ") " + fName + " = " + f.get(this) + ", ");
}
sb.append("]");
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
I hope that it will help someone, because I also have searched.
I have implemented the method from Varun Vohra's answer here for both lists and dicts.
import math
import numbers
import operator
import itertools
def round_list_percentages(number_list):
"""
Takes a list where all values are numbers that add up to 100,
and rounds them off to integers while still retaining a sum of 100.
A total value sum that rounds to 100.00 with two decimals is acceptable.
This ensures that all input where the values are calculated with [fraction]/[total]
and the sum of all fractions equal the total, should pass.
"""
# Check input
if not all(isinstance(i, numbers.Number) for i in number_list):
raise ValueError('All values of the list must be a number')
# Generate a key for each value
key_generator = itertools.count()
value_dict = {next(key_generator): value for value in number_list}
return round_dictionary_percentages(value_dict).values()
def round_dictionary_percentages(dictionary):
"""
Takes a dictionary where all values are numbers that add up to 100,
and rounds them off to integers while still retaining a sum of 100.
A total value sum that rounds to 100.00 with two decimals is acceptable.
This ensures that all input where the values are calculated with [fraction]/[total]
and the sum of all fractions equal the total, should pass.
"""
# Check input
# Only allow numbers
if not all(isinstance(i, numbers.Number) for i in dictionary.values()):
raise ValueError('All values of the dictionary must be a number')
# Make sure the sum is close enough to 100
# Round value_sum to 2 decimals to avoid floating point representation errors
value_sum = round(sum(dictionary.values()), 2)
if not value_sum == 100:
raise ValueError('The sum of the values must be 100')
# Initial floored results
# Does not add up to 100, so we need to add something
result = {key: int(math.floor(value)) for key, value in dictionary.items()}
# Remainders for each key
result_remainders = {key: value % 1 for key, value in dictionary.items()}
# Keys sorted by remainder (biggest first)
sorted_keys = [key for key, value in sorted(result_remainders.items(), key=operator.itemgetter(1), reverse=True)]
# Otherwise add missing values up to 100
# One cycle is enough, since flooring removes a max value of < 1 per item,
# i.e. this loop should always break before going through the whole list
for key in sorted_keys:
if sum(result.values()) == 100:
break
result[key] += 1
# Return
return result
You can use for loop if you really want to.
char table[][] table = new char[row][col];
for(int i = 0; i < row * col ; ++i){
table[i/row][i % col] = char('a' + (i+1));
}
or do what bhesh said.
With ECMAScript 2015 you can export and import multiple classes like this
class Person
{
constructor()
{
this.type = "Person";
}
}
class Animal{
constructor()
{
this.type = "Animal";
}
}
module.exports = {
Person,
Animal
};
then where you use them:
const { Animal, Person } = require("classes");
const animal = new Animal();
const person = new Person();
In case of name collisions, or you prefer other names you can rename them like this:
const { Animal : OtherAnimal, Person : OtherPerson} = require("./classes");
const animal = new OtherAnimal();
const person = new OtherPerson();
If you are using 'docker-compose' as the method to spin up your container(s), there is actually a useful way to pass an environment variable defined on your server to the Docker container.
In your docker-compose.yml
file, let's say you are spinning up a basic hapi-js container and the code looks like:
hapi_server:
container_name: hapi_server
image: node_image
expose:
- "3000"
Let's say that the local server that your docker project is on has an environment variable named 'NODE_DB_CONNECT' that you want to pass to your hapi-js container, and you want its new name to be 'HAPI_DB_CONNECT'. Then in the docker-compose.yml
file, you would pass the local environment variable to the container and rename it like so:
hapi_server:
container_name: hapi_server
image: node_image
environment:
- HAPI_DB_CONNECT=${NODE_DB_CONNECT}
expose:
- "3000"
I hope this helps you to avoid hard-coding a database connect string in any file in your container!
After trying all the solutions and none giving acceptable results (maybe because I was working on a device with default very large fonts), the following worked for me (COMPLEX_UNIT_DIP = Device Independent Pixels):
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
I had the same issue. I think it was a deadlock issue with SQL. You can just force close the SQL process from Task Manager. If that didn't fix it, just restart your computer. You don't need to drop the table and reload the data.
Swift 3 Extension Variant that preserves existing attributes.
extension UILabel {
func setLineHeight(lineHeight: CGFloat) {
guard self.text != nil && self.attributedText != nil else { return }
var attributedString = NSMutableAttributedString()
if let attributedText = self.attributedText {
attributedString = NSMutableAttributedString(attributedString: attributedText)
} else if let text = self.text {
attributedString = NSMutableAttributedString(string: text)
}
let style = NSMutableParagraphStyle()
style.lineSpacing = lineHeight
style.alignment = self.textAlignment
let str = NSString(string: attributedString.string)
attributedString.addAttribute(NSParagraphStyleAttributeName,
value: style,
range: str.range(of: str as String))
self.attributedText = attributedString
}
}
There are tree ways methods and properties are implemented on function or class objects, and on they instances.
Foo.method()
or Foo.prop
. Those are static methods or propertiesFoo.prototype.method()
or Foo.prototype.prop
. When created, the instances will inherit those object via the prototype witch is {method:function(){...}, prop:...}
. So the foo object will receive, as prototype, a copy of the Foo.prototype object.foo={method:function(){...}, prop:...}
The this
keyword will represent and act differently according to the context. In a static method, it will represent the class itself (witch is after all an instance of Function : class Foo {}
is quite equivalent to let Foo = new Function({})
With ECMAScript 2015, that seems well implemented today, it is clearer to see the difference between class (static) methods and properties, instance methods and properties and own methods ans properties. You can thus create three method or properties having the same name, but being different because they apply to different objects, the this
keyword, in methods, will apply to, respectively, the class object itself and the instance object, by the prototype or by its own.
class Foo {
constructor(){super();}
static prop = "I am static" // see 1.
static method(str) {alert("static method"+str+" :"+this.prop)} // see 1.
prop="I am of an instance"; // see 2.
method(str) {alert("instance method"+str+" : "+this.prop)} // see 2.
}
var foo= new Foo();
foo.prop = "I am of own"; // see 3.
foo.func = function(str){alert("own method" + str + this.prop)} // see 3.
this works for me...
using System.IO;
private long GetTotalFreeSpace(string driveName)
{
foreach (DriveInfo drive in DriveInfo.GetDrives())
{
if (drive.IsReady && drive.Name == driveName)
{
return drive.TotalFreeSpace;
}
}
return -1;
}
good luck!
You can use sshpass for it. Below are the steps
sudo apt-get install sshpass
sshpass -p '#Password_For_remote_machine' scp /home/ubuntu/latest_build/abc.war #user@#RemoteIP:/var/lib/tomcat7/webapps
Code for adding fragment
public Fragment getItem(int position) {
switch (position){
case 0:
return new Fragment1();
case 1:
return new Fragment2();
case 2:
return new Fragment3();
case 3:
return new Fragment4();
default:
break;
}
return null;
}
Create an xml file for each fragment say for Fragment1, use fragment_one.xml as layout file, use the below code in Fragment1 java file.
public class Fragment1 extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
return view;
}
}
Later you can make necessary corrections.. It worked for me.
There are no problems with the second version of the assignment operator. In fact, that is the standard way for an assignment operator.
Edit: Note that I am referring to the return type of the assignment operator, not to the implementation itself. As has been pointed out in comments, the implementation itself is another issue. See here.
I had the same issue lately. Problem was Security Software(Trendmicro) was blocking docker to create Hyperv network interface. You should also check firewall, AV software not blocking installation or configuration.
Oracle used to have a component in SQL Developer called Data Modeler
. It no longer exists in the product since at least 3.2.20.10.
It's now a separate download that you can find here:
http://www.oracle.com/technetwork/developer-tools/datamodeler/overview/index.html
You could define a mapping of air pressure to servo angle, for example:
def calc_angle(pressure, min_p=1000, max_p=1200): return 360 * ((pressure - min_p) / float(max_p - min_p)) angle = calc_angle(pressure)
This will linearly convert pressure
values between min_p
and max_p
to angles between 0 and 360 (you could include min_a
and max_a
to constrain the angle, too).
To pick a data structure, I wouldn't use a list but you could look up values in a dictionary:
d = {1000:0, 1001: 1.8, ...} angle = d[pressure]
but this would be rather time-consuming to type out!
Because you have multiple versions of NumPy installed.
Try pip uninstall numpy
and pip list | grep numpy
several times, until you see no output from pip list | grep numpy
.
Then pip install numpy
will get you the newest version of NumPy.
My implementation:
def get_nested(data, *args):
if args and data:
element = args[0]
if element:
value = data.get(element)
return value if len(args) == 1 else get_nested(value, *args[1:])
Example usage:
>>> dct={"foo":{"bar":{"one":1, "two":2}, "misc":[1,2,3]}, "foo2":123}
>>> get_nested(dct, "foo", "bar", "one")
1
>>> get_nested(dct, "foo", "bar", "two")
2
>>> get_nested(dct, "foo", "misc")
[1, 2, 3]
>>> get_nested(dct, "foo", "missing")
>>>
There are no exceptions raised in case a key is missing, None value is returned in that case.
I faced the same problem , i resolved it by typing :q!
then hit Enter
And it resolved my problem
After that run the the following command
git commit -a -m "your comment here"
This should resolve your problem.
Pipe it to awk
:
awk '{if(NR>1)print}'
or sed
sed -n '1!p'
Alciende's answer didn't quite work for me in Safari for whatever reason just now, but did after a minor modification:
function textAreaAdjust(o) {
o.style.height = "1px";
setTimeout(function() {
o.style.height = (o.scrollHeight)+"px";
}, 1);
}
Hope this helps someone
Try using this:
If you specify
ON DUPLICATE KEY UPDATE
, and a row is inserted that would cause a duplicate value in aUNIQUE index or
PRIMARY KEY, MySQL performs an [
UPDATE`](http://dev.mysql.com/doc/refman/5.7/en/update.html) of the old row...The
ON DUPLICATE KEY UPDATE
clause can contain multiple column assignments, separated by commas.With
ON DUPLICATE KEY UPDATE
, the affected-rows value per row is 1 if the row is inserted as a new row, 2 if an existing row is updated, and 0 if an existing row is set to its current values. If you specify theCLIENT_FOUND_ROWS
flag tomysql_real_connect()
when connecting to mysqld, the affected-rows value is 1 (not 0) if an existing row is set to its current values...
Sample application using Vue. Requires a backend server running on localhost to process the request:
var app = new Vue({
el: "#app",
data: {
file: ''
},
methods: {
submitFile() {
let formData = new FormData();
formData.append('file', this.file);
console.log('>> formData >> ', formData);
// You should have a server side REST API
axios.post('http://localhost:8080/restapi/fileupload',
formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}
).then(function () {
console.log('SUCCESS!!');
})
.catch(function () {
console.log('FAILURE!!');
});
},
handleFileUpload() {
this.file = this.$refs.file.files[0];
console.log('>>>> 1st element in files array >>>> ', this.file);
}
}
});
By default WampServer is installed to port 80 which is already used by IIS. To set WampServer to use an open port, left click on the WampServer icon in the system tray and go to Apache > httpd.conf
Open the httpd.conf in Notepad. press ctrl+f and search for "Listen 80", change this line to "Listen 8080" (u can change this port as what you want), and then close and save the httpd.conf file.
Open a web browser and enter "[];, this will open the WampServer configuration page where you can configure Apache, MySQL, and PHP.
and some times this problem may occur because of skype also use 80 as default port hope this will help
You are trying to alter the behaviour of onclick
inside the same function call. Try it like this:
<a id="loginLink" onclick="toggleTable();" href="#">Login</a>
function toggleTable() {
var lTable = document.getElementById("loginTable");
lTable.style.display = (lTable.style.display == "table") ? "none" : "table";
}
In addition to user2545728 and Reft answers, without javascript but with the modal-backdrop in
3 things to add
modal-backdrop in
before the .modal classstyle="display:block;"
to the .modal classfade in
together with the .modal classExample
<div class="modal-backdrop in"></div>
<div class="modal fade in" tabindex="-1" role="dialog" aria-labelledby="channelModal" style="display:block;">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="channelModal">Welcome!</h4>
</div>
<div class="modal-body" style="height:350px;">
How did you find us?
</div>
</div>
</div>
</div>
The new cv2
interface for Python integrates numpy arrays into the OpenCV framework, which makes operations much simpler as they are represented with simple multidimensional arrays. For example, your question would be answered with:
import cv2 # Not actually necessary if you just want to create an image.
import numpy as np
blank_image = np.zeros((height,width,3), np.uint8)
This initialises an RGB-image that is just black. Now, for example, if you wanted to set the left half of the image to blue and the right half to green , you could do so easily:
blank_image[:,0:width//2] = (255,0,0) # (B, G, R)
blank_image[:,width//2:width] = (0,255,0)
If you want to save yourself a lot of trouble in future, as well as having to ask questions such as this one, I would strongly recommend using the cv2
interface rather than the older cv
one. I made the change recently and have never looked back. You can read more about cv2
at the OpenCV Change Logs.
If you're already using Apache commons, it provides a static method for this:
StringEscapeUtils.escapeJson("some string")
It converts any string into one that's properly escaped for inclusion in JSON
To use the second way, add 1:
print $#arr + 1; # Second way to print array size
I prefer to use typename because I'm not a fan of overloaded keywords (jeez - how many different meanings does static
have for various different contexts?).
This was always the question I had when I was working on one of my application which created massive number of threads per request.
So this is a really good question and there are two aspects of this:
1. Whether my Xms and Xmx value should be same
- Most websites and even oracle docs suggest it to be the same. However, I suggest to have some 10-20% of buffer between those values to give heap resizing an option to your application in case sudden high traffic spikes OR a incidental memory leak.
2. Whether I should start my Application with lower heap size
- So here's the thing - no matter what GC Algo you use (even G1), large heap always has some trade off. The goal is to identify the behavior of your application to what heap size you can allow your GC pauses in terms of latency and throughput.
- For example, if your application has lot of threads (each thread has 1 MB stack in native memory and not in heap) but does not occupy heavy object space, then I suggest have a lower value of Xms.
- If your application creates lot of objects with increasing number of threads, then identify to what value of Xms you can set to tolerate those STW pauses. This means identify the max response time of your incoming requests you can tolerate and according tune the minimum heap size.
"mxc" is right. fetchType
just specifies when the relation should be resolved.
To optimize eager loading by using an outer join you have to add
@Fetch(FetchMode.JOIN)
to your field. This is a hibernate specific annotation.
The first parentheses are for, if you will, order of operations. The 'result' of the set of parentheses surrounding the function definition is the function itself which, indeed, the second set of parentheses executes.
As to why it's useful, I'm not enough of a JavaScript wizard to have any idea. :P
Simple you can use bellow class.
.nopadmar {_x000D_
padding: 0 !important;_x000D_
margin: 0 !important;_x000D_
}
_x000D_
<div class="container-fluid">_x000D_
<div class="row">_x000D_
<div class="col-md-6 nopadmar">Your Content<div>_x000D_
<div class="col-md-6 nopadmar">Your Content<div>_x000D_
</div>_x000D_
</div>
_x000D_
Use something like header( 'Location: /my-other-page.html' );
to redirect. You can't have sent any other data on the page before you do this though.
If you are using WebStorm
, press configuration selection drop down button left of the run button and select edit configurations:
Double click on Start React Native Bundler
at bottom in Before launch
section:
Enter --reset-cache
to Arguments
section:
I had the same issue, docker-compose was creating a directory instead of a file, then crashing mid-way.
what i did :
run the container without mapping the file
copy the config file to the host location :
docker cp containername:/var/www/html/config.php ./config.php
remove the container (docker-compose down)
put the mapping back and remount up the container
docker compose will find the config file, and will map that instead of trying to create a directory.
I really like the YUI3 library for this sort of thing.
<div id="mydiv"> ... </div>
<script>
YUI().use('node-base', function(Y) {
Y.on("available", someFunction, '#mydiv')
})
Adapted from this answer to a very similar question:
FORFILES /S /D -10 /C "cmd /c IF @isdir == TRUE rd /S /Q @path"
You should run this command from within your d:\study
folder. It will delete all subfolders which are older than 10 days.
The /S /Q
after the rd
makes it delete folders even if they are not empty, without prompting.
I suggest you put the above command into a .bat file, and save it as d:\study\cleanup.bat
.
Uploading on Instagram is possible. Their API provides a media upload endpoint, even if it's not documented.
POST https://instagram.com/api/v1/media/upload/
Check this code for example https://code.google.com/p/twitubas/source/browse/common/instagram.php
Use display instead of visibility. display: none for invisible and no setting for visible.
Although very late, hope it still helps someone:
Many of comments here and in other posts are concerned about setting initial size.
I used jqueryUi.Resizable. Initial widths shall be defined within each "< td >" tag at first line (< TR >). This is unlike what colResizable recommends; colResizable prohibits defining widths at first line, there I had to define widths in "< col>" tag which wasn't consikstent with jqueryresizable.
the following snippet is very neat and easier to read than usual samples:
$("#Content td").resizable({
handles: "e, s",
resize: function (event, ui) {
var sizerID = "#" + $(event.target).attr("id");
$(sizerID).width(ui.size.width);
}
});
Content is id of my table. Handles (e, s) define in which directions the plugin can change the size. You must have a link to css of jquery-ui, otherwise it won't work.
pydoc is fantastic for generating documentation, but the documentation has to be written in the first place. You must have docstrings in your source code as was mentioned by RocketDonkey in the comments:
"""
This example module shows various types of documentation available for use
with pydoc. To generate HTML documentation for this module issue the
command:
pydoc -w foo
"""
class Foo(object):
"""
Foo encapsulates a name and an age.
"""
def __init__(self, name, age):
"""
Construct a new 'Foo' object.
:param name: The name of foo
:param age: The ageof foo
:return: returns nothing
"""
self.name = name
self.age = age
def bar(baz):
"""
Prints baz to the display.
"""
print baz
if __name__ == '__main__':
f = Foo('John Doe', 42)
bar("hello world")
The first docstring provides instructions for creating the documentation with pydoc. There are examples of different types of docstrings so you can see how they look when generated with pydoc.
You can also handle index yourself if You need the index, it will not work if You need the key.
let i = 0;
for (const item of iterableItems) {
// do something with index
console.log(i);
i++;
}
exit
terminates the current process; with or without an exit code, consider this a system more than a program function. Note that when sourcing, exit
will end the shell. However, when running, it will just exit
the script.
return
from a function go back to the instruction after the call, with or without a return code. return
is optional and it's implicit at the end of the function. return
can only be used inside a function.
I want to add that while being sourced, it's not easy to exit
the script from within a function without killing the shell. I think, an example is better on a 'test' script:
#!/bin/bash
function die(){
echo ${1:=Something terrible wrong happen}
#... clean your trash
exit 1
}
[ -f /whatever/ ] || die "whatever is not available"
# Now we can proceed
echo "continue"
doing the following:
user$ ./test
Whatever is not available
user$
test
-and- the shell will close.
user$ . ./test
Whatever is not available
Only test
will finish and the prompt will show.
The solution is to enclose the potentially procedure in (
and )
:
#!/bin/bash
function die(){
echo $(1:=Something terrible wrong happen)
#... Clean your trash
exit 1
}
( # Added
[ -f /whatever/ ] || die "whatever is not available"
# Now we can proceed
echo "continue"
) # Added
Now, in both cases only test
will exit.
You want reorder()
. Here is an example with dummy data
set.seed(42)
df <- data.frame(Category = sample(LETTERS), Count = rpois(26, 6))
require("ggplot2")
p1 <- ggplot(df, aes(x = Category, y = Count)) +
geom_bar(stat = "identity")
p2 <- ggplot(df, aes(x = reorder(Category, -Count), y = Count)) +
geom_bar(stat = "identity")
require("gridExtra")
grid.arrange(arrangeGrob(p1, p2))
Giving:
Use reorder(Category, Count)
to have Category
ordered from low-high.
sys.path
. See site
module.A larger list of additional Python file-extensions (mostly rare and unofficial) can be found at http://dcjtech.info/topic/python-file-extensions/
I would simplify the most voted answer to:
BS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def to_base(n, b):
return "0" if not n else to_base(n//b, b).lstrip("0") + BS[n%b]
With the same advice for RuntimeError: maximum recursion depth exceeded in cmp
on very large integers and negative numbers. (You could usesys.setrecursionlimit(new_limit)
)
To avoid recursion problems:
BS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def to_base(s, b):
res = ""
while s:
res+=BS[s%b]
s//= b
return res[::-1] or "0"
public string phoneformat(string phnumber)
{
String phone=phnumber;
string countrycode = phone.Substring(0, 3);
string Areacode = phone.Substring(3, 3);
string number = phone.Substring(6,phone.Length);
phnumber="("+countrycode+")" +Areacode+"-" +number ;
return phnumber;
}
Output will be :001-568-895623
You could use border-top-left-radius
and border-top-right-radius
properties to round the corners on the box according to the box's height (and added borders).
Then add a border to top/right/left sides of the box to achieve the effect.
Here you go:
.half-circle {
width: 200px;
height: 100px; /* as the half of the width */
background-color: gold;
border-top-left-radius: 110px; /* 100px of height + 10px of border */
border-top-right-radius: 110px; /* 100px of height + 10px of border */
border: 10px solid gray;
border-bottom: 0;
}
Alternatively, you could add box-sizing: border-box
to the box in order to calculate the width/height of the box including borders and padding.
.half-circle {
width: 200px;
height: 100px; /* as the half of the width */
border-top-left-radius: 100px;
border-top-right-radius: 100px;
border: 10px solid gray;
border-bottom: 0;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
UPDATED DEMO. (Demo without background color)
Object AccountObject = _dbContext.Accounts
.Join(_dbContext.Users, acc => acc.AccountId, usr => usr.AccountId, (acc, usr) => new { acc, usr })
.Where(x => x.usr.EmailAddress == key1)
.Where(x => x.usr.Hash == key2)
.Select(x => new { AccountId = x.acc.AccountId, Name = x.acc.Name })
.SingleOrDefault();
In the pattern, the inclusion of a 'z' date-time component indicates that timezone format needs to conform to the General time zone "standard", examples of which are Pacific Standard Time; PST; GMT-08:00
.
A 'Z' indicates that the timezone conforms to the RFC 822 time zone standard, e.g. -0800
.
I think you need a DatatypeConverter ...
@Test
public void testTimezoneIsGreenwichMeanTime() throws ParseException {
final Calendar calendar = javax.xml.bind.DatatypeConverter.parseDateTime("2010-04-05T17:16:00Z");
TestCase.assertEquals("gotten timezone", "GMT+00:00", calendar.getTimeZone().getID());
}
I have a feeling that most answers here overcomplicate the simple problem. If you already understand how the map
works that should be fairly easy to grasp.
There are cases where we can end up with unwanted nested structures when using map()
, the flatMap()
method is designed to overcome this by avoiding wrapping.
Examples:
List<List<Integer>> result = Stream.of(Arrays.asList(1), Arrays.asList(2, 3))
.collect(Collectors.toList());
We can avoid having nested lists by using flatMap
:
List<Integer> result = Stream.of(Arrays.asList(1), Arrays.asList(2, 3))
.flatMap(i -> i.stream())
.collect(Collectors.toList());
Optional<Optional<String>> result = Optional.of(42)
.map(id -> findById(id));
Optional<String> result = Optional.of(42)
.flatMap(id -> findById(id));
where:
private Optional<String> findById(Integer id)
Recommendedations from the Python 2.7 docs for the time
module
Well, you can compute the height of a tree with the following recursive function:
int height(struct tree *t) {
if (t == NULL)
return 0;
else
return max(height(t->left), height(t->right)) + 1;
}
with an appropriate definition of max()
and struct tree
. You should take the time to figure out why this corresponds to the definition based on path-length that you quote. This function uses zero as the height of the empty tree.
However, for something like an AVL tree, I don't think you actually compute the height each time you need it. Instead, each tree node is augmented with a extra field that remembers the height of the subtree rooted at that node. This field has to be kept up-to-date as the tree is modified by insertions and deletions.
I suspect that, if you compute the height each time instead of caching it within the tree like suggested above, that the AVL tree shape will be correct, but it won't have the expected logarithmic performance.
The issue is that you're not saving the mysqli connection. Change your connect to:
$aVar = mysqli_connect('localhost','tdoylex1_dork','dorkk','tdoylex1_dork');
And then include it in your query:
$query1 = mysqli_query($aVar, "SELECT name1 FROM users
ORDER BY RAND()
LIMIT 1");
$aName1 = mysqli_fetch_assoc($query1);
$name1 = $aName1['name1'];
Also don't forget to enclose your connections variables as strings as I have above. This is what's causing the error but you're using the function wrong, mysqli_query returns a query object but to get the data out of this you need to use something like mysqli_fetch_assoc http://php.net/manual/en/mysqli-result.fetch-assoc.php to actually get the data out into a variable as I have above.
A Singleton (and this isn't tied to C#, it's an OO design pattern) is when you want to allow only ONE instance of a class to be created throughout your application. Useages would typically include global resources, although I will say from personal experience, they're very often the source of great pain.
b = a[a>threshold]
this should do
I tested as follows:
import numpy as np, datetime
# array of zeros and ones interleaved
lrg = np.arange(2).reshape((2,-1)).repeat(1000000,-1).flatten()
t0 = datetime.datetime.now()
flt = lrg[lrg==0]
print datetime.datetime.now() - t0
t0 = datetime.datetime.now()
flt = np.array(filter(lambda x:x==0, lrg))
print datetime.datetime.now() - t0
I got
$ python test.py
0:00:00.028000
0:00:02.461000
http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays
Can I pass parameters by reference in Java?
No.
Why ? Java has only one mode of passing arguments to methods: by value.
Note:
For primitives this is easy to understand: you get a copy of the value.
For all other you get a copy of the reference and this is called also passing by value.
It is all in this picture:
Using recursion:
function isPalindromeRecursive(str) {
const isLessThan2 = str.length < 2;
const firstAndLastEqual = str.slice(0, 1) === str.slice(-1);
return !isLessThan2 && firstAndLastEqual
? isPalindromeRecursive(str.slice(1, -1))
: isLessThan2;
}
You can use SQL Management Objects to perform this. These are the same objects that Management Studio uses to execute queries. I believe Server.ConnectionContext.ExecuteNonQuery()
will perform what you need.
you need to include the Wordpress loop in your search.php this is example
search.php template file:
<?php get_header(); ?>
<?php
$s=get_search_query();
$args = array(
's' =>$s
);
// The Query
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
_e("<h2 style='font-weight:bold;color:#000'>Search Results for: ".get_query_var('s')."</h2>");
while ( $the_query->have_posts() ) {
$the_query->the_post();
?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php
}
}else{
?>
<h2 style='font-weight:bold;color:#000'>Nothing Found</h2>
<div class="alert alert-info">
<p>Sorry, but nothing matched your search criteria. Please try again with some different keywords.</p>
</div>
<?php } ?>
<?php get_sidebar(); ?>
<?php get_footer(); ?>
I know this is old, but it is actually very possible.
Go to your WinSCP profile (Session > Sites > Site Manager)
Click on Edit > Advanced... > Environment > SFTP
Insert sudo su -c /usr/lib/sftp-server
in "SFTP Server" (note this path might be different in your system)
Save and connect
Say, for an user, there is revision for each date. The following will pick up record for the max revision of each date for each employee.
select job, adate, rev, usr, typ
from tbl
where exists ( select 1 from ( select usr, adate, max(rev) as max_rev
from tbl
group by usr, adate
) as cond
where tbl.usr=cond.usr
and tbl.adate =cond.adate
and tbl.rev =cond.max_rev
)
order by adate, job, usr
#more {
background:none;
border:none;
color:#FFF;
font-family:Verdana, Geneva, sans-serif;
cursor: pointer;
}
if name in ("Jesse", "jesse"):
would be the correct way to do it.
Although, if you want to use or
, the statement would be
if name == 'Jesse' or name == 'jesse':
>>> ("Jesse" or "jesse")
'Jesse'
evaluates to 'Jesse'
, so you're essentially not testing for 'jesse'
when you do if name == ("Jesse" or "jesse")
, since it only tests for equality to 'Jesse'
and does not test for 'jesse'
, as you observed.
https://guide.macports.org/
sudo port install openssl
or sudo port upgrade openssl
openssl version
to see the result.In my case, R.java was not generating because there was a problem in AndroidManifest.xml file wherein I had wrongly specified the name of an activity!
Long story short, low coupling as I understood it meant components can be swapped out without affecting the proper functioning of a system. Basicaly modulize your system into functioning components that can be updated individually without breaking the system
Another option is to use placeholders.
Html:
<body>
<div id="root">
<asp:PlaceHolder ID="iframeDiv" runat="server"/>
</div>
</body>
C#:
iframeDiv.Controls.Add(new LiteralControl("<iframe src=\"" + whatever.com + "\"></iframe><br />"));
Python: Reads image blob.jpg and performs blob detection with different parameters.
#!/usr/bin/python
# Standard imports
import cv2
import numpy as np;
# Read image
im = cv2.imread("blob.jpg")
# Setup SimpleBlobDetector parameters.
params = cv2.SimpleBlobDetector_Params()
# Change thresholds
params.minThreshold = 10
params.maxThreshold = 200
# Filter by Area.
params.filterByArea = True
params.minArea = 1500
# Filter by Circularity
params.filterByCircularity = True
params.minCircularity = 0.1
# Filter by Convexity
params.filterByConvexity = True
params.minConvexity = 0.87
# Filter by Inertia
params.filterByInertia = True
params.minInertiaRatio = 0.01
# Create a detector with the parameters
detector = cv2.SimpleBlobDetector(params)
# Detect blobs.
keypoints = detector.detect(im)
# Draw detected blobs as red circles.
# cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS ensures
# the size of the circle corresponds to the size of blob
im_with_keypoints = cv2.drawKeypoints(im, keypoints, np.array([]), (0,0,255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
# Show blobs
cv2.imshow("Keypoints", im_with_keypoints)
cv2.waitKey(0)
C++: Reads image blob.jpg and performs blob detection with different parameters.
#include "opencv2/opencv.hpp"
using namespace cv;
using namespace std;
int main(int argc, char** argv)
{
// Read image
#if CV_MAJOR_VERSION < 3 // If you are using OpenCV 2
Mat im = imread("blob.jpg", CV_LOAD_IMAGE_GRAYSCALE);
#else
Mat im = imread("blob.jpg", IMREAD_GRAYSCALE);
#endif
// Setup SimpleBlobDetector parameters.
SimpleBlobDetector::Params params;
// Change thresholds
params.minThreshold = 10;
params.maxThreshold = 200;
// Filter by Area.
params.filterByArea = true;
params.minArea = 1500;
// Filter by Circularity
params.filterByCircularity = true;
params.minCircularity = 0.1;
// Filter by Convexity
params.filterByConvexity = true;
params.minConvexity = 0.87;
// Filter by Inertia
params.filterByInertia = true;
params.minInertiaRatio = 0.01;
// Storage for blobs
std::vector<KeyPoint> keypoints;
#if CV_MAJOR_VERSION < 3 // If you are using OpenCV 2
// Set up detector with params
SimpleBlobDetector detector(params);
// Detect blobs
detector.detect(im, keypoints);
#else
// Set up detector with params
Ptr<SimpleBlobDetector> detector = SimpleBlobDetector::create(params);
// Detect blobs
detector->detect(im, keypoints);
#endif
// Draw detected blobs as red circles.
// DrawMatchesFlags::DRAW_RICH_KEYPOINTS flag ensures
// the size of the circle corresponds to the size of blob
Mat im_with_keypoints;
drawKeypoints(im, keypoints, im_with_keypoints, Scalar(0, 0, 255), DrawMatchesFlags::DRAW_RICH_KEYPOINTS);
// Show blobs
imshow("keypoints", im_with_keypoints);
waitKey(0);
}
The answer has been copied from this tutorial I wrote at LearnOpenCV.com explaining various parameters of SimpleBlobDetector. You can find additional details about the parameters in the tutorial.
I ran into the same issue while using CMB2 with Wordpress and wanted to hook into the change event of a file upload metabox.
So in case you're not able to modify the code that invokes the change (in this case the CMB2 script), use the code below. The trigger is being invoked AFTER the value is set, otherwise your change eventHandler will work, but the value will be the previous one, not the one being set.
Here's the code i use:
(function ($) {
var originalVal = $.fn.val;
$.fn.val = function (value) {
if (arguments.length >= 1) {
// setter invoked, do processing
return originalVal.call(this, value).trigger('change');
}
//getter invoked do processing
return originalVal.call(this);
};
})(jQuery);
also you can try this
date.timezone = <?php date('Y'); ?>
Another option would be to add engine='python'
to the command pandas.read_csv(filename, sep='\t', engine='python')
create procedure PSaleCForms
as
begin
declare
@b varchar(9),
@c nvarchar(500),
@q nvarchar(max)
declare @T table(FY nvarchar(9),Qtr int,title nvarchar (max),invoicenumber nvarchar(max),invoicedate datetime,sp decimal 18,2),grandtotal decimal(18,2))
declare @data cursor
set @data= Cursor
forward_only static
for
select x.DBTitle,y.CurrentFinancialYear from [Accounts Manager].dbo.DBManager x inner join [Accounts Manager].dbo.Accounts y on y.DBID=x.DBID where x.cfy=1
open @data
fetch next from @data
into @c,@b
while @@FETCH_STATUS=0
begin
set @q=N'Select '''+@b+''' [fy], case cast(month(i.invoicedate)/3.1 as int) when 0 then 4 else cast(month(i.invoicedate)/3.1 as int) end [Qtr], l.title,i.invoicenumber,i.invoicedate,i.sp,i.grandtotal from ['+@c+'].dbo.invoicemain i inner join ['+@c+'].dbo.ledgermain l on l.ledgerid=i.ledgerid where (sp=0 or stocktype=''x'') and invoicetype=''DS'''
insert into @T exec [master].dbo.sp_executesql @q fetch next from @data into @c,@b end close @data deallocate @data select * from @T return end
1st method
MyTable.objects.filter(pk=some_value).update(field1='some value')
2nd Method
q = MyModel.objects.get(pk=some_value)
q.field1 = 'some value'
q.save()
3rd method
By using get_object_or_404
q = get_object_or_404(MyModel,pk=some_value)
q.field1 = 'some value'
q.save()
4th Method
if you required if pk=some_value
exist then update
it other wise create
new one by using update_or_create
.
MyModel.objects.update_or_create(pk=some_value,defaults={'field1':'some value'})
pip list -v
can be used to list packages' install locations, introduced in https://pip.pypa.io/en/stable/news/#b1-2018-03-31
Show install locations when list command ran with “-v” option. (#979)
>pip list -v
Package Version Location Installer
------------------------ --------- -------------------------------------------------------------------- ---------
alabaster 0.7.12 c:\users\me\appdata\local\programs\python\python38\lib\site-packages pip
apipkg 1.5 c:\users\me\appdata\local\programs\python\python38\lib\site-packages pip
argcomplete 1.10.3 c:\users\me\appdata\local\programs\python\python38\lib\site-packages pip
astroid 2.3.3 c:\users\me\appdata\local\programs\python\python38\lib\site-packages pip
...
This feature is introduced in pip
10.0.0b1. On Ubuntu 18.04 (Bionic Beaver), pip
or pip3
installed with sudo apt install python-pip
or sudo apt install python3-pip
is 9.0.1 which doesn't have this feature.
Check https://github.com/pypa/pip/issues/5599 for suitable ways of upgrading pip
or pip3
.
I wish the Lukas Olsen solution works for other scenarios, But in my case is quite different.
I faced the same while add ActionBarShelock to project, by comparing to the older library I found that application tag is missing in manifest. By adding one line I fixed my issue.
</application>
Datanewolf's code is ALMOST right. I had to reverse both the winding and the normals to make it work properly with the fixed pipeline. The below works correctly with cull on or off for me:
std::vector<GLfloat> vertices;
std::vector<GLfloat> normals;
std::vector<GLfloat> texcoords;
std::vector<GLushort> indices;
float const R = 1./(float)(rings-1);
float const S = 1./(float)(sectors-1);
int r, s;
vertices.resize(rings * sectors * 3);
normals.resize(rings * sectors * 3);
texcoords.resize(rings * sectors * 2);
std::vector<GLfloat>::iterator v = vertices.begin();
std::vector<GLfloat>::iterator n = normals.begin();
std::vector<GLfloat>::iterator t = texcoords.begin();
for(r = 0; r < rings; r++) for(s = 0; s < sectors; s++) {
float const y = sin( -M_PI_2 + M_PI * r * R );
float const x = cos(2*M_PI * s * S) * sin( M_PI * r * R );
float const z = sin(2*M_PI * s * S) * sin( M_PI * r * R );
*t++ = s*S;
*t++ = r*R;
*v++ = x * radius;
*v++ = y * radius;
*v++ = z * radius;
*n++ = -x;
*n++ = -y;
*n++ = -z;
}
indices.resize(rings * sectors * 4);
std::vector<GLushort>::iterator i = indices.begin();
for(r = 0; r < rings-1; r++)
for(s = 0; s < sectors-1; s++) {
/*
*i++ = r * sectors + s;
*i++ = r * sectors + (s+1);
*i++ = (r+1) * sectors + (s+1);
*i++ = (r+1) * sectors + s;
*/
*i++ = (r+1) * sectors + s;
*i++ = (r+1) * sectors + (s+1);
*i++ = r * sectors + (s+1);
*i++ = r * sectors + s;
}
Edit: There was a question on how to draw this... in my code I encapsulate these values in a G3DModel class. This is my code to setup the frame, draw the model, and end it:
void GraphicsProvider3DPriv::BeginFrame()const{
int win_width;
int win_height;// framework of choice here
glfwGetWindowSize(window, &win_width, &win_height); // retrieve window
float const win_aspect = (float)win_width / (float)win_height;
// set lighting
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_DEPTH_TEST);
GLfloat lightpos[] = {0, 0.0, 0, 0.};
glLightfv(GL_LIGHT0, GL_POSITION, lightpos);
GLfloat lmodel_ambient[] = { 0.2, 0.2, 0.2, 1.0 };
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);
glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
// set up world transform
glClearColor(0.f, 0.f, 0.f, 1.f);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT|GL_ACCUM_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45, win_aspect, 1, 10);
glMatrixMode(GL_MODELVIEW);
}
void GraphicsProvider3DPriv::DrawModel(const G3DModel* model, const Transform3D transform)const{
G3DModelPriv* privModel = (G3DModelPriv *)model;
glPushMatrix();
glLoadMatrixf(transform.GetOGLData());
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, &privModel->vertices[0]);
glNormalPointer(GL_FLOAT, 0, &privModel->normals[0]);
glTexCoordPointer(2, GL_FLOAT, 0, &privModel->texcoords[0]);
glEnable(GL_TEXTURE_2D);
//glFrontFace(GL_CCW);
glEnable(GL_CULL_FACE);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, privModel->texname);
glDrawElements(GL_QUADS, privModel->indices.size(), GL_UNSIGNED_SHORT, &privModel->indices[0]);
glPopMatrix();
glDisable(GL_TEXTURE_2D);
}
void GraphicsProvider3DPriv::EndFrame()const{
/* Swap front and back buffers */
glDisable(GL_LIGHTING);
glDisable(GL_LIGHT0);
glDisable(GL_CULL_FACE);
glfwSwapBuffers(window);
/* Poll for and process events */
glfwPollEvents();
}
As an addition to Yorro's answer, it can also be done by using attributes.
Sample for int
type unique key combination:
[Index("IX_UniqueKeyInt", IsUnique = true, Order = 1)]
public int UniqueKeyIntPart1 { get; set; }
[Index("IX_UniqueKeyInt", IsUnique = true, Order = 2)]
public int UniqueKeyIntPart2 { get; set; }
If the data type is string
, then MaxLength
attribute must be added:
[Index("IX_UniqueKeyString", IsUnique = true, Order = 1)]
[MaxLength(50)]
public string UniqueKeyStringPart1 { get; set; }
[Index("IX_UniqueKeyString", IsUnique = true, Order = 2)]
[MaxLength(50)]
public string UniqueKeyStringPart2 { get; set; }
If there is a domain/storage model separation concern, using Metadatatype
attribute/class can be an option: https://msdn.microsoft.com/en-us/library/ff664465%28v=pandp.50%29.aspx?f=255&MSPPError=-2147217396
A quick console app example:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
namespace EFIndexTest
{
class Program
{
static void Main(string[] args)
{
using (var context = new AppDbContext())
{
var newUser = new User { UniqueKeyIntPart1 = 1, UniqueKeyIntPart2 = 1, UniqueKeyStringPart1 = "A", UniqueKeyStringPart2 = "A" };
context.UserSet.Add(newUser);
context.SaveChanges();
}
}
}
[MetadataType(typeof(UserMetadata))]
public class User
{
public int Id { get; set; }
public int UniqueKeyIntPart1 { get; set; }
public int UniqueKeyIntPart2 { get; set; }
public string UniqueKeyStringPart1 { get; set; }
public string UniqueKeyStringPart2 { get; set; }
}
public class UserMetadata
{
[Index("IX_UniqueKeyInt", IsUnique = true, Order = 1)]
public int UniqueKeyIntPart1 { get; set; }
[Index("IX_UniqueKeyInt", IsUnique = true, Order = 2)]
public int UniqueKeyIntPart2 { get; set; }
[Index("IX_UniqueKeyString", IsUnique = true, Order = 1)]
[MaxLength(50)]
public string UniqueKeyStringPart1 { get; set; }
[Index("IX_UniqueKeyString", IsUnique = true, Order = 2)]
[MaxLength(50)]
public string UniqueKeyStringPart2 { get; set; }
}
public class AppDbContext : DbContext
{
public virtual DbSet<User> UserSet { get; set; }
}
}
With the release of Android 2.3 (Gingerbread), you can now use the android.hardware.Camera
class to get the number of cameras, information about a specific camera, and get a reference to a specific Camera
. Check out the new Camera
APIs here.
It is possible to build an arbitrary GET or POST request and send it to any server accessible to a victims browser. This includes devices on your local network, such as Printers and Routers.
There are many ways of building a CSRF exploit. A simple POST based CSRF attack can be sent using .submit()
method. More complex attacks, such as cross-site file upload CSRF attacks will exploit CORS use of the xhr.withCredentals behavior.
CSRF does not violate the Same-Origin Policy For JavaScript because the SOP is concerned with JavaScript reading the server's response to a clients request. CSRF attacks don't care about the response, they care about a side-effect, or state change produced by the request, such as adding an administrative user or executing arbitrary code on the server.
Make sure your requests are protected using one of the methods described in the OWASP CSRF Prevention Cheat Sheet. For more information about CSRF consult the OWASP page on CSRF.
No -- AL is the 8 least significant bits of AX. AX is the 16 least significant bits of EAX.
Perhaps it's easiest to deal with if we start with 04030201h in eax. In this case, AX will contain 0201h, AH wil contain 02h and AL will contain 01h.
This is for others who would have struggled like me to get this working....I wasted more than half a day on a seemingly trivial thing...
If you want to use SQL Express 2012 LocalDB from VS2010 you must have this patch installed http://www.microsoft.com/en-us/download/details.aspx?id=27756
Just like mentioned in the comments above I too had Microsoft .NET Framework Version 4.0.30319 SP1Rel and since its mentioned everywhere that you need "Framework 4.0.2 or Above" I thought I am good to go...
However, when I explicitly downloaded that 4.0.2 patch and installed it I got it working....
foreach($yourArrayName as $object)
{
$arrays[] = $object->toArray();
}
// Dump array with object-arrays
dd($arrays);
Or when toArray()
fails because it's a stdClass
foreach($yourArrayName as $object)
{
$arrays[] = (array) $object;
}
// Dump array with object-arrays
dd($arrays);
Not working? Maybe you can find your answer here:
From docs and example it is not clear that classpath manipulation is not allowed.
<configuration>
<compilerArgs>
<arg>classpath=${basedir}/lib/bad.jar</arg>
</compilerArgs>
</configuration>
But see Java docs (also https://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/tooldocs/solaris/javac.html)
-classpath path Specifies the path javac uses to look up classes needed to run javac or being referenced by other classes you are compiling. Overrides the default or the CLASSPATH environment variable if it is set.
Maybe it is possible to get current classpath and extend it,
see in maven, how output the classpath being used?
<properties>
<cpfile>cp.txt</cpfile>
</properties>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.9</version>
<executions>
<execution>
<id>build-classpath</id>
<phase>generate-sources</phase>
<goals>
<goal>build-classpath</goal>
</goals>
<configuration>
<outputFile>${cpfile}</outputFile>
</configuration>
</execution>
</executions>
</plugin>
Read file (Read a file into a Maven property)
<plugin>
<groupId>org.codehaus.gmaven</groupId>
<artifactId>gmaven-plugin</artifactId>
<version>1.4</version>
<executions>
<execution>
<phase>generate-resources</phase>
<goals>
<goal>execute</goal>
</goals>
<configuration>
<source>
def file = new File(project.properties.cpfile)
project.properties.cp = file.getText()
</source>
</configuration>
</execution>
</executions>
</plugin>
and finally
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<compilerArgs>
<arg>classpath=${cp}:${basedir}/lib/bad.jar</arg>
</compilerArgs>
</configuration>
</plugin>
I also came across the same problem. In my case, I was using transfermode = streaming with Mtom. As it turns out, I had named one of my variables (for a structure), "HEADER". This conflicted with the message element [http://tempuri.org/:HEADER] as part of the http service download. Clearly, one must avoid using "reserved" words as parameter name.
If you want to add a dynamic class to your host element, you may combine your HostBinding
with a getter as
@HostBinding('class') get class() {
return aComponentVariable
}
Stackblitz demo at https://stackblitz.com/edit/angular-dynamic-hostbinding
tmtheme-editor.herokuapp.com seems pretty nice.
On the mac, the default theme files are in ~/Library/Application\ Support/Sublime\ Text\ 2/Packages/Color\ Scheme\ -\ Default
On Win7, the default theme files are in %appdata%\Sublime Text 2\Packages\Color Scheme - Default
I'll add 2 points:
So, the 2 expressions are simply not equal.
WHERE some_col in (1,2,3,4,5) AND some_other_expr
--to the optimiser is this
WHERE
(
some_col = 1 OR
some_col = 2 OR
some_col = 3 OR
some_col = 4 OR
some_col = 5
)
AND
some_other_expr
So, when you break the IN clause up, you split the serial ORs up, and changed precedence.
Like this:
str_replace(array(':', '\\', '/', '*'), ' ', $string);
Or, in modern PHP (anything from 5.4 onwards), the slighty less wordy:
str_replace([':', '\\', '/', '*'], ' ', $string);