Try resolving the issue with either of the following options:
Start-Service "Hyper-V Virtual Machine Management"
Start-Service "Hyper-V Host Compute Service"
or
Open "Window Security"
Open "App & Browser control"
Click "Exploit protection settings" at the bottom
Switch to "Program settings" tab
Locate "C:\WINDOWS\System32\vmcompute.exe" in the list and expand it
Click "Edit"
Scroll down to "Code flow guard (CFG)" and uncheck "Override system settings"
Start vmcompute from powershell "net start vmcompute"
Then restart your system
To make it work without modifying your scripts:
I found a solution here: http://wahlnetwork.com/2015/11/17/solving-the-first-launch-configuration-error-with-powershells-invoke-webrequest-cmdlet/
The error is probably coming up because IE has not yet been launched for the first time, bringing up the window below. Launch it and get through that screen, and then the error message will not come up any more. No need to modify any scripts.
First of all you missed ScriptService attribute to add in webservice.
[ScriptService]
After then try following method to call webservice via JSON.
var webAddr = "http://Domain/VBRService.asmx/callJson"; var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr); httpWebRequest.ContentType = "application/json; charset=utf-8"; httpWebRequest.Method = "POST"; using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { string json = "{\"x\":\"true\"}"; streamWriter.Write(json); streamWriter.Flush(); } var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { var result = streamReader.ReadToEnd(); return result; }
In my case the problem was because of conflicting Jars.
Here is the full list of jars which is working absolutely fine for me.
antlr-2.7.7.jar
byte-buddy-1.8.12.jar
c3p0-0.9.5.2.jar
classmate-1.3.4.jar
dom4j-1.6.1.jar
geolatte-geom-1.3.0.jar
hibernate-c3p0-5.3.1.Final.jar
hibernate-commons-annotations-5.0.3.Final.jar
hibernate-core-5.3.1.Final.jar
hibernate-envers-5.3.1.Final.jar
hibernate-jpamodelgen-5.3.1.Final.jar
hibernate-osgi-5.3.1.Final.jar
hibernate-proxool-5.3.1.Final.jar
hibernate-spatial-5.3.1.Final.jar
jandex-2.0.3.Final.jar
javassist-3.22.0-GA.jar
javax.interceptor-api-1.2.jar
javax.persistence-api-2.2.jar
jboss-logging-3.3.2.Final.jar
jboss-transaction-api_1.2_spec-1.1.1.Final.jar
jts-core-1.14.0.jar
mchange-commons-java-0.2.11.jar
mysql-connector-java-5.1.21.jar
org.osgi.compendium-4.3.1.jar
org.osgi.core-4.3.1.jar
postgresql-42.2.2.jar
proxool-0.8.3.jar
slf4j-api-1.6.1.jar
In Visual Studio 2019 I was able to fix it by changing the dropdown to Release as recommended in other answers. But when I changed back to Debug mode the error appeared again.
What fixed it for me in Debug mode:
You need to install JMF first (download using this link)
File f = new File("D:/Songs/preview.mp3");
MediaLocator ml = new MediaLocator(f.toURL());
Player p = Manager.createPlayer(ml);
p.start();
don't forget to add JMF jar files
I have seen the following error twice in the past week or so:
adb server version (40) doesn't match this client (41)
I fixed it by rebooting my PC every time. I do not know how to explain it.
I tried killing and starting adb via command line multiple timea, restarting Android Studio multiple times to no avail. Task Manager does not show adb.exe.
I am running Android Studio 3.4 on Windows 10 (V1809, Build:17763.503)
Edit (2019-05-30): When this happened for the 3rd time, I closed all applications, then restarted Android Studio, and the problem was solved. It seems that another application causes this. I will report back once I find the culprit.
Edit (2019-05-30): I have finally found the culprit - Visual Studio paired with a Macbook Pro for building and debugging an iOS app. Once VS is closed or the pairding is disabled, adb becomes normal.
In the specific case of Wicket: This is the very reason why I asked the Wicket devs to add support for an explicit two phase component initialization process in the framework's lifecycle of constructing a component i.e.
There was quite an active debate about whether it was necessary or not (it fully is necessary IMHO) as this link demonstrates http://apache-wicket.1842946.n4.nabble.com/VOTE-WICKET-3218-Component-onInitialize-is-broken-for-Pages-td3341090i20.html)
The good news is that the excellent devs at Wicket did end up introducing two phase initialization (to make the most aweseome Java UI framework even more awesome!) so with Wicket you can do all your post construction initialization in the onInitialize method that is called by the framework automatically if you override it - at this point in the lifecycle of your component its constructor has completed its work so virtual methods work as expected.
At the end of your lines, simply add the following special character: 
That special character defines the carriage-return character.
C++
The first one is good for beginners and the second one requires more advanced level in C++.
A good resource to teach young people is the free eBook "Invent your own games with Python":
A simple possibility (if you'd rather avoid REs) is
' '.join(mystring.split())
The split and join perform the task you're explicitly asking about -- plus, they also do the extra one that you don't talk about but is seen in your example, removing trailing spaces;-).
It sounds like the populate method is what your looking for. First make small change to your post schema:
var postSchema = new Schema({
name: String,
postedBy: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
dateCreated: Date,
comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}],
});
Then make your model:
var Post = mongoose.model('Post', postSchema);
Then, when you make your query, you can populate references like this:
Post.findOne({_id: 123})
.populate('postedBy')
.exec(function(err, post) {
// do stuff with post
});
when: myvar | default('', true) | trim != ''
I use | trim != ''
to check if a variable has an empty value or not. I also always add the | default(..., true)
check to catch when myvar
is undefined too.
WCF completely replaces ASMX web services. ASMX is the old way to do web services and WCF is the current way to do web services. All new SOAP web service development, on the client or the server, should be done using WCF.
Converting to a DATE
or using an open-ended date range in any case will yield the best performance. FYI, convert to date using an index are the best performers. More testing a different techniques in article: What is the most efficient way to trim time from datetime? Posted by Aaron Bertrand
From that article:
DECLARE @dateVar datetime = '19700204';
-- Quickest when there is an index on t.[DateColumn],
-- because CONVERT can still use the index.
SELECT t.[DateColumn]
FROM MyTable t
WHERE = CONVERT(DATE, t.[DateColumn]) = CONVERT(DATE, @dateVar);
-- Quicker when there is no index on t.[DateColumn]
DECLARE @dateEnd datetime = DATEADD(DAY, 1, @dateVar);
SELECT t.[DateColumn]
FROM MyTable t
WHERE t.[DateColumn] >= @dateVar AND
t.[DateColumn] < @dateEnd;
Also from that article: using BETWEEN
, DATEDIFF
or CONVERT(CHAR(8)...
are all slower.
The Gutenberg Project hosts Webster's Unabridged English Dictionary plus many other public domain literary works. Actually it looks like they've got several versions of the dictionary hosted with copyright from different years. The one I linked has a 2009 copyright. You may want to poke around the site and investigate the different versions of Webster's dictionary.
check out this page from flutter wiki :
Use the LayoutBuilder class: From its builder property, you get a BoxConstraints. Examine the constraint's properties to decide what to display. For example, if your maxWidth is greater than your width breakpoint, return a Scaffold object with a row that has a list on the left. If it's narrower, return a Scaffold object with a drawer containing that list. You can also adjust your display based on the device's height, the aspect ratio, or some other property. When the constraints change (e.g. the user rotates the phone, or puts your app into a tile UI in Nougat), the build function will rerun.
Looks like @mixin
and @include
are not needed for a simple case like this.
One can just do:
.myclass {
font-weight: bold;
font-size: 90px;
}
.myotherclass {
@extend .myclass;
color: #000000;
}
These parameters are typically used for proxy functions, so the proxy can pass any input parameter to the target function.
def foo(bar=2, baz=5):
print bar, baz
def proxy(x, *args, **kwargs): # reqire parameter x and accept any number of additional arguments
print x
foo(*args, **kwargs) # applies the "non-x" parameter to foo
proxy(23, 5, baz='foo') # calls foo with bar=5 and baz=foo
proxy(6)# calls foo with its default arguments
proxy(7, bar='asdas') # calls foo with bar='asdas' and leave baz default argument
But since these parameters hide the actual parameter names, it is better to avoid them.
If it is full binary tree with children of node x as 2*x and 2*x+1 than there is a faster way to do it
int get_bits(unsigned int x) {
int high = 31;
int low = 0,mid;
while(high>=low) {
mid = (high+low)/2;
if(1<<mid==x)
return mid+1;
if(1<<mid<x) {
low = mid+1;
}
else {
high = mid-1;
}
}
if(1<<mid>x)
return mid;
return mid+1;
}
unsigned int Common_Ancestor(unsigned int x,unsigned int y) {
int xbits = get_bits(x);
int ybits = get_bits(y);
int diff,kbits;
unsigned int k;
if(xbits>ybits) {
diff = xbits-ybits;
x = x >> diff;
}
else if(xbits<ybits) {
diff = ybits-xbits;
y = y >> diff;
}
k = x^y;
kbits = get_bits(k);
return y>>kbits;
}
How does it work
- get bits needed to represent x & y which using binary search is O(log(32))
- the common prefix of binary notation of x & y is the common ancestor
- whichever is represented by larger no of bits is brought to same bit by k >> diff
- k = x^y erazes common prefix of x & y
- find bits representing the remaining suffix
- shift x or y by suffix bits to get common prefix which is the common ancestor.
This works because basically divide the larger number by two recursively until both numbers are equal. That number is the common ancestor. Dividing is effectively the right shift opearation. So we need to find common prefix of two numbers to find the nearest ancestor
Fancybox currently does not directly support a way to automatically launch. The work around I was able to get working is creating a hidden anchor tag and triggering it's click event. Make sure your call to trigger the click event is included after the jQuery and Fancybox JS files are included. The code I used is as follows:
This sample script is embedded directly in the HTML, but it could also be included in a JS file.
<script type="text/javascript">
$(document).ready(function() {
$("#hidden_link").fancybox().trigger('click');
});
</script>
There's no legitimate way you can do it.
collection.ToList().ForEach(c => c.PropertyToSet = value);
As of Gradle 4.9 Application plugin understands --args
option, so passing the arguments is as simple as:
build.gradle
plugins {
id 'application'
}
mainClassName = "my.App"
src/main/java/my/App.java
public class App {
public static void main(String[] args) {
System.out.println(args);
}
}
bash
./gradlew run --args='This string will be passed into my.App#main arguments'
or in Windows, use double quotes:
gradlew run --args="This string will be passed into my.App#main arguments"
The whole point of Autotools is to provide an arcane M4-macro-based language which ultimately compiles to a shell script called ./configure
. You can ship this compiled shell script with the source code and that script should do everything to detect the environment and prepare the program for building. Autotools should only be required by someone who wants to tweak the tests and refresh that shell script.
It defeats the point of Autotools if GNU This and GNU That has to be installed on the system for it to work. Originally, it was invented to simplify the porting of programs to various Unix systems, which could not be counted on to have anything on them. Even the constructs used by the generated shell code in ./configure
had to be very carefully selected to make sure they would work on every broken old shell just about everywhere.
The problem you're running into is due to some broken Makefile steps invented by people who simply don't understand what Autotools is for and the role of the final ./configure
script.
As a workaround, you can go into the Makefile and make some changes to get this out of the way. As an example, I'm building the Git head of GNU Awk and running into this same problem. I applied this patch to Makefile.in
, however, and I can sucessfully make gawk
:
diff --git a/Makefile.in b/Makefile.in
index 5585046..b8b8588 100644
--- a/Makefile.in
+++ b/Makefile.in
@@ -312,12 +312,12 @@ distcleancheck_listfiles = find . -type f -print
# Directory for gawk's data files. Automake supplies datadir.
pkgdatadir = $(datadir)/awk
-ACLOCAL = @ACLOCAL@
+ACLOCAL = true
AMTAR = @AMTAR@
AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@
-AUTOCONF = @AUTOCONF@
-AUTOHEADER = @AUTOHEADER@
-AUTOMAKE = @AUTOMAKE@
+AUTOCONF = true
+AUTOHEADER = true
+AUTOMAKE = true
AWK = @AWK@
CC = @CC@
CCDEPMODE = @CCDEPMODE@
Basically, I changed things so that the harmless true
shell command is substituted for all the Auto-stuff programs.
The actual build steps for Gawk don't need the Auto-stuff! It's only involved in some rules that get invoked if parts of the Auto-stuff have changed and need to be re-processed. However, the Makefile is structured in such a way that it fails if the tools aren't present.
Before the above patch:
$ ./configure
[...]
$ make gawk
CDPATH="${ZSH_VERSION+.}:" && cd . && /bin/bash /home/kaz/gawk/missing aclocal-1.15 -I m4
/home/kaz/gawk/missing: line 81: aclocal-1.15: command not found
WARNING: 'aclocal-1.15' is missing on your system.
You should only need it if you modified 'acinclude.m4' or
'configure.ac' or m4 files included by 'configure.ac'.
The 'aclocal' program is part of the GNU Automake package:
<http://www.gnu.org/software/automake>
It also requires GNU Autoconf, GNU m4 and Perl in order to run:
<http://www.gnu.org/software/autoconf>
<http://www.gnu.org/software/m4/>
<http://www.perl.org/>
make: *** [aclocal.m4] Error 127
After the patch:
$ ./configure
[...]
$ make gawk
CDPATH="${ZSH_VERSION+.}:" && cd . && true -I m4
CDPATH="${ZSH_VERSION+.}:" && cd . && true
gcc -std=gnu99 -DDEFPATH='".:/usr/local/share/awk"' -DDEFLIBPATH="\"/usr/local/lib/gawk\"" -DSHLIBEXT="\"so"\" -DHAVE_CONFIG_H -DGAWK -DLOCALEDIR='"/usr/local/share/locale"' -I. -g -O2 -DNDEBUG -MT array.o -MD -MP -MF .deps/array.Tpo -c -o array.o array.c
[...]
gcc -std=gnu99 -g -O2 -DNDEBUG -Wl,-export-dynamic -o gawk array.o awkgram.o builtin.o cint_array.o command.o debug.o dfa.o eval.o ext.o field.o floatcomp.o gawkapi.o gawkmisc.o getopt.o getopt1.o int_array.o io.o main.o mpfr.o msg.o node.o profile.o random.o re.o regex.o replace.o str_array.o symbol.o version.o -ldl -lm
$ ./gawk --version
GNU Awk 4.1.60, API: 1.2
Copyright (C) 1989, 1991-2015 Free Software Foundation.
[...]
There we go. As you can see, the CDPATH=
command lines there are where the Auto-stuff was being invoked, where you see the true
commands. These report successful termination, and so it just falls through that junk to do the darned build, which is perfectly configured.
I did make gawk
because there are some subdirectories that get built which fail; the trick has to be repeated for their respective Makefiles.
If you're running into this kind of thing with a pristine, official tarball of the program from its developers, then complain. It should just unpack, ./configure
and make
without you having to patch anything or install any Automake or Autoconf materials.
Ideally, a pull of their Git head should also behave that way.
Don't use exit(0);
That's bad practice at the best of times. Use Yii::$app->end();
So your code would look like
$this->redirect(['index'], 302);
Yii::$app->end();
That said though the actual problem was stopping POST requests, this is the wrong solution to that problem (although it does work). To stop POST requests you need to use access control.
public function behaviors()
{
return [
'access' => [
'class' => \yii\filters\AccessControl::className(),
'only' => ['create', 'update'],
'rules' => [
// deny all POST requests
[
'allow' => false,
'verbs' => ['POST']
],
// allow authenticated users
[
'allow' => true,
'roles' => ['@'],
],
// everything else is denied
],
],
];
}
The difference can be demonstrated by this example:
generate a matrix
>>> A = numpy.matrix(numpy.ones((3,3)))
>>> A
matrix([[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.]])
use numpy.array
to modify A
. Doesn't work because you are modifying a copy
>>> numpy.array(A)[2]=2
>>> A
matrix([[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.]])
use numpy.asarray
to modify A
. It worked because you are modifying A
itself
>>> numpy.asarray(A)[2]=2
>>> A
matrix([[ 1., 1., 1.],
[ 1., 1., 1.],
[ 2., 2., 2.]])
Hope this helps!
Depending on what you want to achive, you are probably easiest calling the system ping command..
Using the subprocess module is the best way of doing this, although you have to remember the ping command is different on different operating systems!
import subprocess
host = "www.google.com"
ping = subprocess.Popen(
["ping", "-c", "4", host],
stdout = subprocess.PIPE,
stderr = subprocess.PIPE
)
out, error = ping.communicate()
print out
You don't need to worry about shell-escape characters. For example..
host = "google.com; `echo test`
..will not execute the echo command.
Now, to actually get the ping results, you could parse the out
variable. Example output:
round-trip min/avg/max/stddev = 248.139/249.474/250.530/0.896 ms
Example regex:
import re
matcher = re.compile("round-trip min/avg/max/stddev = (\d+.\d+)/(\d+.\d+)/(\d+.\d+)/(\d+.\d+)")
print matcher.search(out).groups()
# ('248.139', '249.474', '250.530', '0.896')
Again, remember the output will vary depending on operating system (and even the version of ping
). This isn't ideal, but it will work fine in many situations (where you know the machines the script will be running on)
As it turns out, my suspicions were right. The audience aud
claim in a JWT is meant to refer to the Resource Servers that should accept the token.
As this post simply puts it:
The audience of a token is the intended recipient of the token.
The audience value is a string -- typically, the base address of the resource being accessed, such as
https://contoso.com
.
The client_id
in OAuth refers to the client application that will be requesting resources from the Resource Server.
The Client app (e.g. your iOS app) will request a JWT from your Authentication Server. In doing so, it passes it's client_id
and client_secret
along with any user credentials that may be required. The Authorization Server validates the client using the client_id
and client_secret
and returns a JWT.
The JWT will contain an aud
claim that specifies which Resource Servers the JWT is valid for. If the aud
contains www.myfunwebapp.com
, but the client app tries to use the JWT on www.supersecretwebapp.com
, then access will be denied because that Resource Server will see that the JWT was not meant for it.
Very useful web-based tool written in PHP which makes it easy to search and replace text strings in a MySQL database.
Take a look at this blog post which has code for a simple chat app in Python/Django/gevent.
Yes, as said by Thanakron Tandavas,
Recursion is good when you are solving a problem that can be solved by divide and conquer technique.
For example: Towers of Hanoi
I believe that the Roots starter theme has a fantastic function to get the current page title. It is very hackable, covers all bases, and can be easily used with the wp_title
hook.
/**
* Page titles
*/
function roots_title() {
if (is_home()) {
if (get_option('page_for_posts', true)) {
echo get_the_title(get_option('page_for_posts', true));
} else {
_e('Latest Posts', 'roots');
}
} elseif (is_archive()) {
$term = get_term_by('slug', get_query_var('term'), get_query_var('taxonomy'));
if ($term) {
echo $term->name;
} elseif (is_post_type_archive()) {
echo get_queried_object()->labels->name;
} elseif (is_day()) {
printf(__('Daily Archives: %s', 'roots'), get_the_date());
} elseif (is_month()) {
printf(__('Monthly Archives: %s', 'roots'), get_the_date('F Y'));
} elseif (is_year()) {
printf(__('Yearly Archives: %s', 'roots'), get_the_date('Y'));
} elseif (is_author()) {
$author = get_queried_object();
printf(__('Author Archives: %s', 'roots'), $author->display_name);
} else {
single_cat_title();
}
} elseif (is_search()) {
printf(__('Search Results for %s', 'roots'), get_search_query());
} elseif (is_404()) {
_e('Not Found', 'roots');
} else {
the_title();
}
}
I just found the solution, kind of answering to my own question in case anyone else stumbles upon it.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://url/url/url" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, "body goes here" );
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/plain'));
$result=curl_exec ($ch);
<input type="file" @change="onFileChange" class="input upload-input" ref="inputFile"/>
onFileChange(e) {
//upload file and then delete it from input
self.$refs.inputFile.value = ''
}
If you just want to drop the database no matter what (but please first read the whole post: the error was given for a reason, and it might be important to know what the reason was!), you can:
SHOW VARIABLES WHERE Variable_name LIKE '%datadir%';
service mysql stop
or rcmysqld stop
or similar on Linux, NET STOP <name of MYSQL service, often MYSQL57 or similar>
or through SERVICES.MSC
on Windows)MySQL has no write permission on the parent directory in which the mydb
folder resides.
Check it with
ls -la /path/to/data/dir/ # see below on how to discover data dir
ls -la /path/to/data/dir/mydb
On Linux, this can also happen if you mix and match MySQL and AppArmor/SELinux packages. What happens is that AppArmor expects mysqld to have its data in /path/to/data/dir
, and allows full R/W there, but MySQLd is from a different distribution or build, and it actually stores its data elsewhere (e.g.: /var/lib/mysql5/data/**
as opposed to /var/lib/mysql/**
). So what you see is that the directory has correct permissions and ownership and yet it still gives Errno 13 because apparmor/selinux won't allow access to it.
To verify, check the system log for security violations, manually inspect apparmor/selinux configuration, and/or impersonate the mysql user and try going to the base var directory, then cd incrementally until you're in the target directory, and run something like touch aardvark && rm aardvark
. If permissions and ownership match, and yet the above yields an access error, chances are that it's a security framework issue.
"EASY FIX" considered harmful
I have happened upon an "easy fix" suggested on a "experts forum" (not Stack Overflow, thank goodness), the same "fix" I sometimes find for Web and FTP problems --
chown 777
. PLEASE NEVER DO THAT. For those who don't already know, 777 (or 775, or 666) isn't a magic number that somehow MySQL programmers forgot to apply themselves, or don't want you to know. Each digit has a meaning, and 777 means "I hereby consent to everyone doing whatever they want with my stuff, up to and including executing it as if it were a binary or shell script". By doing this (and chances are you won't be allowed to do this on a sanely configured system),
- you risk several security conscious programs to refuse to function anymore (e.g. if you do that to your SSH keys, goodbye SSH connections; etc.) since they realize they're now in a insecure context.
- you allow literally everyone with any level of access whatsoever to the system to read and write your data, whether MySQL allows it or not, unbeknownst to MySQL itself - i.e. it becomes possible to silently corrupt whole databases.
- the above might sometimes be done, in exceedingly dire straits, by desperate and knowledgeable people, to gain access again to an otherwise inaccessible screwed MySQL installation (i.e. even
mysqladmin
no longer grants local access), and will be immediately undone as soon as things get back to normal - it's not a permanent change, not even then. And it's not a fix to "one weird trick to be able to drop my DB".(needless to say, it's almost never the real fix to any Web or FTP problems either. The fix to "Of late, the wife's keys fail to open the front door and she can't enter our home" is 'check the keys or have the lock repaired or replaced'; the admittedly much quicker
chown 777
is "Just leave the front door wide open! Easy peasy! What's the worst that might happen?")
This code means "directory not empty". The directory contains some hidden files MySQL knows nothing about. For non-hidden files, see Errno 17. The solution is the same.
This code means "file exists". The directory contains some MySQL file that MySQL doesn't feel about deleting. Such files could have been created by a SELECT ... INTO OUTFILE "filename";
command where filename
had no path. In this case, the MySQL process creates them in its current working directory, which (tested on MySQL 5.6 on OpenSuSE 12.3) is the data directory of the database, e.g. /var/lib/mysql/data/nameofdatabase
.
Reproducibility:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1676
Server version: 5.6.12-log openSUSE package
[ snip ]
mysql> CREATE DATABASE pippo;
Query OK, 1 row affected (0.00 sec)
mysql> USE pippo;
Database changed
mysql> SELECT version() INTO OUTFILE 'test';
Query OK, 1 row affected (0.00 sec)
mysql> DROP DATABASE pippo;
ERROR 1010 (HY000): Error dropping database (can't rmdir './pippo/', errno: 17)
-- now from another console I delete the "test" file, without closing this connection
-- and just retry. Now it works.
mysql> DROP DATABASE pippo;
Query OK, 0 rows affected (0.00 sec)
Move the file(s) outside (or delete if not needed) and retry. Also, determine why they were created in the first place - it could point to a bug in some application. Or worse: see below...
This happened on a Linux system with Wordpress installed. Unfortunately the customer was under time constraints and I could neither image the disk or do a real forensics round - I reinstalled the whole machine and Wordpress got updated in the process, so I can only say that I'm almost certain they did it through this plugin.
Symptoms: the mysql
data directory contained three files with extension PHP. Wait, what?!? -- and inside the files there was a bulk of base64 code which was passed to base64_decode
, gzuncompress
and [eval()][2]
. Aha. Of course these were only the first attempts, the unsuccessful ones. The site had been well and truly pwn3d.
So if you find a file in your mysql data dir that's causing an Error 17, check it with file
utility or scan it with an antivirus. Or visually inspect its contents. Do not assume it's there for some innocuous mistake.
(Needless to say, to visually inspect the file, never double click it).
The victim in this case (he had some friend "do the maintenance") would never have guessed he'd been hacked until a maintenance/update/whatever script ran a DROP DATABASE
(do not ask me why - I'm not sure even I want to know) and got an error. From the CPU load and the syslog messages, I'm fairly positive that the host had become a spam farm.
If you rsync
or copy between two MySQL installations of the same version but different platform or file systems such as Linux or Windows (which is discouraged, and risky, but many do it nonetheless), and specifically with different case sensitivity settings, you can accidentally end up with two versions of the same file (either data, index, or metadata); say Customers.myi
and Customer.MYI
. MySQL uses one of them and knows nothing about the other (which could be out of date and lead to a disastrous sync). When dropping the database, which also happens in many a mysqldump ... | ... mysql
backup schemes, the DROP
will fail because that extra file (or those extra files) exists. If this happens, you should be able to recognize the obsolete file(s) that need manual deletion from the file time, or from the fact that their case scheme is different from the majority of the other tables.
In general, you can find the data directory by inspecting the my.cnf
file (/etc/my.cnf
, /etc/sysconfig/my.cnf
, /etc/mysql/my.cnf
on Linux; my.ini
in the MySQL program files directory in Windows), under the [mysqld]
heading, as datadir
.
Alternatively you can ask it to MySQL itself:
mysql> SHOW VARIABLES WHERE Variable_name LIKE '%datadir%';
+---------------+-----------------+
| Variable_name | Value |
+---------------+-----------------+
| datadir | /var/lib/mysql/ |
+---------------+-----------------+
1 row in set (0.00 sec)
A tool to use here is awk:
cat file | awk 'BEGIN{ found=0} /TERMINATE/{found=1} {if (found) print }'
How does this work:
The other solutions might consume a lot of memory if you use them on very large files.
One reason to choose .keystore over .jks is that Unity recognizes the former but not the latter when you're navigating to select your keystore file (Unity 2017.3, macOS).
CPython (the classic and prevalent implementation of Python) can't have more than one thread executing Python bytecode at the same time. This means compute-bound programs will only use one core. I/O operations and computing happening inside C extensions (such as numpy) can operate simultaneously.
Other implementation of Python (such as Jython or PyPy) may behave differently, I'm less clear on their details.
The usual recommendation is to use many processes rather than many threads.
I think using the matrix.at<type>(x,y)
is not the best way to iterate trough a Mat object!
If I recall correctly matrix.at<type>(x,y)
will iterate from the beginning of the matrix each time you call it(I might be wrong though).
I would suggest using cv::MatIterator_
cv::Mat someMat(1, 4, CV_64F, &someData);;
cv::MatIterator_<double> _it = someMat.begin<double>();
for(;_it!=someMat.end<double>(); _it++){
std::cout << *_it << std::endl;
}
Try to use:
pattern="(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/\d{4}"
Another Solution in Case You Don't Have Control Over Dynamic Content
This works if you didn't load your element through a directive (ie. like in the example in the commented jsfiddles).
Wrap up Your Content
Wrap your content in a div so that you can select it if you are using JQuery. You an also opt to use native javascript to get your element.
<div class="selector">
<grid-filter columnname="LastNameFirstName" gridname="HomeGrid"></grid-filter>
</div>
Use Angular Injector
You can use the following code to get a reference to $compile if you don't have one.
$(".selector").each(function () {
var content = $(this);
angular.element(document).injector().invoke(function($compile) {
var scope = angular.element(content).scope();
$compile(content)(scope);
});
});
Summary
The original post seemed to assume you had a $compile reference handy. It is obviously easy when you have the reference, but I didn't so this was the answer for me.
One Caveat of the previous code
If you are using a asp.net/mvc bundle with minify scenario you will get in trouble when you deploy in release mode. The trouble comes in the form of Uncaught Error: [$injector:unpr] which is caused by the minifier messing with the angular javascript code.
Here is the way to remedy it:
Replace the prevous code snippet with the following overload.
...
angular.element(document).injector().invoke(
[
"$compile", function($compile) {
var scope = angular.element(content).scope();
$compile(content)(scope);
}
]);
...
This caused a lot of grief for me before I pieced it together.
Here is my version which adds the tcp port in case it's not 80 or 443:
function url(s) {
var l = window.location;
return ((l.protocol === "https:") ? "wss://" : "ws://") + l.hostname + (((l.port != 80) && (l.port != 443)) ? ":" + l.port : "") + l.pathname + s;
}
Edit 1: Improved version as by suggestion of @kanaka :
function url(s) {
var l = window.location;
return ((l.protocol === "https:") ? "wss://" : "ws://") + l.host + l.pathname + s;
}
Edit 2: Nowadays I create the WebSocket
this:
var s = new WebSocket(((window.location.protocol === "https:") ? "wss://" : "ws://") + window.location.host + "/ws");
In my experiment, Java abstract class does need to specify abstract keyword. Reversely, error that "abstract modifier cannot be put here" will be prompted. You can specify abstract attributes just like ordinary attributes.
public abstract class Duck implements Quackable, Observable {
// observerList should keep the list of observers watching this duck
List<Observer> observerList;
public AttackBehavior attackBehavior;
public FlyBehavior flyBehavior;
public Duck() {
observerList = new ArrayList<Observer>();
}
}
And in subclass, you can directly use these attributes this.flyBehavior
or this.attackBehavior
. You don't need to rewrite the attributes in attribute field.
For those who are trying to find how to enable debugging on devices running Jelly Bean 4.2 (e.g Google Nexus), you have to go to Settings > Apps > About tablet and tap the text "Build number" 7 times slowly. Go back to the now available Settings > Developer options and check USB debugging as stated in previous posts.
I use the following syntax :
$Domain=[System.Net.Dns]::GetHostByName($VM).Hostname.split('.')
$Domain=$Domain[1]+'.'+$Domain[2]
it does not matter if the $VM is up or down...
You can use sudo ip link delete
to remove the interface.
I was cleaning up warnings and messages and see that VS does warn about it: Validation (ASP.Net): Attribute 'OnClick' is not a valid attribute of element 'CheckBox'. Use the html input control to specify a client side handler and then you won't get the extra span tag and the two elements.
Slight modification on @JRodd version to support objects coming from Json (JObject)
public static dynamic ToDynamic(this object value)
{
IDictionary<string, object> expando = new ExpandoObject();
//Get the type of object
Type t = value.GetType();
//If is Dynamic Expando object
if (t.Equals(typeof(ExpandoObject)))
{
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(value.GetType()))
expando.Add(property.Name, property.GetValue(value));
}
//If coming from Json object
else if (t.Equals(typeof(JObject)))
{
foreach (JProperty property in (JToken)value)
expando.Add(property.Name, property.Value);
}
else //Try converting a regular object
{
string str = JsonConvert.SerializeObject(value);
ExpandoObject obj = JsonConvert.DeserializeObject<ExpandoObject>(str);
return obj;
}
return expando as ExpandoObject;
}
Just go to your app/storage/logs
there logs of error
available. Go to filename of today's date time and you will find latest error
in your application.
OR
Open app/config/app.php
and change setting
'debug' => false,
To
'debug' => true,
OR
Go to .env
file to your application and change the configuratuion
APP_LOG_LEVEL=debug
Enabling multidex
is not a good solution because multidex
have another usage in android see this answer what is multidex
The solution is disabling instant run as @Shylendra Madda said
Settings ? Build, Execution, Deployment ? Instant Run and uncheck Enable Instant Run
I think the reason of this problem is when instant run is enabled, Android Studio don't put libraries such as firebase
into generated apk to decreasing project build time because firebase
library and other libraries such as maps
and others is exist in play services and play services is installed on android device so if instant run enabled don't need to put them in generated apk to make build time faster.
So when you extract apk and install it on another device you will see this exception
I have always found the distinction between unsupervised and supervised learning to be arbitrary and a little confusing. There is no real distinction between the two cases, instead there is a range of situations in which an algorithm can have more or less 'supervision'. The existence of semi-supervised learning is an obvious examples where the line is blurred.
I tend to think of supervision as giving feedback to the algorithm about what solutions should be preferred. For a traditional supervised setting, such as spam detection, you tell the algorithm "don't make any mistakes on the training set"; for a traditional unsupervised setting, such as clustering, you tell the algorithm "points that are close to each other should be in the same cluster". It just so happens that, the first form of feedback is a lot more specific than the latter.
In short, when someone says 'supervised', think classification, when they say 'unsupervised' think clustering and try not to worry too much about it beyond that.
The same as in Eli's answer - just using a shorter form, because you can skip a lambda
part here.
Creating new list:
>>> xs = ['dddd','a','bb','ccc']
>>> sorted(xs, key=len)
['a', 'bb', 'ccc', 'dddd']
In-place sorting:
>>> xs.sort(key=len)
>>> xs
['a', 'bb', 'ccc', 'dddd']
Use pandas:
import pandas as pd
my_csv = pd.read_csv(filename)
column = my_csv.column_name
# you can also use my_csv['column_name']
Discard unneeded columns at parse time:
my_filtered_csv = pd.read_csv(filename, usecols=['col1', 'col3', 'col7'])
P.S. I'm just aggregating what other's have said in a simple manner. Actual answers are taken from here and here.
I used an extension to UIViewController and a struct to make sure that my current view is presented from the favourites
1.Struct for a global Bool
struct PresentedFromFavourites {
static var comingFromFav = false}
2.UIVeiwController extension: presented modally as in the second option by "stefandouganhyde - Option 2 " and solving the back
extension UIViewController {
func returnToFavourites()
{
// you return to the storyboard wanted by changing the name
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let mainNavigationController = storyBoard.instantiateViewController(withIdentifier: "HomeNav") as! UINavigationController
// Set animated to false
let favViewController = storyBoard.instantiateViewController(withIdentifier: "Favourites")
self.present(mainNavigationController, animated: false, completion: {
mainNavigationController.pushViewController(favViewController, animated: false)
})
}
// call this function in viewDidLoad()
//
func addBackToFavouritesButton()
{
if PresentedFromFavourites.comingFromFav
{
//Create a button
// I found this good for most size classes
let buttonHeight = (self.navigationController?.navigationBar.frame.size.height)! - 15
let rect = CGRect(x: 2, y: 8, width: buttonHeight, height: buttonHeight)
let aButton = UIButton(frame: rect)
// Down a back arrow image from icon8 for free and add it to your image assets
aButton.setImage(#imageLiteral(resourceName: "backArrow"), for: .normal)
aButton.backgroundColor = UIColor.clear
aButton.addTarget(self, action:#selector(self.returnToFavourites), for: .touchUpInside)
self.navigationController?.navigationBar.addSubview(aButton)
PresentedFromFavourites.comingFromFav = false
}
}}
Please to solve this problem we just have set installed JDK path in
standalone.conf
file which under the bin folder of JBoss\Wildfly Server. To solve this we do the following steps:
Charles Bailey's answer is correct. The exact wording from the C++ standard is (§4.7/4): "If the source type is bool, the value false is converted to zero and the value true is converted to one."
Edit: I see he's added the reference as well -- I'll delete this shortly, if I don't get distracted and forget...
Edit2: Then again, it is probably worth noting that while the Boolean values themselves always convert to zero or one, a number of functions (especially from the C standard library) return values that are "basically Boolean", but represented as int
s that are normally only required to be zero to indicate false or non-zero to indicate true. For example, the is* functions in <ctype.h>
only require zero or non-zero, not necessarily zero or one.
If you cast that to bool
, zero will convert to false, and non-zero to true (as you'd expect).
extension Date {
func daysFromToday() -> Int {
return Calendar.current.dateComponents([.day], from: self, to: Date()).day!
}
}
Then use it like
func dayCount(dateString: String) -> String{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM dd,yyyy hh:mm a"
let fetchedDate = dateFormatter.date(from: dateString)
let day = fetchedDate?.daysFromToday()
if day! > -1{
return "\(day!) days passed."
}else{
return "\(day! * -1) days left."
}
}
You should read up on the onclick
html attribute and the window.open()
documentation. Below is what you want.
<a href='#' onclick='window.open("http://www.google.com", "myWin", "scrollbars=yes,width=400,height=650"); return false;'>1</a>
_x000D_
JSFiddle: http://jsfiddle.net/TBcVN/
You can also use the computeIfAbsent()
method in the HashMap
class.
In the following example, map
stores a list of transactions (integers) that are applied to the key (the name of the bank account). To add 2 transactions of 100
and 200
to checking_account
you can write:
HashMap<String, ArrayList<Integer>> map = new HashMap<>();
map.computeIfAbsent("checking_account", key -> new ArrayList<>())
.add(100)
.add(200);
This way you don't have to check to see if the key checking_account
exists or not.
computeIfAbsent()
. Really elegant!
Assaf's response of
Depends on how much money you got...
sounds flippant, but actually it's pertinant.
Only today we had an issue where a record failed to be inserted into our Rate table, because one of the columns (GrossRate) is set to Decimal (11,4), and our Product department just got a contract for rooms in some amazing resort in Bora Bora, that sell for several million Pacific Francs per night... something that was never anticpated when the database schema was designed 10 years ago.
In Access VBA I've used this to turn off all the dialogs when running a bunch of updates:
DoCmd.SetWarnings False
After running all the updates, the last step in my VBA script is:
DoCmd.SetWarnings True
Hope this helps.
This should work for all browsers/devices:
function getActualWidth()
{
var actualWidth = window.innerWidth ||
document.documentElement.clientWidth ||
document.body.clientWidth ||
document.body.offsetWidth;
return actualWidth;
}
When I do this, I like to have some control over the details of how the table is formatted. In particular, I want header cells to have a different format than body cells, and the table column widths to only be as wide as each one needs to be. Here's my solution:
def format_matrix(header, matrix,
top_format, left_format, cell_format, row_delim, col_delim):
table = [[''] + header] + [[name] + row for name, row in zip(header, matrix)]
table_format = [['{:^{}}'] + len(header) * [top_format]] \
+ len(matrix) * [[left_format] + len(header) * [cell_format]]
col_widths = [max(
len(format.format(cell, 0))
for format, cell in zip(col_format, col))
for col_format, col in zip(zip(*table_format), zip(*table))]
return row_delim.join(
col_delim.join(
format.format(cell, width)
for format, cell, width in zip(row_format, row, col_widths))
for row_format, row in zip(table_format, table))
print format_matrix(['Man Utd', 'Man City', 'T Hotspur', 'Really Long Column'],
[[1, 2, 1, -1], [0, 1, 0, 5], [2, 4, 2, 2], [0, 1, 0, 6]],
'{:^{}}', '{:<{}}', '{:>{}.3f}', '\n', ' | ')
Here's the output:
| Man Utd | Man City | T Hotspur | Really Long Column
Man Utd | 1.000 | 2.000 | 1.000 | -1.000
Man City | 0.000 | 1.000 | 0.000 | 5.000
T Hotspur | 2.000 | 4.000 | 2.000 | 2.000
Really Long Column | 0.000 | 1.000 | 0.000 | 6.000
best way to format JSON data is like this!
header('Content-type: application/json; charset=UTF-8');
echo json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
Replace $response with your Data which is required to be converted to JSON
This may answer your question:
select cast(xmlField as xml) xmlField into tmp from (
select '<person><firstName>Jon</firstName><lastName>Johnson</lastName></person>' xmlField
union select '<person><firstName>Kathy</firstName><lastName>Carter</lastName></person>'
union select '<person><firstName>Bob</firstName><lastName>Burns</lastName></person>'
) tb
SELECT
xmlField.value('(person/firstName)[1]', 'nvarchar(max)') as FirstName
,xmlField.value('(person/lastName)[1]', 'nvarchar(max)') as LastName
FROM tmp
drop table tmp
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
The 100% correct answer for the default location of the log files is...
%SystemDrive%\inetpub\logs\LogFiles
Yes you can enter this into the explorer address bar it'll work.
To be 100% sure, you need to look at the logging for the web site in IIS.
https://docs.microsoft.com/en-us/iis/get-started/whats-new-in-iis-85/enhanced-logging-for-iis85
i.e.
EDIT: As pointed out by Andy in the comments below you need to ensure when installing IIS that you elected to enable HTTP logging, otherwise HTTP logging won't be available.
If everything is right, but this mistake is present, it need check next section in ****.vcxproj file:
<ClCompile Include="stdafx.cpp">
<PrecompiledHeader Condition=
In my case it there was an incorrect name of a configuration: only first word.
On version 4.4.1, you can use:
npm config set @myco:registry=http://reg.example.com
Where @myco is your package scope. You can install package in this way:
npm install @myco/my-package
Define your own parse format string to use.
string formatString = "yyyyMMddHHmmss";
string sample = "20100611221912";
DateTime dt = DateTime.ParseExact(sample,formatString,null);
In case you got a datetime having milliseconds, use the following formatString
string format = "yyyyMMddHHmmssfff"
string dateTime = "20140123205803252";
DateTime.ParseExact(dateTime ,format,CultureInfo.InvariantCulture);
Thanks
Am adding this answer for the purpose of those who google about this..
There was an episode of DevBytes (ListView Cell Dragging and Rearranging) recently which explains how to do this
You can find it here also the sample code is available here.
What this code basically does is that it creates a dynamic listview
by the extension of listview
that supports cell dragging and swapping. So that you can use the DynamicListView
instead of your basic ListView
and that's it you have implemented a ListView with Drag and Drop.
#/bin/bash
TESTSTR="abc,def,ghij"
for i in $(echo $TESTSTR | tr ',' '\n')
do
echo $i
done
I prefer to use tr instead of sed, becouse sed have problems with special chars like \r \n in some cases.
other solution is to set IFS to certain separator
we can use the below to get key as string from JSON OBJECT
JsonObject json = new JsonObject();
json.get("key").getAsString();
this gives the string without double quotes " "
in the string
You can create the headers on the fly (no need to specify delimiter when the delimiter is a comma):
Import-CSV $filepath -Header IP1,IP2,IP3,IP4 | Foreach-Object{
Write-Host $_.IP1
Write-Host $_.IP2
...
}
You can handle click on list view item like this:
<ListView.ItemTemplate>
<DataTemplate>
<Button BorderBrush="Transparent" Background="Transparent" Focusable="False">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<i:InvokeCommandAction Command="{Binding DataContext.MyCommand, ElementName=ListViewName}" CommandParameter="{Binding}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<Button.Template>
<ControlTemplate>
<Grid VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
...
See the documentation on MDN about expressions and operators and statements.
this
keyword:var x = function()
vs. function x()
— Function declaration syntax(function(){
…})()
— IIFE (Immediately Invoked Function Expression)(function(){…})();
work but function(){…}();
doesn't?(function(){…})();
vs (function(){…}());
!function(){…}();
- What does the exclamation mark do before the function?+function(){…}();
- JavaScript plus sign in front of function expression!
vs leading semicolon(function(window, undefined){…}(window));
someFunction()()
— Functions which return other functions=>
— Equal sign, greater than: arrow function expression syntax|>
— Pipe, greater than: Pipeline operatorfunction*
, yield
, yield*
— Star after function
or yield
: generator functions[]
, Array()
— Square brackets: array notationIf the square brackets appear on the left side of an assignment ([a] = ...
), or inside a function's parameters, it's a destructuring assignment.
{key: value}
— Curly brackets: object literal syntax (not to be confused with blocks)If the curly brackets appear on the left side of an assignment ({ a } = ...
) or inside a function's parameters, it's a destructuring assignment.
`
…${
…}
…`
— Backticks, dollar sign with curly brackets: template literals`…${…}…`
code from the node docs mean?/
…/
— Slashes: regular expression literals$
— Dollar sign in regex replace patterns: $$
, $&
, $`
, $'
, $n
()
— Parentheses: grouping operatorobj.prop
, obj[prop]
, obj["prop"]
— Square brackets or dot: property accessors?.
, ?.[]
, ?.()
— Question mark, dot: optional chaining operator::
— Double colon: bind operatornew
operator...iter
— Three dots: spread syntax; rest parameters(...args) => {}
— What is the meaning of “…args” (three dots) in a function definition?[...iter]
— javascript es6 array feature […data, 0] “spread operator”{...props}
— Javascript Property with three dots (…)++
, --
— Double plus or minus: pre- / post-increment / -decrement operatorsdelete
operatorvoid
operator+
, -
— Plus and minus: addition or concatenation, and subtraction operators; unary sign operators|
, &
, ^
, ~
— Single pipe, ampersand, circumflex, tilde: bitwise OR, AND, XOR, & NOT operators~1
equal -2
?%
— Percent sign: remainder operator&&
, ||
, !
— Double ampersand, double pipe, exclamation point: logical operators??
— Double question mark: nullish-coalescing operator**
— Double star: power operator (exponentiation)x ** 2
is equivalent to Math.pow(x, 2)
==
, ===
— Equal signs: equality operators!=
, !==
— Exclamation point and equal signs: inequality operators<<
, >>
, >>>
— Two or three angle brackets: bit shift operators?
…:
… — Question mark and colon: conditional (ternary) operator=
— Equal sign: assignment operator%=
— Percent equals: remainder assignment+=
— Plus equals: addition assignment operator&&=
, ||=
, ??=
— Double ampersand, pipe, or question mark, followed by equal sign: logical assignments||=
(or equals) in JavaScript?,
— Comma operator{
…}
— Curly brackets: blocks (not to be confused with object literal syntax)var
, let
, const
— Declaring variableslabel:
— Colon: labels#
— Hash (number sign): Private methods or private fieldsTry adding 2 spaces (or a backslash \
) after the first line:
[Name of link](url)
My line of text\
Visually:
[Name of link](url)<space><space>
My line of text\
Output:
<p><a href="url">Name of link</a><br>
My line of text<br></p>
Yes, but in what file is pyth_test
's definition declared in? Is it also located before it's called?
Edit:
To put it into perspective, create a file called test.py
with the following contents:
def pyth_test (x1, x2):
print x1 + x2
pyth_test(1,2)
Now run the following command:
python test.py
You should see the output you desire. Now if you are in an interactive session, it should go like this:
>>> def pyth_test (x1, x2):
... print x1 + x2
...
>>> pyth_test(1,2)
3
>>>
I hope this explains how the declaration works.
To give you an idea of how the layout works, we'll create a few files. Create a new empty folder to keep things clean with the following:
myfunction.py
def pyth_test (x1, x2):
print x1 + x2
program.py
#!/usr/bin/python
# Our function is pulled in here
from myfunction import pyth_test
pyth_test(1,2)
Now if you run:
python program.py
It will print out 3. Now to explain what went wrong, let's modify our program this way:
# Python: Huh? where's pyth_test?
# You say it's down there, but I haven't gotten there yet!
pyth_test(1,2)
# Our function is pulled in here
from myfunction import pyth_test
Now let's see what happens:
$ python program.py
Traceback (most recent call last):
File "program.py", line 3, in <module>
pyth_test(1,2)
NameError: name 'pyth_test' is not defined
As noted, python cannot find the module for the reasons outlined above. For that reason, you should keep your declarations at top.
Now then, if we run the interactive python session:
>>> from myfunction import pyth_test
>>> pyth_test(1,2)
3
The same process applies. Now, package importing isn't all that simple, so I recommend you look into how modules work with Python. I hope this helps and good luck with your learnings!
Conclusion Maximum z-index value is 2,147,483,647 and more than this convert to 2,147,483,647
?Browser | Maximum | More Than Maximum |
---|---|---|
Chrome >= 29 | 2,147,483,647 | 2,147,483,647 |
Opera >= 9 | 2,147,483,647 | 2,147,483,647 |
IE >= 6 | 2,147,483,647 | 2,147,483,647 |
Safari >= 4 | 2,147,483,647 | 2,147,483,647 |
Safari = 3 | 16,777,271 | 16,777,271 |
Firefox >= 4 | 2,147,483,647 | 2,147,483,647 |
Firefox = 3 | 2,147,483,647 | 0 |
Firefox = 2 | 2,147,483,647 | Bug: tag hidden |
All Values tested in BrowserStack.
pylab
, not matplotlib.pyplot
You may try using hist
to put your data info along with the fitted curve as below:
import numpy as np
import scipy.stats as stats
import pylab as pl
h = sorted([186, 176, 158, 180, 186, 168, 168, 164, 178, 170, 189, 195, 172,
187, 180, 186, 185, 168, 179, 178, 183, 179, 170, 175, 186, 159,
161, 178, 175, 185, 175, 162, 173, 172, 177, 175, 172, 177, 180]) #sorted
fit = stats.norm.pdf(h, np.mean(h), np.std(h)) #this is a fitting indeed
pl.plot(h,fit,'-o')
pl.hist(h,normed=True) #use this to draw histogram of your data
pl.show() #use may also need add this
J.F. Sebastian's answer is most elegant but requires python 2.6 as fortran pointed out.
For Python version < 2.6, here's the best I can come up with:
from itertools import repeat,ifilter,chain
chain(ifilter(predicate,seq),repeat(None)).next()
Alternatively if you needed a list later (list handles the StopIteration), or you needed more than just the first but still not all, you can do it with islice:
from itertools import islice,ifilter
list(islice(ifilter(predicate,seq),1))
UPDATE: Although I am personally using a predefined function called first() that catches a StopIteration and returns None, Here's a possible improvement over the above example: avoid using filter / ifilter:
from itertools import islice,chain
chain((x for x in seq if predicate(x)),repeat(None)).next()
Just add target="_blank"
to the
<a mat-raised-button target="_blank" [routerLink]="['/find-post/post', post.postID]"
class="theme-btn bg-grey white-text mx-2 mb-2">
Open in New Window
</a>
Thanks to Renato answer, I have created a really basic example:
const exec = require('child_process').exec
exec('git config --global user.name', (err, stdout, stderr) => console.log(stdout))
It will just print your global git username :)
And another way:
<a href="javascript:history.back()">Go Back</a>
_x000D_
You don't want to do that. It can cause undefined behavior depending on the collection. You want to use an Iterator directly. Although the for each construct is syntactic sugar and is really using an iterator, it hides it from your code so you can't access it to call Iterator.remove
.
The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.
Instead write your code:
List<String> names = ....
Iterator<String> it = names.iterator();
while (it.hasNext()) {
String name = it.next();
// Do something
it.remove();
}
Note that the code calls Iterator.remove
, not List.remove
.
Addendum:
Even if you are removing an element that has not been iterated over yet, you still don't want to modify the collection and then use the Iterator
. It might modify the collection in a way that is surprising and affects future operations on the Iterator
.
The easiest way to disable this is uncheck the warnings in the chrome dev tools
Hope this helps.
Boost contains cstdint.hpp header file with the types you are looking for: http://www.boost.org/doc/libs/1_36_0/boost/cstdint.hpp
Why not try find /usr/include/X11 -name Xlib.h
If there is a hit, you have Xlib.h
If not install it using sudo apt-get install libx11-dev
and you are good to go :)
You have the syntax wrong; there is no need to place a period inside a double-quoted string. Instead, it should be more like
$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$prefix%'");
You can confirm this by printing out the string to see that it turns out identical to the first case.
Of course it's not a good idea to simply inject variables into the query string like this because of the danger of SQL injection. At the very least you should manually escape the contents of the variable with mysql_real_escape_string
, which would make it look perhaps like this:
$sql = sprintf("SELECT * FROM table WHERE the_number LIKE '%s%%'",
mysql_real_escape_string($prefix));
$query = mysql_query($sql);
Note that inside the first argument of sprintf
the percent sign needs to be doubled to end up appearing once in the result.
Here a code that works with windows office 2010. This script will ask you for input filtered range of cells and then the paste range.
Please, both ranges should have the same number of cells.
Sub Copy_Filtered_Cells()
Dim from As Variant
Dim too As Variant
Dim thing As Variant
Dim cell As Range
'Selection.SpecialCells(xlCellTypeVisible).Select
'Set from = Selection.SpecialCells(xlCellTypeVisible)
Set temp = Application.InputBox("Copy Range :", Type:=8)
Set from = temp.SpecialCells(xlCellTypeVisible)
Set too = Application.InputBox("Select Paste range selected cells ( Visible cells only)", Type:=8)
For Each cell In from
cell.Copy
For Each thing In too
If thing.EntireRow.RowHeight > 0 Then
thing.PasteSpecial
Set too = thing.Offset(1).Resize(too.Rows.Count)
Exit For
End If
Next
Next
End Sub
Enjoy!
Adding dependencies didn't fix the issue at my end.
The issue was happening at my end because of "additional" fields that are part of the "@Entity" class and don't exist in the database.
I removed the additional fields from the @Entity class and it worked.
dt
- your data table name
ColumnName
- your columnname i.e id
DataView view = new DataView(dt);
DataTable distinctValues = new DataTable();
distinctValues = view.ToTable(true, ColumnName);
Zend framework
public function verifyTablesExists($tablesName)
{
$db = $this->getDefaultAdapter();
$config_db = $db->getConfig();
$sql = "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '{$config_db['dbname']}' AND table_name = '{$tablesName}'";
$result = $db->fetchRow($sql);
return $result;
}
SUPER KEY:
Attribute or set of attributes used to uniquely identify tuples in the database.
CANDIDATE KEY:
PRIMARY KEY:
one of the candidate key which is used to identify records in DB uniquely
not null
As the answer said above, CSS PIE makes things like border-radius and box-shadow work in IE6-IE8: http://css3pie.com/
That said I have still found things to be somewhat flaky when using PIE and now just accept that people using older browsers aren't going to see rounded corners and dropshadows.
Given a branch foo
and a remote upstream
:
As of Git 1.8.0:
git branch -u upstream/foo
Or, if local branch foo
is not the current branch:
git branch -u upstream/foo foo
Or, if you like to type longer commands, these are equivalent to the above two:
git branch --set-upstream-to=upstream/foo
git branch --set-upstream-to=upstream/foo foo
As of Git 1.7.0 (before 1.8.0):
git branch --set-upstream foo upstream/foo
Notes:
foo
to track remote branch foo
from remote upstream
.git fetch upstream
beforehand.See also: Why do I need to do `--set-upstream` all the time?
Windows XP has the Windows Firewall which can interfere with network traffic if not configured properly. You can turn off the Windows Firewall, if you have administrator privileges, by accessing the Windows Firewall applet through the Control Panel. If your application works with the Windows Firewall turned off then the problem is probably due to the settings of the firewall.
We have an application which runs on multiple PCs communicating using UDP/IP and we have been doing experiments so that the application can run on a PC with a user who does not have administrator privileges. In order for our application to communicate between multiple PCs we have had to use an administrator account to modify the Windows Firewall settings.
In our application, one PC is designated as the server and the others are clients in a server/client group and there may be several groups on the same subnet.
The first change was to use the functionality of the Exceptions tab of the Windows Firewall applet to create an exception for the port that we use for communication.
We are using host name lookup so that the clients can locate their assigned server by using the computer name which is composed of a mnemonic prefix with a dash followed by an assigned terminal number (for instance SERVER100-1). This allows several servers with their assigned clients to coexist on the same subnet. The client uses its prefix to generate the computer name for the assigned server and to then use host name lookup to discover the IP address of the assigned server.
What we found is that the host name lookup using the computer name (assigned through the Computer Name tab of the System Properties dialog) would not work unless the server PC's Windows Firewall had the File and Printer Sharing Service port enabled.
So we had to make two changes: (1) setup an exception for the port we used for communication and (2) enable File and Printer Service in the Exceptions tab to allow for the host name lookup.
** EDIT **
You may also find this Microsoft Knowledge Base article on helpful on Windows XP networking.
And see this article on NETBIOS name resolution in Windows.
You can use move when you need to "transfer" the content of an object somewhere else, without doing a copy (i.e. the content is not duplicated, that's why it could be used on some non-copyable objects, like a unique_ptr). It's also possible for an object to take the content of a temporary object without doing a copy (and save a lot of time), with std::move.
This link really helped me out :
http://thbecker.net/articles/rvalue_references/section_01.html
I'm sorry if my answer is coming too late, but I was also looking for a good link for the std::move, and I found the links above a little bit "austere".
This puts the emphasis on r-value reference, in which context you should use them, and I think it's more detailed, that's why I wanted to share this link here.
I have similar issue faced and solve with following solution: my date format is: 'Fri Dec 11 2020 05:00:00 GMT+0500 (Pakistan Standard Time)'
let currentDate = moment(new Date('Fri Dec 11 2020 05:00:00 GMT+0500 (Pakistan Standard Time)').format('DD-MM-YYYY'); // 'Fri Dec 11 2020 05:00:00 GMT+0500 (Pakistan Standard Time)'
let output=(moment(currentDate).isSameOrAfter('07-12-2020'));
For Linux
Open Terminal :
For Debug Build
keytool -exportcert -alias androiddebugkey -keystore debug.keystore | openssl sha1 -binary | openssl base64
you wil find debug.keystore from ".android" folder copy it from and paste on desktop and run above command
For release Build
keytool -exportcert -alias <aliasName> -keystore <keystoreFilePath> | openssl sha1 -binary | openssl base64
NOTE : Make sure In Both case it must ask for password. If it does not asks for password that means something is wrong in command.
In cs file:
private DataTable _dataTable;
public DataTable DataTable
{
get { return _dataTable; }
set { _dataTable = value; }
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
this._dataTable = new DataTable("table");
this._dataTable.Columns.Add("col0");
this._dataTable.Columns.Add("col1");
this._dataTable.Columns.Add("col2");
this._dataTable.Rows.Add("data00", "data01", "data02");
this._dataTable.Rows.Add("data10", "data11", "data22");
this._dataTable.Rows.Add("data20", "data21", "data22");
this.grid1.DataContext = this;
}
In Xaml file:
<DataGrid x:Name="grid1"
Margin="10"
AutoGenerateColumns="True"
ItemsSource="{Binding Path=DataTable, Mode=TwoWay}" />
I think, this example suggests a small nuance on how the partitioning works and how group by works. My example is from Oracle 12, if my example happens to be a compiling bug.
I tried :
SELECT t.data_key
, SUM ( CASE when t.state = 'A' THEN 1 ELSE 0 END)
OVER (PARTITION BY t.data_key) count_a_rows
, SUM ( CASE when t.state = 'B' THEN 1 ELSE 0 END)
OVER (PARTITION BY t.data_key) count_b_rows
, SUM ( CASE when t.state = 'C' THEN 1 ELSE 0 END)
OVER (PARTITION BY t.data_key) count_c_rows
, COUNT (1) total_rows
from mytable t
group by t.data_key ---- This does not compile as the compiler feels that t.state isn't in the group by and doesn't recognize the aggregation I'm looking for
This however works as expected :
SELECT distinct t.data_key
, SUM ( CASE when t.state = 'A' THEN 1 ELSE 0 END)
OVER (PARTITION BY t.data_key) count_a_rows
, SUM ( CASE when t.state = 'B' THEN 1 ELSE 0 END)
OVER (PARTITION BY t.data_key) count_b_rows
, SUM ( CASE when t.state = 'C' THEN 1 ELSE 0 END)
OVER (PARTITION BY t.data_key) count_c_rows
, COUNT (1) total_rows
from mytable t;
Producing the number of elements in each state based on the external key "data_key". So, if, data_key = 'APPLE' had 3 rows with state 'A', 2 rows with state 'B', a row with state 'C', the corresponding row for 'APPLE' would be 'APPLE', 3, 2, 1, 6.
Try this Javascript (jquery) code. Its an ajax request to an external URL. Use the callback function to fire any code:
<script type="text/javascript">
$(function() {
$('form').submit(function(){
$.post('http://example.com/upload', function() {
window.location = 'http://google.com';
});
return false;
});
});
</script>
On Gentoo You have to execute the following
# Install postgresql client libraries
sudo emerge postgresql-base
Or else you can use two arrays to implement queue data structure.
var temp_stack = new Array();
var stack = new Array();
temp_stack.push(1);
temp_stack.push(2);
temp_stack.push(3);
If I pop the elements now then the output will be 3,2,1. But we want FIFO structure so you can do the following.
stack.push(temp_stack.pop());
stack.push(temp_stack.pop());
stack.push(temp_stack.pop());
stack.pop(); //Pop out 1
stack.pop(); //Pop out 2
stack.pop(); //Pop out 3
Just to elaborate on the excellent answer from K3---rnc, here is a more generic version:
def onehottify(x, n=None, dtype=float):
"""1-hot encode x with the max value n (computed from data if n is None)."""
x = np.asarray(x)
n = np.max(x) + 1 if n is None else n
return np.eye(n, dtype=dtype)[x]
Also, here is a quick-and-dirty benchmark of this method and a method from the currently accepted answer by YXD (slightly changed, so that they offer the same API except that the latter works only with 1D ndarrays):
def onehottify_only_1d(x, n=None, dtype=float):
x = np.asarray(x)
n = np.max(x) + 1 if n is None else n
b = np.zeros((len(x), n), dtype=dtype)
b[np.arange(len(x)), x] = 1
return b
The latter method is ~35% faster (MacBook Pro 13 2015), but the former is more general:
>>> import numpy as np
>>> np.random.seed(42)
>>> a = np.random.randint(0, 9, size=(10_000,))
>>> a
array([6, 3, 7, ..., 5, 8, 6])
>>> %timeit onehottify(a, 10)
188 µs ± 5.03 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
>>> %timeit onehottify_only_1d(a, 10)
139 µs ± 2.78 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
Take these two scenarios:
Optional<Foo> opt = ...
Foo x = opt.orElse( new Foo() );
Foo y = opt.orElseGet( Foo::new );
If opt
doesn't contain a value, the two are indeed equivalent. But if opt
does contain a value, how many Foo
objects will be created?
P.s.: of course in this example the difference probably wouldn't be measurable, but if you have to obtain your default value from a remote web service for example, or from a database, it suddenly becomes very important.
Async/Await with axios
useEffect(() => {
const getData = async () => {
await axios.get('your_url')
.then(res => {
console.log(res)
})
.catch(err => {
console.log(err)
});
}
getData()
}, [])
Should also be able to do this:
total += eval(myInt1) + eval(myInt2) + eval(myInt3);
This helped me in a different, but similar, situation.
You don't have to bind parameters if you use query builder or eloquent ORM. However, if you use DB::raw()
, ensure that you binding the parameters.
Try the following:
$array = array(1,2,3); $query = DB::table('offers'); $query->select('id', 'business_id', 'address_id', 'title', 'details', 'value', 'total_available', 'start_date', 'end_date', 'terms', 'type', 'coupon_code', 'is_barcode_available', 'is_exclusive', 'userinformations_id', 'is_used'); $query->leftJoin('user_offer_collection', function ($join) use ($array) { $join->on('user_offer_collection.offers_id', '=', 'offers.id') ->whereIn('user_offer_collection.user_id', $array); }); $query->get();
Try this code, I get working fine.
webSettings.setSupportZoom(true);
webSettings.setBuiltInZoomControls(true);
webSettings.setDisplayZoomControls(false);
Using grid?
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = "#FF0000";
ctx.fillRect(0, 0, canvas.width, canvas.height);
_x000D_
body, html {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
background-color: black;
}
body {
display: grid;
grid-template-rows: auto;
justify-items: center;
align-items: center;
}
canvas {
height: 80vh;
width: 80vw;
display: block;
}
_x000D_
<html>
<body>
<canvas></canvas>
</body>
</html>
_x000D_
If you comparing 2 arrays but values not in same index, then try this
var array1=[1,2,3,4]
var array2=[1,4,3,2]
var is_equal = array1.length==array2.length && array1.every(function(v,i) { return ($.inArray(v,array2) != -1)})
console.log(is_equal)
Delete rows from dbo_MigrationHistory table or delete the table and run
update-database -verbose
It will run all the migrations in your project one by one
For >= Python3.4:
import importlib
importlib.reload(module)
For <= Python3.3:
import imp
imp.reload(module)
For Python2.x:
Use the in-built reload()
function.
reload(module)
chunks = [data[100*i:100*(i+1)] for i in range(len(data)/100 + 1)]
This is equivalent to the accepted answer. For example, shortening to batches of 10 for readability:
data = range(35)
print [data[x:x+10] for x in xrange(0, len(data), 10)]
print [data[10*i:10*(i+1)] for i in range(len(data)/10 + 1)]
Outputs:
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [10, 11, 12, 13, 14, 15, 16, 17, 18, 19], [20, 21, 22, 23, 24, 25, 26, 27, 28, 29], [30, 31, 32, 33, 34]]
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [10, 11, 12, 13, 14, 15, 16, 17, 18, 19], [20, 21, 22, 23, 24, 25, 26, 27, 28, 29], [30, 31, 32, 33, 34]]
I had got the same CORS error while working on a Vue.js project. You can resolve this either by building a proxy server or another way would be to disable the security settings of your browser (eg, CHROME) for accessing cross origin apis (this is temporary solution & not the best way to solve the issue). Both these solutions had worked for me. The later solution does not require any mock server or a proxy server to be build. Both these solutions can be resolved at the front end.
You can disable the chrome security settings for accessing apis out of the origin by typing the below command on the terminal:
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --user-data-dir="/tmp/chrome_dev_session" --disable-web-security
After running the above command on your terminal, a new chrome window with security settings disabled will open up. Now, run your program (npm run serve / npm run dev) again and this time you will not get any CORS error and would be able to GET request using axios.
Hope this helps!
I'd like to add one suggestion I've used, based on defense in depth. You don't need to have the same auth&auth system for admins as regular users. You can have a separate login form on a separate url executing separate code for requests that will grant high privileges. This one can make choices that would be a total pain to regular users. One such that I've used is to actually scramble the login URL for admin access and email the admin the new URL. Stops any brute force attack right away as your new URL can be arbitrarily difficult (very long random string) but your admin user's only inconvenience is following a link in their email. The attacker no longer knows where to even POST to.
As pointed out by @aarjithn, that WebP is a codec for storing photographs.
This is also a codec to store animations (animated image sequence). As of 2020, most mainstream browsers has out of the box support for it (compatibility table). Note for WIC a plugin is available.
It has advantages over GIF because it is based on a video codec VP8 and has a broader color range than GIF, where GIF limits to 256 colors it expands it to 224 = 16777216 colors, still saving significant amount of space.
Additional information to abouve answers for those still having problems.
FindBoost.cmake
may not content last
version fo Boost. Add it if needed.Boost_COMPILER
and Boost_ARCHITECTURE
suffix vars if needed.You simply need to upgrade your Tomcat version, to Tomcat 8.0.xx. Java8 <-> Tomcat8
This is the configuration that I have been using and it has always worked out well
When mysql was installed with Homebrew, the following command did the trick for me:
brew services stop mysql
The simplest way ist just to start it with start
start notepad.exe
Here you can find more information about start
I think the problem may be in the charset that you are trying to use. It is probably best to use UTF-8 instead of iso-8859-1.
Also open whatever file is being used for your InputStream and make sure no special characters were accidentally inserted. Sometimes you have to specifically tell your editor to display hidden / special characters.
Try this example:
exec DBMS_LOCK.sleep(5);
This is the whole script:
SELECT TO_CHAR (SYSDATE, 'MM-DD-YYYY HH24:MI:SS') "Start Date / Time" FROM DUAL;
exec DBMS_LOCK.sleep(5);
SELECT TO_CHAR (SYSDATE, 'MM-DD-YYYY HH24:MI:SS') "End Date / Time" FROM DUAL;
You must have to define encoding format
like utf-8
,
Try this easy way,
This example generates a random number using the SHA256 algorithm:
>>> import hashlib
>>> hashlib.sha256(str(random.getrandbits(256)).encode('utf-8')).hexdigest()
'cd183a211ed2434eac4f31b317c573c50e6c24e3a28b82ddcb0bf8bedf387a9f'
To clarify, the syntax is as follows for MongoDB version 4.0.x:
db.collection.update({},{$set: {"new_field*":1}},false,true)
Here is a working example adding a published field to the articles collection and setting the field's value to true:
db.articles.update({},{$set: {"published":true}},false,true)
Very near to TheEye answer, but I change a little thing to make it work:
var num = 192.16;_x000D_
_x000D_
console.log( Math.ceil(num * 10) / 10 );
_x000D_
$('<input>').attr('type','hidden').appendTo('form');
To answer your second question:
$('<input>').attr({
type: 'hidden',
id: 'foo',
name: 'bar'
}).appendTo('form');
Recently I had this problem and none of solutions provided here helped me. Or it completely destroyed it so it could not be shown again. On document ready also did not work but what worked is that I wrapped all my listeners with immediately invoked function like this:
$(function () {
$('#btn-show-modal').click(function () {
$("#modal-lightbox").modal('show');
});
$('#btn-close-modal').click(function () {
$("#modal-lightbox").modal('hide');
});
});
private static String removeQuotesFromStartAndEndOfString(String inputStr) {
String result = inputStr;
int firstQuote = inputStr.indexOf('\"');
int lastQuote = result.lastIndexOf('\"');
int strLength = inputStr.length();
if (firstQuote == 0 && lastQuote == strLength - 1) {
result = result.substring(1, strLength - 1);
}
return result;
}
There is one important thing to mention:
$("#txt_name").val();
will return the current real value of a text field, for example if the user typed something there after a page load.
But:
$("#txt_name").attr('value')
will return value from DOM/HTML.
In Postgres, you can make almost any single value query return a value or null by wrapping it:
SELECT (SELECT <query>) AS value
and hence avoid complexity in the caller.
Even if this question is a little older:
If you want to use if cond1 or cond 2
- you should not use complicated loops or stuff like that.
Simple provide both ifs
after each other combined with goto
- that's an implicit or.
//thats an implicit IF cond1 OR cond2 OR cond3
if cond1 GOTO doit
if cond2 GOTO doit
if cond3 GOTO doit
//thats our else.
GOTO end
:doit
echo "doing it"
:end
Without goto but an "inplace" action, you might execute the action 3 times, if ALL conditions are matching.
You need to configure the security group as stated by cyraxjoe. Along with that you also need to open System port. Steps to open port in windows :-
//------------------code is return in typescript
const updateMyData1 = (rowIndex:any, columnId:any, value:any) => {
setItems(old => old.map((row, index) => {
if (index === rowIndex) {
return Object.assign(Object.assign({}, old[rowIndex]), { [columnId]: value });
}
return row;
}));
The Code Runner extension has a setting "Clear previous output", which is what I need 95% of the time.
File > Preferences > Settings > (search for "output") > Code-runner: Clear previous output
The remaining few times I will disable the setting and use the "Clear output" button (top right of the output pane) to selectively clear accumulated output.
This is in Visual Studio Code 1.33.1 with Code Runner 0.9.8.
(Setting the keybinding for Ctrl+k
did not work for me, presumably because some extension has defined "chords" beginning with Ctrl-k
. But "Clear previous output" was actually a better option for me.)
I see one problem with std::make_shared, it doesn't support private/protected constructors
There are already many good answers to the part "what is uintptr_t data type". I will try to address the "what it can be used for?" part in this post.
Primarily for bitwise operations on pointers. Remember that in C++ one cannot perform bitwise operations on pointers. For reasons see Why can't you do bitwise operations on pointer in C, and is there a way around this?
Thus in order to do bitwise operations on pointers one would need to cast pointers to type unitpr_t and then perform bitwise operations.
Here is an example of a function that I just wrote to do bitwise exclusive or of 2 pointers to store in a XOR linked list so that we can traverse in both directions like a doubly linked list but without the penalty of storing 2 pointers in each node.
template <typename T>
T* xor_ptrs(T* t1, T* t2)
{
return reinterpret_cast<T*>(reinterpret_cast<uintptr_t>(t1)^reinterpret_cast<uintptr_t>(t2));
}
Those two solution require only two nested elements.
First - Relative and absolute positioning if the content is static (manual center).
.black {
position:relative;
min-height:500px;
background:rgba(0,0,0,.5);
}
.message {
position:absolute;
margin: 0 auto;
width: 180px;
top: 45%; bottom:45%; left: 0%; right: 0%;
}
https://jsfiddle.net/GlupiJas/5mv3j171/
or for fluid design - for exact content center use below example instead:
.message {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
https://jsfiddle.net/GlupiJas/w3jnjuv0/
You need 'min-height' set in case the content will exceed 50% of window height. You can also manipulate this height with media query for mobile and tablet devices . But only if You play with responsive design.
I guess You could go further and use simple JavaScript/JQuery script to manipulate the min-height or fixed height if there is a need for some reason.
Second - if content is fluid u can also use table and table-cell css properties with vertical alignment and text-align centered:
/*in a wrapper*/
display:table;
and
/*in the element inside the wrapper*/
display:table-cell;
vertical-align: middle;
text-align: center;
Works and scale perfectly, often used as responsive web design solution with grid layouts and media query that manipulate the width of the object.
.black {
display:table;
height:500px;
width:100%;
background:rgba(0,0,0,.5);
}
.message {
display:table-cell;
vertical-align: middle;
text-align: center;
}
https://jsfiddle.net/GlupiJas/4daf2v36/
I prefer table solution for exact content centering, but in some cases relative absolute positioning will do better job especially if we don't want to keep exact proportion of content alignment.
The error is in your string formatting.
The correct way to use traditional string formatting using the '%' operator is to use a printf-style format string (Python documentation for this here: http://docs.python.org/2/library/string.html#format-string-syntax):
"'%s' is longer than '%s'" % (name1, name2)
However, the '%' operator will probably be deprecated in the future. The new PEP 3101 way of doing things is like this:
"'{0}' is longer than '{1}'".format(name1, name2)
Currently, it is not possible to prevent a user from writing decimal values in your input with HTML only. You have to use javascript.
If you're using SQL Server it would be something like this:
DATEDIFF(d,GETDATE(),FUTUREDATE) BETWEEN 0 AND 90
This way to pass value from Controller to View:
ViewData["ID"] = _obj.ID;
Here is the way to pass value from View to Controller back:
<input type="button" title="Next" value="Next Step" onclick="location.href='@Url.Action("CreatePerson", "Person", new { ID = ViewData["ID"] })'" />
Using a UINavigationController
and setting its navigation bar's barStyle
to .Black
. past this line in your AppDelegate.m
file.
navigationController.navigationBar.barStyle = UIBarStyleBlack;
If you are not using UINavigationController
then add following code in your ViewController.m
file.
- (UIStatusBarStyle)preferredStatusBarStyle
{
return UIStatusBarStyleLightContent;
}
And call the method to this line :
[self setNeedsStatusBarAppearanceUpdate];
The WebClient class should be more than capable of handling the functionality you describe, for example:
System.Net.WebClient wc = new System.Net.WebClient();
byte[] raw = wc.DownloadData("http://www.yoursite.com/resource/file.htm");
string webData = System.Text.Encoding.UTF8.GetString(raw);
or (further to suggestion from Fredrick in comments)
System.Net.WebClient wc = new System.Net.WebClient();
string webData = wc.DownloadString("http://www.yoursite.com/resource/file.htm");
When you say it took 30 seconds, can you expand on that a little more? There are many reasons as to why that could have happened. Slow servers, internet connections, dodgy implementation etc etc.
You could go a level lower and implement something like this:
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://www.yoursite.com/resource/file.htm");
using (StreamWriter streamWriter = new StreamWriter(webRequest.GetRequestStream(), Encoding.UTF8))
{
streamWriter.Write(requestData);
}
string responseData = string.Empty;
HttpWebResponse httpResponse = (HttpWebResponse)webRequest.GetResponse();
using (StreamReader responseReader = new StreamReader(httpResponse.GetResponseStream()))
{
responseData = responseReader.ReadToEnd();
}
However, at the end of the day the WebClient class wraps up this functionality for you. So I would suggest that you use WebClient and investigate the causes of the 30 second delay.
Using ranking method.
SELECT @rn := CASE WHEN @prev_grp <> groupa THEN 1 ELSE @rn+1 END AS rn,
@prev_grp :=groupa,
person,age,groupa
FROM users,(SELECT @rn := 0) r
HAVING rn=1
ORDER BY groupa,age DESC,person
This sql can be explained as below,
select * from users, (select @rn := 0) r order by groupa, age desc, person
@prev_grp is null
@rn := CASE WHEN @prev_grp <> groupa THEN 1 ELSE @rn+1 END
this is a three operator expression
like this, rn = 1 if prev_grp != groupa else rn=rn+1
having rn=1 filter out the row you need
You can safely delete the WSDL cache files. If you wish to prevent future caching, use:
ini_set("soap.wsdl_cache_enabled", 0);
or dynamically:
$client = new SoapClient('http://somewhere.com/?wsdl', array('cache_wsdl' => WSDL_CACHE_NONE) );
For Android Studio below 4.1:
From the Top menu Click File and then click Export to Zip File
For Android Studio 4.1 and above:
From the Top menu click File > Manage IDE Settings > Export to Zip File ()
I am writing here for future use of my own. It uses sp_who2 and insert into table variable instead of temp table because Temp table cannot be used twice if you do not drop it. And shows blocked and blocker at the same line.
--blocked: waiting becaused blocked by blocker
--blocker: caused blocking
declare @sp_who2 table(
SPID int,
Status varchar(max),
Login varchar(max),
HostName varchar(max),
BlkBy varchar(max),
DBName varchar(max),
Command varchar(max),
CPUTime int,
DiskIO int,
LastBatch varchar(max),
ProgramName varchar(max),
SPID_2 int,
REQUESTID int
)
insert into @sp_who2 exec sp_who2
select w.SPID blocked_spid, w.BlkBy blocker_spid, tblocked.text blocked_text, tblocker.text blocker_text
from @sp_who2 w
inner join sys.sysprocesses pblocked on w.SPID = pblocked.spid
cross apply sys.dm_exec_sql_text(pblocked.sql_handle) tblocked
inner join sys.sysprocesses pblocker on case when w.BlkBy = ' .' then 0 else cast(w.BlkBy as int) end = pblocker.spid
cross apply sys.dm_exec_sql_text(pblocker.sql_handle) tblocker
where pblocked.Status = 'SUSPENDED'
You are asking to initialize four variables using a single float object, which of course is not iterable. You can do -
grade_1, grade_2, grade_3, grade_4 = [0.0 for _ in range(4)]
grade_1 = grade_2 = grade_3 = grade_4 = 0.0
Unless you want to initialize them with different values of course.
If you only need to pass the value from the outside into the lambda, and not get it out, you can do it with a regular anonymous class instead of a lambda:
list.forEach(new Consumer<Example>() {
int ordinal = 0;
public void accept(Example s) {
s.setOrdinal(ordinal);
ordinal++;
}
});
You can also use scipy.signal.welch to estimate the power spectral density using Welch’s method. Here is an comparison between np.fft.fft and scipy.signal.welch:
from scipy import signal
import numpy as np
import matplotlib.pyplot as plt
fs = 10e3
N = 1e5
amp = 2*np.sqrt(2)
freq = 1234.0
noise_power = 0.001 * fs / 2
time = np.arange(N) / fs
x = amp*np.sin(2*np.pi*freq*time)
x += np.random.normal(scale=np.sqrt(noise_power), size=time.shape)
# np.fft.fft
freqs = np.fft.fftfreq(time.size, 1/fs)
idx = np.argsort(freqs)
ps = np.abs(np.fft.fft(x))**2
plt.figure()
plt.plot(freqs[idx], ps[idx])
plt.title('Power spectrum (np.fft.fft)')
# signal.welch
f, Pxx_spec = signal.welch(x, fs, 'flattop', 1024, scaling='spectrum')
plt.figure()
plt.semilogy(f, np.sqrt(Pxx_spec))
plt.xlabel('frequency [Hz]')
plt.ylabel('Linear spectrum [V RMS]')
plt.title('Power spectrum (scipy.signal.welch)')
plt.show()
Find all products that has been ordered 1 or more times... (kind of duplicate records)
SELECT DISTINCT * from [order_items] where productid in
(SELECT productid
FROM [order_items]
group by productid
having COUNT(*)>0)
order by productid
To select the last inserted of those...
SELECT DISTINCT productid, MAX(id) OVER (PARTITION BY productid) AS LastRowId from [order_items] where productid in
(SELECT productid
FROM [order_items]
group by productid
having COUNT(*)>0)
order by productid
Use the location header flag:
curl -L <URL>
You need to set property for the control:
listView1.View = View.Details;
External fragmentation
Total memory space is enough to satisfy a request or to reside a process in it, but it is not contiguous so it can not be used.
Internal fragmentation
Memory block assigned to process is bigger. Some portion of memory is left unused as it can not be used by another process.
I wrote a little script based on Florian's answer that uses nano (my favorite editor):
#!/bin/sh
if [ "$#" -ne 3 ]; then
echo "Usage: $0 hugeFilePath startLine endLine" >&2
exit 1
fi
sed -n -e $2','$3'p' -e $3'q' $1 > hfnano_temporary_file
nano hfnano_temporary_file
(head -n `expr $2 - 1` $1; cat hfnano_temporary_file; sed -e '1,'$3'd' $1) > hfnano_temporary_file2
cat hfnano_temporary_file2 > $1
rm hfnano_temporary_file hfnano_temporary_file2
Use it like this:
sh hfnano yourHugeFile 3 8
In that example, nano will open up lines 3 through 8, you can edit them, and when you save and quit, those lines in the hugefile will automatically be overwritten with your saved lines.
Check to make sure that the file is complete. This error message can occur if you only partially downloaded a file or if it has major issues. Check the MD5sum.
@Configuration annotation will just solve the error
This is less for @easwee and more for others that might have the same question:
If you do not require support for IE < 10, you can use Flexbox. It's an exciting CSS3 property that unfortunately was implemented in several different versions,; add in vendor prefixes, and getting good cross-browser support suddenly requires quite a few more properties than it should.
With the current, final standard, you would be done with
.container {
display: flex;
}
.container div {
flex: 1;
}
.column_center {
order: 2;
}
That's it. If you want to support older implementations like iOS 6, Safari < 6, Firefox 19 or IE10, this blossoms into
.container {
display: -webkit-box; /* OLD - iOS 6-, Safari 3.1-6 */
display: -moz-box; /* OLD - Firefox 19- (buggy but mostly works) */
display: -ms-flexbox; /* TWEENER - IE 10 */
display: -webkit-flex; /* NEW - Chrome */
display: flex; /* NEW, Spec - Opera 12.1, Firefox 20+ */
}
.container div {
-webkit-box-flex: 1; /* OLD - iOS 6-, Safari 3.1-6 */
-moz-box-flex: 1; /* OLD - Firefox 19- */
-webkit-flex: 1; /* Chrome */
-ms-flex: 1; /* IE 10 */
flex: 1; /* NEW, Spec - Opera 12.1, Firefox 20+ */
}
.column_center {
-webkit-box-ordinal-group: 2; /* OLD - iOS 6-, Safari 3.1-6 */
-moz-box-ordinal-group: 2; /* OLD - Firefox 19- */
-ms-flex-order: 2; /* TWEENER - IE 10 */
-webkit-order: 2; /* NEW - Chrome */
order: 2; /* NEW, Spec - Opera 12.1, Firefox 20+ */
}
Here is an excellent article about Flexbox cross-browser support: Using Flexbox: Mixing Old And New
The most trivial way to upload a file over SFTP with JSch is:
JSch jsch = new JSch();
Session session = jsch.getSession(user, host);
session.setPassword(password);
session.connect();
ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();
sftpChannel.put("C:/source/local/path/file.zip", "/target/remote/path/file.zip");
Similarly for a download:
sftpChannel.get("/source/remote/path/file.zip", "C:/target/local/path/file.zip");
You may need to deal with UnknownHostKey
exception.
Toggle between two classes 'A' and 'B' with Jquery.
$('#selecor_id').toggleClass("A B");
I am running Anaconda version 4.3.22 and a python3.6.1 environment, and had this problem. Here's the history and the fix:
pip uninstall opencv-python # -- the original step. failed.
ImportError: DLL load failed: The specified module could not be found.
I did this into my python3.6 environment and got this error.
python -m pip install opencv-python # same package as above.
conda install -c conda-forge opencv # separate install parallel to opencv
pip-install opencv-contrib-python # suggested by another user here. doesn't resolve it.
Next, I tried downloading python3.6 and putting the python3.dll in the folder and in various folders. nothing changed.
finally, this fixed it:
pip uninstall opencv-python
(the other conda-forge version is still installed) This left only the conda version, and that works in 3.6.
>>>import cv2
>>>
working!
It doesn't matter is your app Boot or just raw Spring. There is just enough to inject org.springframework.core.env.Environment
to your bean.
@Autowired
private Environment environment;
....
this.environment.getActiveProfiles();
I ran into this error trying to run the profiler, even though my connection had Trust server certificate checked and I added TrustServerCertificate=True
in the Advanced Section. I changed to an instance of SSMS running as administrator and the profiler started with no problem. (I previously had found that when my connections even to local took a long time to connect, running as administrator helped).
If you are using bootstrap-datepicker you may use this style:
$('#datepicker').datepicker('setStartDate', "01-01-1900");
This is how I did a similar thing. I have tiles that are thumbnails to YouTube videos. When I click the tile, it redirects me to a 'player' page that uses the 'video_id' to render the correct video to the page.
<GridTile
key={video_id}
title={video_title}
containerElement={<Link to={`/player/${video_id}`}/>}
>
ETA: Sorry, just noticed that you didn't want to use the LINK or REDIRECT components for some reason. Maybe my answer will still help in some way. ; )
Every function inside a class, and every class variable must take the self argument as pointed.
class mystuff:
def average(a,b,c): #get the average of three numbers
result=a+b+c
result=result/3
return result
def sum(self,a,b):
return a+b
print mystuff.average(9,18,27) # should raise error
print mystuff.sum(18,27) # should be ok
If class variables are involved:
class mystuff:
def setVariables(self,a,b):
self.x = a
self.y = b
return a+b
def mult(self):
return x * y # This line will raise an error
def sum(self):
return self.x + self.y
print mystuff.setVariables(9,18) # Setting mystuff.x and mystuff.y
print mystuff.mult() # should raise error
print mystuff.sum() # should be ok
To complement Justus Thane's helpful answer:
As Joey notes in a comment, PowerShell has a powerful, regex-based -split
operator.
-split '...'
), -split
behaves like awk
's default field splitting, which means that:
In PowerShell v4+ an expression-based - and therefore faster - alternative to the ForEach-Object
cmdlet became available: the .ForEach()
array (collection) method, as described in this blog post (alongside the .Where()
method, a more powerful, expression-based alternative to Where-Object
).
Here's a solution based on these features:
PS> (-split ' One for the money ').ForEach({ "token: [$_]" })
token: [One]
token: [for]
token: [the]
token: [money]
Note that the leading and trailing whitespace was ignored, and that the multiple spaces between One
and for
were treated as a single separator.
#!/usr/bin/python3
import sys
primary_numbers = [1, 2]
def is_prime(i):
for pn in enumerate(primary_numbers[2:]):
if i % pn[1] == 0:
return False
return True
def main(position):
i = 3
while len(primary_numbers) < int(position):
print(i)
res = is_prime(i)
if res:
primary_numbers.append(i)
i += 2
if __name__ == '__main__':
position = sys.argv[1]
main(position)
print(primary_numbers)
You have a scope problem. Define the struct before the function, not inside it.
In your receiving intent you need to do:
Intent i = getIntent();
stock_list = i.getStringArrayListExtra("stock_list");
The way you have it you've just created a new empty intent without any extras.
If you only have a single extra you can condense this down to:
stock_list = getIntent().getStringArrayListExtra("stock_list");
list1 = list1.stream().filter(str1->
list2.stream().map(x->x.getStr()).collect(Collectors.toSet())
.contains(str1)).collect(Collectors.toList());
This may work more efficient.
A quick bad approach is that go to app\http\middleware\verifycsrftoken.php and add the route in $except list. The post request will be ignord for CSRF Token verification.
protected $except = [
//
'doLogin.aspx',
'create_coupon',
];
try this
!pip install opencv-contrib-python==4.4.0.44 sift = cv2.SIFT_create()
Just add <br>
where you would like to make the new line.
$S$: a set of shops
<br>
$I$: a set of items M wants to get
Because jupyter notebook markdown cell is a superset of HTML.
http://jupyter-notebook.readthedocs.io/en/latest/examples/Notebook/Working%20With%20Markdown%20Cells.html
Note that newlines using <br>
does not persist when exporting or saving the notebook to a pdf (using "Download as > PDF via LaTeX"). It is probably treating each <br>
as a space.
When an array is a type of Integer class then you can use below:
Integer[] arr = {7, 10, 4, 3, 20, 15};
Arrays.sort(arr, Collections.reverseOrder());
When an array is a type of int data type then you can use below:
int[] arr = {7, 10, 4, 3, 20, 15};
int[] reverseArr = IntStream.rangeClosed(1, arr.length).map(i -> arr[arr.length-i]).toArray();
Here are simple steps that minimize tedium and don't require error-prone semi-automated scripts or pricey tools.
Keep in mind that you can generate DROP/CREATE statements for multiple objects from the Object Explorer Details window (when generated this way, DROP and CREATE scripts are grouped, which makes it easy to insert logic between Drop and Create actions):
If you have smaller projects where it might make sense to change the infrastructure architecture, consider eliminating user-defined table types. Entity Framework and similar tools allow you to move most, if not all, of your data logic to your code base where it's easier to maintain.
Here's a solution based on my favorite ideas from this discussion. This allows styling a <select> element directly without any additional markup.
It works Internet Explorer 10 (and later) with a safe fallback for Internet Explorer 8/9. One caveat for these browsers is that the background image must be positioned and be small enough to hide behind the native expand control.
<select name='options'>
<option value='option-1'>Option 1</option>
<option value='option-2'>Option 2</option>
<option value='option-3'>Option 3</option>
</select>
body {
padding: 4em 40%;
text-align: center;
}
select {
$bg-color: lightcyan;
$text-color: black;
appearance: none; // Using -prefix-free http://leaverou.github.io/prefixfree/
background: {
color: $bg-color;
image: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/1255/caret--down-15.png");
position: right;
repeat: no-repeat;
}
border: {
color: mix($bg-color, black, 80%);
radius: .2em;
style: solid;
width: 1px;
right-color: mix($bg-color, black, 60%);
bottom-color: mix($bg-color, black, 60%);
}
color: $text-color;
padding: .33em .5em;
width: 100%;
}
// Removes default arrow for Internet Explorer 10 (and later)
// Internet Explorer 8/9 gets the default arrow which covers the caret
// image as long as the caret image is smaller than and positioned
// behind the default arrow
select::-ms-expand {
display: none;
}
Git as a system manages and manipulates three trees in its normal operation:
HEAD is the pointer to the current branch reference, which is in turn a pointer to the last commit made on that branch. That means HEAD will be the parent of the next commit that is created. It’s generally simplest to think of HEAD as the snapshot of your last commit on that branch.
What does it contain?
To see what that snapshot looks like run the following in root directory of your repository:
git ls-tree -r HEAD
it would result in something like this:
$ git ls-tree -r HEAD
100644 blob a906cb2a4a904a152... README
100644 blob 8f94139338f9404f2... Rakefile
040000 tree 99f1a6d12cb4b6f19... lib
Git populates this index with a list of all the file contents that were last checked out into your working directory and what they looked like when they were originally checked out. You then replace some of those files with new versions of them, and git commit converts that into the tree for a new commit.
What does it contain?
Use git ls-files -s
to see what it looks like. You should see something like this:
100644 a906cb2a4a904a152e80877d4088654daad0c859 0 README
100644 8f94139338f9404f26296befa88755fc2598c289 0 Rakefile
100644 47c6340d6459e05787f644c2447d2595f5d3a54b 0 lib/simplegit.rb
This is where your files reside and where you can try changes out before committing them to your staging area (index) and then into history.
Let's see how do these three trees (As the ProGit book refers to them) work together?
Git’s typical workflow is to record snapshots of your project in successively better states, by manipulating these three trees. Take a look at this picture:
To get a good visualized understanding consider this scenario. Say you go into a new directory with a single file in it. Call this v1 of the file. It is indicated in blue. Running git init
will create a Git repository with a HEAD reference which points to the unborn master branch
At this point, only the working directory tree has any content.
Now we want to commit this file, so we use git add
to take content in the working directory and copy it to the index.
Then we run git commit
, which takes the contents of the index and saves it as a permanent snapshot, creates a commit object which points to that snapshot, and updates master to point to that commit.
If we run git status
, we’ll see no changes, because all three trees are the same.
The beautiful point
git status shows the difference between these trees in the following manner:
git status
will show there are some changes not staged for commitgit status
will show some files under changes to be committed section in its resultgit status
will show some files under changes not staged for commit section and some other files under changes to be committed section in its result.Note about git reset
command
Hopefully, knowing how reset
command works will further brighten the reason behind the existence of these three trees.
reset
command is your Time Machine in git which can easily take you back in time and bring some old snapshots for you to work on. In this manner, HEAD is the wormhole through which you can travel in time. Let's see how it works with an example from the book:
Consider the following repository which has a single file and 3 commits which are shown in different colours and different version numbers:
The state of trees is like the next picture:
The first thing reset will do is move what HEAD points to. This isn’t the same as changing HEAD itself (which is what checkout does). reset moves the branch that HEAD is pointing to. This means if HEAD is set to the master branch, running git reset 9e5e6a4 will start by making master point to 9e5e6a4. If you call reset
with --soft
option it will stop here, without changing index
and working directory
. Our repo will look like this now:
Notice: HEAD~ is the parent of HEAD
Looking a second time at the image, we can see that the command essentially undid the last commit. As the working tree and the index are the same but different from HEAD, git status
will now show changes in green ready to be committed.
This is the default option of the command
Running reset
with --mixed
option updates the index with the contents of whatever snapshot HEAD points to currently, leaving Working Directory intact. Doing so, your repository will look like when you had done some work that is not staged and git status
will show that as changes not staged for commit in red. This option will also undo the last commit and also unstage all the changes. It's like you made changes but have not called git add
command yet. Our repo would look like this now:
If you call reset
with --hard
option it will copy contents of the snapshot HEAD is pointing to into HEAD, index and Working Directory. After executing reset --hard command, it would mean like you got back to a previous point in time and haven't done anything after that at all. see the picture below:
I hope now you have a better understanding of these trees and have a great idea of the power they bring to you by enabling you to change your files in your repository to undo or redo things you have done mistakenly.
I recently had this problem and found this question and answers. While the above questions work, the problem is that they don't show the default values to IDEs that support it (like PHPStorm).
if you use null
you won't know what the value would be if you leave it blank.
The solution I prefer is to put the default value in the function definition also:
protected function baseItemQuery(BoolQuery $boolQuery, $limit=1000, $sort = [], $offset = 0, $remove_dead=true)
{
if ($limit===null) $limit =1000;
if ($sort===null) $sort = [];
if ($offset===null) $offset = 0;
...
The only difference is that I need to make sure they are the same - but I think that's a small price to pay for the additional clarity.
As the reference for friend declaration says:
The friend declaration appears in a class body and grants a function or another class access to private and protected members of the class where the friend declaration appears.
So just as a reminder, there are technical errors in some of the answers which say that friend
can only visit protected members.
CALL common.php
<style>
.ddsmoothmenu ul li{float: left; padding: 0 20px;}
.ddsmoothmenu ul li a{display: block;
padding: 40px 15px 20px 15px;
color: #4b4b4b;
font-size: 13px;
font-family: 'Open Sans', Arial, sans-serif;
text-align: right;
text-transform: uppercase;
margin-left: 1px; color: #fff; background: #000;}
.current .test{ background: #2767A3; color: #fff;}
</style>
<div class="span8 ddsmoothmenu">
<!-- // Dropdown Menu // -->
<ul id="dropdown-menu" class="fixed">
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'index.php'){echo 'current'; }else { echo ''; } ?>"><a href="index.php" class="test">Home <i>::</i> <span>welcome</span></a></li>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'about.php'){echo 'current'; }else { echo ''; } ?>"><a href="about.php" class="test">About us <i>::</i> <span>Who we are</span></a></li>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'course.php'){echo 'current'; }else { echo ''; } ?>"><a href="course.php">Our Courses <i>::</i> <span>What we do</span></a></li>
</ul><!-- end #dropdown-menu -->
</div><!-- end .span8 -->
add each page
<?php include('common.php'); ?>
This happened to me after a java update, few things to check if you are sure your path has been set before:
if the path doesn't match the latest java install folder, change it (if your in eclipse check the eclipse.ini
too to make sure your using your systems default vm (ie no VM tag) )
go to the java directory, there should be a 'jdk' and a 'jre' in the path, for example:
C:\Program Files (x86)\Java\jdk1.8.0_72\jre
if not you probably installed the JRE only not the JDK that
finally if the lib
folder of the jdk (not jre) doesnt contain tools.jar
then you have a problem with the install
Step 1:
Place debugger
where ever you want to stop script, like:
async saveItem(item, selectedValue) {
debugger
try {
await AsyncStorage.setItem(item, selectedValue);
}
catch (error) {
console.error('AsyncStorage error: ' + error.message);
}
}
This will pause the debugger when ever control comes to this block of code.
Step 2:
Press Cmd+D
on ios emulator and Cmd+M
on Android simulator.
If you are having real device, shake the device to open dev menu, if you don't want to shake device follow this blog
Step 3:
Select Enable Remote JS Debugging
, this will open Chrome
Step 4:
Select Developer Tools.
Step 5:
Your debugger is paused in Sources
tab wherever you have written debugger
within your code . Go to console and type any parameters you want to debug (that are present in the code block) like:
To move to next debugger point again move to Sources -> click on Resume script execution button (Right corner blue button)
Place the debugger, wherever you wanna pause the script.
Enjoy debugging!!
Here's a simple PHP command line script that will do what you need:
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$database = 'database';
$db = mysql_connect($host, $user, $pass);
mysql_query("use $database", $db);
/********************************************************************************/
// Parameters: filename.csv table_name
$argv = $_SERVER[argv];
if($argv[1]) { $file = $argv[1]; }
else {
echo "Please provide a file name\n"; exit;
}
if($argv[2]) { $table = $argv[2]; }
else {
$table = pathinfo($file);
$table = $table['filename'];
}
/********************************************************************************/
// Get the first row to create the column headings
$fp = fopen($file, 'r');
$frow = fgetcsv($fp);
foreach($frow as $column) {
if($columns) $columns .= ', ';
$columns .= "`$column` varchar(250)";
}
$create = "create table if not exists $table ($columns);";
mysql_query($create, $db);
/********************************************************************************/
// Import the data into the newly created table.
$file = $_SERVER['PWD'].'/'.$file;
$q = "load data infile '$file' into table $table fields terminated by ',' ignore 1 lines";
mysql_query($q, $db);
?>
It will create a table based on the first row and import the remaining rows into it. Here is the command line syntax:
php csv_import.php csv_file.csv table_name
Try this:
SElECT * FROM STUDENTS WHERE LEN(CAST(STUDENTID AS VARCHAR)) > 0
With this you get the rows where STUDENTID contains text
To disable (or control disabling), add the following lines to the beginning of /etc/ssh/ssh_config
...
Host 192.168.0.*
StrictHostKeyChecking=no
UserKnownHostsFile=/dev/null
Options:
*
to allow unrestricted access to all IPs./etc/ssh/ssh_config
for global configuration or ~/.ssh/config
for user-specific configuration. See http://linuxcommando.blogspot.com/2008/10/how-to-disable-ssh-host-key-checking.html
Similar question on superuser.com - see https://superuser.com/a/628801/55163
You can just use Arrays#sort()
, it's working perfectly.
See this example :
String [] a = {"English","German","Italian","Korean","Blablablabla.."};
//before sort
for(int i = 0;i<a.length;i++)
{
System.out.println(a[i]);
}
Arrays.sort(a);
System.out.println("After sort :");
for(int i = 0;i<a.length;i++)
{
System.out.println(a[i]);
}
$(document).ready(function() {
$("img").on("contextmenu",function(){
return false;
});
});
And here is a bigint version of the same
DECLARE @ts BIGINT
SET @ts = CAST(CAST(getdate() AS TIMESTAMP) AS BIGINT)
SELECT @ts
I eventually figured it out. Place:
import warnings
warnings.filterwarnings('ignore')
inside ~/.ipython/profile_default/startup/disable-warnings.py
. I'm leaving this question and answer for the record in case anyone else comes across the same issue.
Quite often it is useful to see a warning once. This can be set by:
warnings.filterwarnings(action='once')
You have two options, a PL/SQL block or SQL*Plus bind variables:
var z number
execute my_stored_proc (-1,2,0.01,:z)
print z
How about this one?
function getCookie(k){var v=document.cookie.match('(^|;) ?'+k+'=([^;]*)(;|$)');return v?v[2]:null}
Counted 89 bytes without the function name.
If you don't mind messing with z-index, but you want to avoid adding extra div for overlay, you can use the following approach
/* make sure ::before is positioned relative to .foo */
.foo { position: relative; }
/* overlay */
.foo::before {
content: '';
display: block;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.5);
z-index: 0;
}
/* make sure all elements inside .foo placed above overlay element */
.foo > * { z-index: 1; }
Most likely your sushosin updated, which changed the default of suhosin.memory_limit from disabled to 0 (which won't allow any updates to memory_limit).
On Debian, change /etc/php5/conf.d/suhosin.ini
;suhosin.memory_limit = 0
to
suhosin.memory_limit = 2G
Or whichever value you are comfortable with. You can find the changelog of Sushosin at http://www.hardened-php.net/hphp/changelog.html, which says:
Changed the way the memory_limit protection is implemented
If you want to discard all changes, you can use any of the valid options in an alias in .gitconfig
. For instance:
[alias]
discard = "!f() { git add . && git stash && git stash drop stash@{0}; }; f"
Usage: git discard
Some people may not like it, but this is what I do:
private void StartBackgroundWork() {
if (Application.RenderWithVisualStyles)
progressBar.Style = ProgressBarStyle.Marquee;
else {
progressBar.Style = ProgressBarStyle.Continuous;
progressBar.Maximum = 100;
progressBar.Value = 0;
timer.Enabled = true;
}
backgroundWorker.RunWorkerAsync();
}
private void timer_Tick(object sender, EventArgs e) {
if (progressBar.Value < progressBar.Maximum)
progressBar.Increment(5);
else
progressBar.Value = progressBar.Minimum;
}
The Marquee style requires VisualStyles to be enabled, but it continuously scrolls on its own without needing to be updated. I use that for database operations that don't report their progress.
DTO
is an abbreviation for Data Transfer Object, so it is used to transfer the data between classes and modules of your application.
DTO
should only contain private fields for your data, getters, setters, and constructors.DTO
is not recommended to add business logic methods to such classes, but it is OK to add some util methods.DAO
is an abbreviation for Data Access Object, so it should encapsulate the logic for retrieving, saving and updating data in your data storage (a database, a file-system, whatever).
Here is an example of how the DAO and DTO interfaces would look like:
interface PersonDTO {
String getName();
void setName(String name);
//.....
}
interface PersonDAO {
PersonDTO findById(long id);
void save(PersonDTO person);
//.....
}
The MVC
is a wider pattern. The DTO/DAO would be your model in the MVC pattern.
It tells you how to organize the whole application, not just the part responsible for data retrieval.
As for the second question, if you have a small application it is completely OK, however, if you want to follow the MVC pattern it would be better to have a separate controller, which would contain the business logic for your frame in a separate class and dispatch messages to this controller from the event handlers.
This would separate your business logic from the view.
The behavior depends on which version your repository has. Subversion 1.5 allows 4 types of merge:
Subversion before 1.5 only allowed the first 2 formats.
Technically you can perform all merges with the first two methods, but the last two enable subversion 1.5's merge tracking.
TortoiseSVN's options merge a range or revisions maps to method 3 when your repository is 1.5+ or to method one when your repository is older.
When merging features over to a release/maintenance branch you should use the 'Merge a range of revisions' command.
Only when you want to merge all features of a branch back to a parent branch (commonly trunk) you should look into using 'Reintegrate a branch'.
And the last command -Merge two different trees- is only usefull when you want to step outside the normal branching behavior. (E.g. Comparing different releases and then merging the differenct to yet another branch)
The accepted answer is invalid with the double EXEC (only need the first EXEC):
DECLARE @returnvalue int;
EXEC @returnvalue = SP_SomeProc
PRINT @returnvalue
And you still need to call PRINT (at least in Visual Studio).
Not exactly!!
document.getElementById('contents'); //returns a HTML DOM Object
var contents = $('#contents'); //returns a jQuery Object
In jQuery, to get the same result as document.getElementById
, you can access the jQuery Object and get the first element in the object (Remember JavaScript objects act similar to associative arrays).
var contents = $('#contents')[0]; //returns a HTML DOM Object
The %
operator is for integers. You're looking for the fmod()
function.
#include <cmath>
int main()
{
double x = 6.3;
double y = 2.0;
double z = std::fmod(x,y);
}
What you (probably want) are Flex 2.5.4 (some people are now "maintaining" it and producing newer versions, but IMO they've done more to screw it up than fix any real shortcomings) and byacc 1.9 (likewise). (Edit 2017-11-17: Flex 2.5.4 is not available on Sourceforge any more, and the Flex github repository only goes back to 2.5.5. But you can apparently still get it from a Gnu ftp server at ftp://ftp.gnu.org/old-gnu/gnu-0.2/src/flex-2.5.4.tar.gz.)
Since it'll inevitably be recommended, I'll warn against using Bison. Bison was originally written by Robert Corbett, the same guy who later wrote Byacc, and he openly states that at the time he didn't really know or understand what he was doing. Unfortunately, being young and foolish, he released it under the GPL and now the GPL fans push it as the answer to life's ills even though its own author basically says it should be thought of as essentially a beta test product -- but by the convoluted reasoning of GPL fans, byacc's license doesn't have enough restrictions to qualify as "free"!
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/logout"
android:icon="@drawable/logout"
android:title="Log Out"
app:showAsAction="always"
/>
</menu>
This did the trick for me!