You could query the table_privileges
table in the information schema:
SELECT table_catalog, table_schema, table_name, privilege_type
FROM information_schema.table_privileges
WHERE grantee = 'MY_USER'
I encountered a similar error message. I was able to fix it without enabling remote errors.
In Report Builder 3.0, when I used the Run button to run the report, an error alert appeared, saying
An error has occurred during report processing. (rsProcessingAborted)
[OK] [Details...]
Pressing the details button gave me a text box where I saw this text:
For more information about this error navigate to the report server
on the local server machine, or enable remote errors
----------------------------
Query execution failed for dataset 'DataSet1'. (rsErrorExecutingCommand)
I was confused and frustrated, because my report did not have a dataset named 'DataSet1
'. I even opened the .rdl
file in a text editor to be sure. After a while, I noticed that there was more text in the text box below what I could read. The full error message was:
For more information about this error navigate to the report server
on the local server machine, or enable remote errors
----------------------------
Query execution failed for dataset 'DataSet1'. (rsErrorExecutingCommand)
----------------------------
The execution failed for the shared data set 'CustomerDetailsDataSet'.
(rsDataSetExecutionError)
----------------------------
An error has occurred during report processing. (rsProcessingAborted)
I did have a shared dataset named 'CustomerDetailsDataSet
'. I opened the query (which was a full SQL query entered in text mode) in SQL Server Management Studio, and ran it there. I got error messages which clearly pointed to a certain table, where a column I had been using had been renamed and changed.
From that point, it was straightforward to modify my query so that it worked with the new column, then paste that modification into the shared dataset 'CustomerDetailsDataSet
', and then nudge the report in Report Builder to recognise the change to the shared dataset.
After this fix, my reports no longer triggered this error.
<build>
<plugins>
...
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.3</version>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include> **/*.properties</include>
</includes>
</resource>
</resources>
...
</build>
I am not a fan of bumping old articles but because this was one of the first responses for this particular issue I felt a need to clarify something.
As @Bhavin Shah answer states the domain part of the url is case insensitive, so
http://google.com
and
http://GOOGLE.COM
and
http://GoOgLe.CoM
are all the same but everything after the domain name part is considered case sensitive.
so...
http://GOOGLE.COM/ABOUT
and
http://GOOGLE.COM/about
are different.
Note: I am talking "technically" and not "literally" in a lot of cases, most actually, servers are setup to handle these items the same, but it is possible to set them up so they are NOT handled the same.
Different servers handle this differently and in some cases they Have to be case sensitive. In many cases query string values are encoded (such as Session Ids or Base64 encoded data thats passed as a query string value) These items are case sensitive by their nature so the server has to be case sensitive in handling them.
So to answer the question, "should" servers be case sensitive in grabbing this data, the answer is "yes, most definitely."
Of course not everything needs to be case sensitive but the server should be aware of what that is and how to handle those cases.
@Hart Simha's comment basically says the same thing. I missed it before I posted so I want to give credit where credit is due.
The performance impact depends on the way you lock. You can find a good list of optimizations here: http://www.thinkingparallel.com/2007/07/31/10-ways-to-reduce-lock-contention-in-threaded-programs/
Basically you should try to lock as little as possible, since it puts your waiting code to sleep. If you have some heavy calculations or long lasting code (e.g. file upload) in a lock it results in a huge performance loss.
If anyone is wondering how to set the heading such that it appears with a fixed distance to the left side (and not centered as presented above), I figured that out by modifying @Puigcerber's code.
h1 {
white-space: nowrap;
overflow: hidden;
}
h1:before,
h1:after {
background-color: #000;
content: "";
display: inline-block;
height: 1px;
position: relative;
vertical-align: middle;
}
h1:before {
right: 0.3em;
width: 50px;
}
h1:after {
left: 0.3em;
width: 100%;
}
Here the JSFiddle.
With a null check on the dvdList
and your searchString
if (!StringUtils.isEmpty(searchString)) {
return Optional.ofNullable(dvdList)
.map(Collection::stream)
.orElse(Stream.empty())
.anyMatch(dvd >searchString.equalsIgnoreCase(dvd.getTitle()));
}
You can use the function "=IF(ISERROR(A1);0;A1)" this will show zero if the cell A1 contains an errore or the real value if it doesn't.
A tag is used to label and mark a specific commit in the history.
It is usually used to mark release points (eg. v1.0, etc.).
Although a tag may appear similar to a branch, a tag, however, does not change. It points directly to a specific commit in the history and will not change unless explicitly updated.
You will not be able to checkout the tags if it's not locally in your repository so first, you have to fetch
the tags to your local repository.
First, make sure that the tag exists locally by doing
# --all will fetch all the remotes.
# --tags will fetch all tags as well
$ git fetch --all --tags --prune
Then check out the tag by running
$ git checkout tags/<tag_name> -b <branch_name>
Instead of origin
use the tags/
prefix.
In this sample you have 2 tags version 1.0 & version 1.1 you can check them out with any of the following:
$ git checkout A ...
$ git checkout version 1.0 ...
$ git checkout tags/version 1.0 ...
All of the above will do the same since the tag is only a pointer to a given commit.
origin: https://backlog.com/git-tutorial/img/post/stepup/capture_stepup4_1_1.png
# list all tags
$ git tag
# list all tags with given pattern ex: v-
$ git tag --list 'v-*'
There are 2 ways to create a tag:
# lightweight tag
$ git tag
# annotated tag
$ git tag -a
The difference between the 2 is that when creating an annotated tag you can add metadata as you have in a git commit:
name, e-mail, date, comment & signature
$ git tag -d <tag_name>
Deleted tag <tag_name> (was 000000)
Note: If you try to delete a non existig Git tag, there will be see the following error:
$ git tag -d <tag_name>
error: tag '<tag_name>' not found.
# Delete a tag from the server with push tags
$ git push --delete origin <tag name>
In order to grab the content of a given tag, you can use the checkout
command. As explained above tags are like any other commits so we can use checkout
and instead of using the SHA-1 simply replacing it with the tag_name
Option 1:
# Update the local git repo with the latest tags from all remotes
$ git fetch --all
# checkout the specific tag
$ git checkout tags/<tag> -b <branch>
Option 2:
Since git supports shallow clone by adding the --branch
to the clone command we can use the tag name instead of the branch name. Git knows how to "translate" the given SHA-1 to the relevant commit
# Clone a specific tag name using git clone
$ git clone <url> --branch=<tag_name>
git clone --branch=
--branch
can also take tags and detaches the HEAD at that commit in the resulting repository.
git push --tags
To push all tags:
# Push all tags
$ git push --tags
refs/tags
instead of just specifying the <tagname>
.Why?
refs/tags
since sometimes tags can have the same name as your branches and a simple git push will push the branch instead of the tagTo push annotated tags and current history chain tags use:
git push --follow-tags
This flag --follow-tags
pushes both commits and only tags that are both:
From Git 2.4 you can set it using configuration
$ git config --global push.followTags true
Create a "module" object and declare variables in there. Unlike class-objects that have to be instantiated each time, the module objects are always available. Therefore, a public variable, function, or property in a "module" will be available to all the other objects in the VBA project, macro, Excel formula, or even within a MS Access JET-SQL query def.
As we all know MySQL was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0 ref so I have converted accepted answer to mysqli.
<?php
// Name of the file
$filename = 'db.sql';
// MySQL host
$mysql_host = 'localhost';
// MySQL username
$mysql_username = 'root';
// MySQL password
$mysql_password = '123456';
// Database name
$mysql_database = 'mydb';
$connection = mysqli_connect($mysql_host,$mysql_username,$mysql_password,$mysql_database) or die(mysqli_error($connection));
// Temporary variable, used to store current query
$templine = '';
// Read in entire file
$lines = file($filename);
// Loop through each line
foreach ($lines as $line)
{
// Skip it if it's a comment
if (substr($line, 0, 2) == '--' || $line == '')
continue;
// Add this line to the current segment
$templine .= $line;
// If it has a semicolon at the end, it's the end of the query
if (substr(trim($line), -1, 1) == ';')
{
// Perform the query
mysqli_query($connection,$templine) or print('Error performing query \'<strong>' . $templine . '\': ' . mysqli_error($connection) . '<br /><br />');
// Reset temp variable to empty
$templine = '';
}
}
echo "Tables imported successfully";
?>
Depends on if the form that the select is contained in has the method set to "get" or "post".
If <form method="get">
then the value of the select will be located in the super global array $_GET['taskOption']
.
If <form method="post">
then the value of the select will be located in the super global array $_POST['taskOption']
.
To store it into a variable you would:
$option = $_POST['taskOption']
A good place for more information would be the PHP manual: http://php.net/manual/en/tutorial.forms.php
An established connection was aborted by the software in your host machine
That is a boiler-plate error message, it comes out of Windows. The underlying error code is WSAECONNABORTED. Which really doesn't mean more than "connection was aborted". You have to be a bit careful about the "your host machine" part of the phrase. In the vast majority of Windows application programs, it is indeed the host that the desktop app is connected to that aborted the connection. Usually a server somewhere else.
The roles are reversed however when you implement your own server. Now you need to read the error message as "aborted by the application at the other end of the wire". Which is of course not uncommon when you implement a server, client programs that use your server are not unlikely to abort a connection for whatever reason. It can mean that a fire-wall or a proxy terminated the connection but that's not very likely since they typically would not allow the connection to be established in the first place.
You don't really know why a connection was aborted unless you have insight what is going on at the other end of the wire. That's of course hard to come by. If your server is reachable through the Internet then don't discount the possibility that you are being probed by a port scanner. Or your customers, looking for a game cheat.
Use this code it will help you.
<script>
InitializeDate();
</script>
<input type="text" id="txtFromDate" class="datepicker calendar-icon" placeholder="From Date" style="width: 100px; margin-right: 10px; padding: 0px 0px 0px 7px;">
<input type="text" id="txtToDate" class="datepicker calendar-icon" placeholder="To Date" style="width: 100px; margin-right: 10px; padding: 0px 0px 0px 7px;">
function InitializeDate() {
var date = new Date();
var dd = date.getDate();
var mm = date.getMonth() + 1;
var yyyy = date.getFullYear();
var ToDate = mm + '/' + dd + '/' + yyyy;
var FromDate = mm + '/01/' + yyyy;
$('#txtToDate').datepicker('setDate', ToDate);
$('#txtFromDate').datepicker('setDate', FromDate);
}
If you want to complete both these steps with a single command, you can make an alias for it by adding the below to your ~/.gitconfig
:
[alias]
rmbranch = "!f(){ git branch -d ${1} && git push origin --delete ${1}; };f"
Alternatively, you can add this to your global configuration from the command line using
git config --global alias.rmbranch \
'!f(){ git branch -d ${1} && git push origin --delete ${1}; };f'
NOTE: If using -d
(lowercase d), the branch will only be deleted if it has been merged. To force the delete to happen, you will need to use -D
(uppercase D).
Your error is posted in the official documentation. You can read this article.
I have copied the reason for you (and hyperlinked the URLs) from that article:
This will happen if the administrator has not created a PostgreSQL user account for you. (PostgreSQL user accounts are distinct from operating system user accounts.) If you are the administrator, see Chapter 20 for help creating accounts. You will need to become the operating system user under which PostgreSQL was installed (usually postgres) to create the first user account. It could also be that you were assigned a PostgreSQL user name that is different from your operating system user name; in that case you need to use the -U switch or set the PGUSER environment variable to specify your PostgreSQL user name
For your purposes, you can do:
1) Create a PostgreSQL user account:
sudo -u postgres createuser tom -d -P
(the -P
option to set a password; the -d
option for allowing the creation of database for your username 'tom'. Note that 'tom' is your operating system username. That way, you can execute PostgreSQL commands without sudo
ing.)
2) Now you should be able to execute createdb
and other PostgreSQL commands.
In SQL 2012+, you can use THROW.
THROW 51000, 'Stopping execution because validation failed.', 0;
PRINT 'Still Executing'; -- This doesn't execute with THROW
From MSDN:
Raises an exception and transfers execution to a CATCH block of a TRY…CATCH construct ... If a TRY…CATCH construct is not available, the session is ended. The line number and procedure where the exception is raised are set. The severity is set to 16.
I would stack generator expressions:
with open(filename) as f_in:
lines = (line.rstrip() for line in f_in) # All lines including the blank ones
lines = (line for line in lines if line) # Non-blank lines
Now, lines
is all of the non-blank lines. This will save you from having to call strip on the line twice. If you want a list of lines, then you can just do:
with open(filename) as f_in:
lines = (line.rstrip() for line in f_in)
lines = list(line for line in lines if line) # Non-blank lines in a list
You can also do it in a one-liner (exluding with
statement) but it's no more efficient and harder to read:
with open(filename) as f_in:
lines = list(line for line in (l.strip() for l in f_in) if line)
I agree that this is ugly because of the repetition of tokens. You could just write a generator if you prefer:
def nonblank_lines(f):
for l in f:
line = l.rstrip()
if line:
yield line
Then call it like:
with open(filename) as f_in:
for line in nonblank_lines(f_in):
# Stuff
with open(filename) as f_in:
lines = filter(None, (line.rstrip() for line in f_in))
and on CPython (with deterministic reference counting)
lines = filter(None, (line.rstrip() for line in open(filename)))
In Python 2 use itertools.ifilter
if you want a generator and in Python 3, just pass the whole thing to list
if you want a list.
Static memory allocation: The compiler allocates the required memory space for a declared variable.By using the address of operator,the reserved address is obtained and this address may be assigned to a pointer variable.Since most of the declared variable have static memory,this way of assigning pointer value to a pointer variable is known as static memory allocation. memory is assigned during compilation time.
Dynamic memory allocation: It uses functions such as malloc( ) or calloc( ) to get memory dynamically.If these functions are used to get memory dynamically and the values returned by these functions are assingned to pointer variables, such assignments are known as dynamic memory allocation.memory is assined during run time.
if you inistalled mysql Independently you can stop mysql service if running no one of these answers are worked for me this work for me
For Linux, the following list of papers might be useful:
Personally, whilst Dummynet is good, I find NetEm to be the most versatile for my use-cases; I'm usually interested in the effect of delays, rather than bandwidth (i.e. WiFi connection issues), and it's super-easy to emulate random packet loss/corruption, etc. It's also very accessible, and free (unlike the hardware-based Linktropy).
On a side-note, for Windows, Clumsy is awesome. I would also like to add that (regarding websites) browser throttling is not an accurate method for emulating real-life network issues (I think "TKK" commented on a few of the reasons why above).
Hope this helps someone!
What worked for me was restarting Visual Studio.
I tried manually rebuilding, performing a clean and rebuild, and deleting the bin folder all of which did not work. My output path was already set to bin\
git log --oneline | grep PATTERN
regular view----->short name for a query,no additional space is used here
Materialised view---->similar to creating table whose data will refresh periodically based on data query used for creating the view
Concatenation of a string and integer is simple: just use
abhishek+str(2)
I either want my or their version in full, or want to review individual changes and decide for each of them.
Fully accept my or theirs version:
Accept my version (local, ours):
git checkout --ours -- <filename>
git add <filename> # Marks conflict as resolved
git commit -m "merged bla bla" # An "empty" commit
Accept their version (remote, theirs):
git checkout --theirs -- <filename>
git add <filename>
git commit -m "merged bla bla"
If you want to do for all conflict files run:
git merge --strategy-option ours
or
git merge --strategy-option theirs
Review all changes and accept them individually
git mergetool
git add <filename>
git commit -m "merged bla bla"
Default mergetool
works in command line. How to use a command line mergetool should be a separate question.
You can also install visual tool for this, e.g. meld
and run
git mergetool -t meld
It will open local version (ours), "base" or "merged" version (the current result of the merge) and remote version (theirs). Save the merged version when you are finished, run git mergetool -t meld
again until you get "No files need merging", then go to Steps 3. and 4.
just to be pythonic :-)
>>> x = ['a1sd','23df','aaa','ccc','rrrr', 'ssss', 'e', '']
>>> [x[i] + x[i+1] for i in range(0,len(x),2)]
['a1sd23df', 'aaaccc', 'rrrrssss', 'e']
in case the you want to be alarmed if the list length is odd you can try:
[x[i] + x[i+1] if not len(x) %2 else 'odd index' for i in range(0,len(x),2)]
Best of Luck
I think this one is simple enough to understand:
function fibonacci(limit) {
let result = [0, 1];
for (var i = 2; i < limit; i++) {
result[result.length] = result[result.length - 1] + result[result.length - 2];
}
return result;
}
// [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
console.log(fibonacci(10));
You need to implement the equals() method in your MyClass
.
The reason that ==
didn't work is this is checking that they refer to the same instance. Since you did new
for each, each one is a different instance.
The reason that equals()
didn't work is because you didn't implement it yourself yet. I believe it's default behavior is the same thing as ==
.
Note that you should also implement hashcode()
if you're going to implement equals()
because a lot of java.util Collections expect that.
You can also use a conditional lookup using .loc
as seen here:
df.loc[df[<some_column_name>] == <condition>, [<another_column_name>]] = <value_to_add>
where <some_column_name
is the column you want to check the <condition>
variable against and <another_column_name>
is the column you want to add to (can be a new column or one that already exists). <value_to_add>
is the value you want to add to that column/row.
This example doesn't work precisely with the question at hand, but it might be useful for someone wants to add a specific value based on a condition.
After you add some stuff... commit them and after all finished push it! BANG!! Start all problems... As you should notice there are some differences in the way both new and existent projects were defined. If some other person tries to add/commit/push same files, or content (git keep both as same objects), we will face the following error:
$ git push
Counting objects: 31, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (17/17), done.
Writing objects: 100% (21/21), 2.07 KiB | 0 bytes/s, done.
Total 21 (delta 12), reused 0 (delta 0)
remote: error: insufficient permission for adding an object to repository database ./objects remote: fatal: failed to write object
To solve this problem you have to have something in mind operational system's permissions system as you are restricted by it in this case. Tu understand better the problem, go ahead and check your git object's folder (.git/objects). You will probably see something like that:
<your user_name>@<the machine name> objects]$ ls -la
total 200
drwxr-xr-x 25 <your user_name> <group_name> 2048 Feb 10 09:28 .
drwxr-xr-x 3 <his user_name> <group_name> 1024 Feb 3 15:06 ..
drwxr-xr-x 2 <his user_name> <group_name> 1024 Jan 31 13:39 02
drwxr-xr-x 2 <his user_name> <group_name> 1024 Feb 3 13:24 08
*Note that those file's permissions were granted only for your users, no one will never can changed it... *
Level u g o
Permission rwx r-x ---
Binary 111 101 000
Octal 7 5 0
SOLVING THE PROBLEM
If you have super user permission, you can go forward and change all permissions by yourself using the step two, in any-other case you will need to ask all users with objects created with their users, use the following command to know who they are:
$ ls -la | awk '{print $3}' | sort -u
<your user_name>
<his user_name>
Now you and all file's owner users will have to change those files permission, doing:
$ chmod -R 774 .
After that you will need to add a new property that is equivalent to --shared=group done for the new repository, according to the documentation, this make the repository group-writable, do it executing:
$ git config core.sharedRepository group
/C
Carries out the command specified by the string and then terminates.
You can get all the cmd command line switches by typing cmd /?
.
I don't try changing sequence via setval
. But using ALTER
I was issued how to write sequence name properly. And this only work for me:
Check required sequence name using SELECT * FROM information_schema.sequences;
ALTER SEQUENCE public."table_name_Id_seq" restart {number};
In my case it was ALTER SEQUENCE public."Services_Id_seq" restart 8;
Also there is a page on wiki.postgresql.org where describes a way to generate sql script to fix sequences in all database tables at once. Below the text from link:
Save this to a file, say 'reset.sql'
SELECT 'SELECT SETVAL(' || quote_literal(quote_ident(PGT.schemaname) || '.' || quote_ident(S.relname)) || ', COALESCE(MAX(' ||quote_ident(C.attname)|| '), 1) ) FROM ' || quote_ident(PGT.schemaname)|| '.'||quote_ident(T.relname)|| ';' FROM pg_class AS S, pg_depend AS D, pg_class AS T, pg_attribute AS C, pg_tables AS PGT WHERE S.relkind = 'S' AND S.oid = D.objid AND D.refobjid = T.oid AND D.refobjid = C.attrelid AND D.refobjsubid = C.attnum AND T.relname = PGT.tablename ORDER BY S.relname;
Run the file and save its output in a way that doesn't include the usual headers, then run that output. Example:
psql -Atq -f reset.sql -o temp psql -f temp rm temp
And the output will be a set of sql commands which look exactly like this:
SELECT SETVAL('public."SocialMentionEvents_Id_seq"', COALESCE(MAX("Id"), 1) ) FROM public."SocialMentionEvents";
SELECT SETVAL('public."Users_Id_seq"', COALESCE(MAX("Id"), 1) ) FROM public."Users";
Here is my sample how I use it. For the css/less task. Can be applied for all.
var cssTask = function (options) {
var minifyCSS = require('gulp-minify-css'),
less = require('gulp-less'),
src = cssDependencies;
src.push(codePath + '**/*.less');
var run = function () {
var start = Date.now();
console.log('Start building CSS/LESS bundle');
gulp.src(src)
.pipe(gulpif(options.devBuild, plumber({
errorHandler: onError
})))
.pipe(concat('main.css'))
.pipe(less())
.pipe(gulpif(options.minify, minifyCSS()))
.pipe(gulp.dest(buildPath + 'css'))
.pipe(gulpif(options.devBuild, browserSync.reload({stream:true})))
.pipe(notify(function () {
console.log('END CSS/LESS built in ' + (Date.now() - start) + 'ms');
}));
};
run();
if (options.watch) {
gulp.watch(src, run);
}
};
gulp.task('dev', function () {
var options = {
devBuild: true,
minify: false,
watch: false
};
cssTask (options);
});
You asked for a combination of quick, nice, no use of a boolean, no use of goto, and C#. You've ruled out all possible ways of doing what you want.
The most quick and least ugly way is to use a goto.
Having just read this thread and been disappointed that it wasn't easy to just to this "UPSERT"ing, I investigated further...
You can actually do this directly and easily in SQLITE.
Instead of using: INSERT INTO
Use: INSERT OR REPLACE INTO
This does exactly what you want it to do!
Try this
new_df = pd.merge(A_df, B_df, how='left', left_on=['A_c1','c2'], right_on = ['B_c1','c2'])
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html
left_on : label or list, or array-like Field names to join on in left DataFrame. Can be a vector or list of vectors of the length of the DataFrame to use a particular vector as the join key instead of columns
right_on : label or list, or array-like Field names to join on in right DataFrame or vector/list of vectors per left_on docs
I got a similar error (Incorrect string value: '\xD0\xBE\xDO\xB2. ...' for 'content' at row 1
). I have tried to change character set of column to utf8mb4
and after that the error has changed to 'Data too long for column 'content' at row 1'
.
It turned out that mysql shows me wrong error. I turned back character set of column to utf8
and changed type of the column to MEDIUMTEXT
. After that the error disappeared.
I hope it helps someone.
By the way MariaDB in same case (I have tested the same INSERT there) just cut a text without error.
This is a bit late but I know it will help someone:
If you are using datetimepicker
make sure you include the right CSS and JS files. datetimepicker
uses(Take note of their names);
and
On the above question asked by @mindfreak,The main problem is due to the imported files.
EDIT
var utcDate = new Date(incomingUTCepoch);
var date = new Date();
date.setUTCDate(utcDate.getDate());
date.setUTCHours(utcDate.getHours());
date.setUTCMonth(utcDate.getMonth());
date.setUTCMinutes(utcDate.getMinutes());
date.setUTCSeconds(utcDate.getSeconds());
date.setUTCMilliseconds(utcDate.getMilliseconds());
EDIT fixed
This worked for me.
In php.ini
file, change the following property.
Before:
mbstring.encoding_transration = On
After:
mbstring.encoding_transration = Off
UNIX timestamp it is count of seconds from 1970, so you need to convert it to JS Date object:
var date = new Date(unixTimestamp*1000);
I use this method for logging when I want to quickly optimize different page loads. It's a little tip...
Logging to a TABLE
SET global general_log = 1;
SET global log_output = 'table';
You can then select from my mysql.general_log
table to retrieve recent queries.
I can then do something similar to tail -f
on the mysql.log, but with more refinements...
select * from mysql.general_log
where event_time > (now() - INTERVAL 8 SECOND) and thread_id not in(9 , 628)
and argument <> "SELECT 1" and argument <> ""
and argument <> "SET NAMES 'UTF8'" and argument <> "SHOW STATUS"
and command_type = "Query" and argument <> "SET PROFILING=1"
This makes it easy to see my queries that I can try and cut back. I use 8 seconds interval to only fetch queries executed within the last 8 seconds.
I believe you are now able to use Window.getComputedStyle()
var style = window.getComputedStyle(element[, pseudoElt]);
Example to get width of an element:
window.getComputedStyle(document.querySelector('#mainbar')).width
Array indexes in JavaScript start at zero for the first item, so try this:
var firstArrayItem = myValues[0]
Of course, if you actually want the second item in the array at index 1, then it's myValues[1]
.
See Accessing array elements for more info.
html5mode
= false
?All of the other answers work only when Angular's html5mode
is true
. If you're working outside of html5mode
, then $location
refers only to the "fake" location that lives in your hash -- and so $location.search
can't see/edit/fix the actual page's search params.
Here's a workaround, to be inserted in the HTML of the page before angular loads:
<script>
if (window.location.search.match("code=")){
var newHash = "/after-auth" + window.location.search;
if (window.history.replaceState){
window.history.replaceState( {}, "", window.location.toString().replace(window.location.search, ""));
}
window.location.hash = newHash;
}
</script>
Let us say your table has following fields:
( pk_id int not null auto_increment primary key,
col1 int,
col2 varchar(10)
)
then, to copy values from one row to the other row with new key value, following query may help
insert into my_table( col1, col2 ) select col1, col2 from my_table where pk_id=?;
This will generate a new value for pk_id
field and copy values from col1
, and col2
of the selected row.
You can extend this sample to apply for more fields in the table.
UPDATE:
In due respect to the comments from JohnP and Martin -
We can use temporary table to buffer first from main table and use it to copy to main table again. Mere update of pk reference field in temp table will not help as it might already be present in the main table. Instead we can drop the pk field from the temp table and copy all other to the main table.
With reference to the answer by Tim Ruehsen in the referred posting:
CREATE TEMPORARY TABLE tmp SELECT * from my_table WHERE ...;
ALTER TABLE tmp drop pk_id; # drop autoincrement field
# UPDATE tmp SET ...; # just needed to change other unique keys
INSERT INTO my_table SELECT 0,tmp.* FROM tmp;
DROP TEMPORARY TABLE tmp;
Hope this helps.
You might encounter one of these three problems:
A blog post with the summary for all three possible problems might be found here: https://cms4j.wordpress.com/2016/11/29/0x851c0001-the-credentials-you-provided-for-the-sqlserveragent-service-is-invalid/
Setting android:layout_gravity="bottom|right"
worked for me
Use localhost
instead of 127.0.0.1
(in your .env file), then run command:
php artisan config:cache
Why am I unable to use a string for a newline in write() but I can use it in writelines()?
The idea is the following: if you want to write a single string you can do this with write()
. If you have a sequence of strings you can write them all using writelines()
.
write(arg)
expects a string as argument and writes it to the file. If you provide a list of strings, it will raise an exception (by the way, show errors to us!).
writelines(arg)
expects an iterable as argument (an iterable object can be a tuple, a list, a string, or an iterator in the most general sense). Each item contained in the iterator is expected to be a string. A tuple of strings is what you provided, so things worked.
The nature of the string(s) does not matter to both of the functions, i.e. they just write to the file whatever you provide them. The interesting part is that writelines()
does not add newline characters on its own, so the method name can actually be quite confusing. It actually behaves like an imaginary method called write_all_of_these_strings(sequence)
.
What follows is an idiomatic way in Python to write a list of strings to a file while keeping each string in its own line:
lines = ['line1', 'line2']
with open('filename.txt', 'w') as f:
f.write('\n'.join(lines))
This takes care of closing the file for you. The construct '\n'.join(lines)
concatenates (connects) the strings in the list lines
and uses the character '\n' as glue. It is more efficient than using the +
operator.
Starting from the same lines
sequence, ending up with the same output, but using writelines()
:
lines = ['line1', 'line2']
with open('filename.txt', 'w') as f:
f.writelines("%s\n" % l for l in lines)
This makes use of a generator expression and dynamically creates newline-terminated strings. writelines()
iterates over this sequence of strings and writes every item.
Edit: Another point you should be aware of:
write()
and readlines()
existed before writelines()
was introduced. writelines()
was introduced later as a counterpart of readlines()
, so that one could easily write the file content that was just read via readlines()
:
outfile.writelines(infile.readlines())
Really, this is the main reason why writelines
has such a confusing name. Also, today, we do not really want to use this method anymore. readlines()
reads the entire file to the memory of your machine before writelines()
starts to write the data. First of all, this may waste time. Why not start writing parts of data while reading other parts? But, most importantly, this approach can be very memory consuming. In an extreme scenario, where the input file is larger than the memory of your machine, this approach won't even work. The solution to this problem is to use iterators only. A working example:
with open('inputfile') as infile:
with open('outputfile') as outfile:
for line in infile:
outfile.write(line)
This reads the input file line by line. As soon as one line is read, this line is written to the output file. Schematically spoken, there always is only one single line in memory (compared to the entire file content being in memory in case of the readlines/writelines approach).
I don't have reputation to comment yet, but I want to add to alko answer for further reference.
From the docs:
skiprows: A collection of numbers for rows in the file to skip. Can also be an integer to skip the first n rows
In case if you use new swift version.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ChannelMoreSegue" {
}
}
You can try importing them and then handle the ImportError if the module doesn't exist.
try:
import numpy
except ImportError:
print "numpy is not installed"
Low Coupling:-- Will keep it very simple. If you change your module how does it impact other modules.
Example:- If your service API is exposed as JAR, any change to method signature will break calling API (High/Tight coupling).
If your module and other module communicate via async messages. As long as you get messages, your method change signature will be local to your module (Low coupling).
Off-course if there is change in message format, calling client will need to make some change.
Sure. In this case, you'd just do:
length_key = len(d['key']) # length of the list stored at `'key'` ...
It's hard to say why you actually want this, but, perhaps it would be useful to create another dict that maps the keys to the length of values:
length_dict = {key: len(value) for key, value in d.items()}
length_key = length_dict['key'] # length of the list stored at `'key'` ...
Let's look at one of the most popular SPA sites, GMail.
1. SPA is extremely good for very responsive sites:
Server-side rendering is not as hard as it used to be with simple techniques like keeping a #hash in the URL, or more recently HTML5 pushState
. With this approach the exact state of the web app is embedded in the page URL. As in GMail every time you open a mail a special hash tag is added to the URL. If copied and pasted to other browser window can open the exact same mail (provided they can authenticate). This approach maps directly to a more traditional query string, the difference is merely in the execution. With HTML5 pushState() you can eliminate the #hash
and use completely classic URLs which can resolve on the server on the first request and then load via ajax on subsequent requests.
2. With SPA we don't need to use extra queries to the server to download pages.
The number of pages user downloads during visit to my web site?? really how many mails some reads when he/she opens his/her mail account. I read >50 at one go. now the structure of the mails is almost the same. if you will use a server side rendering scheme the server would then render it on every request(typical case). - security concern - you should/ should not keep separate pages for the admins/login that entirely depends upon the structure of you site take paytm.com for example also making a web site SPA does not mean that you open all the endpoints for all the users I mean I use forms auth with my spa web site. - in the probably most used SPA framework Angular JS the dev can load the entire html temple from the web site so that can be done depending on the users authentication level. pre loading html for all the auth types isn't SPA.
3. May be any other advantages? Don't hear about any else..
Advantages that I can think of are:
Updates from Comments
It doesn't seem like anyone mentioned about sockets and long-polling. If you log out from another client say mobile app, then your browser should also log out. If you don't use SPA, you have to re-create the socket connection every time there is a redirect. This should also work with any updates in data like notifications, profile update etc
An alternate perspective: Aside from your website, will your project involve a native mobile app? If yes, you are most likely going to be feeding raw data to that native app from a server (ie JSON) and doing client-side processing to render it, correct? So with this assertion, you're ALREADY doing a client-side rendering model. Now the question becomes, why shouldn't you use the same model for the website-version of your project? Kind of a no-brainer. Then the question becomes whether you want to render server-side pages only for SEO benefits and convenience of shareable/bookmarkable URLs
Well, if you want it done from the client side using only a browser you have jcrawl.com. After having designed your scrapping service from the web application (http://www.jcrawl.com/app.html), you only need to add the generated script to an HTML page to start using/presenting your data.
All the scrapping logic happens on the the browser via JavaScript. I hope you find it useful. Click this link for a live example that extracts the latest news from Yahoo tennis.
I've found that the jQuery Calendar plugin, for me at least, in general just works better for selecting dates.
If with the word "anywhere" you mean without having an explicit Context
(for example from a background thread) you should define a class in your project like:
public class MyApp extends Application {
private static MyApp instance;
public static MyApp getInstance() {
return instance;
}
public static Context getContext(){
return instance;
// or return instance.getApplicationContext();
}
@Override
public void onCreate() {
instance = this;
super.onCreate();
}
}
Then in your manifest
you need to add this class to the Name
field at the Application
tab. Or edit the xml and put
<application
android:name="com.example.app.MyApp"
android:icon="@drawable/icon"
android:label="@string/app_name"
.......
<activity
......
and then from anywhere you can call
String packagename= MyApp.getContext().getPackageName();
Hope it helps.
SparkSQl support writing programs using Dataset and Dataframe API, along with it need to support sql.
In order to support Sql on DataFrames, first it requires a table definition with column names are required, along with if it creates tables the hive metastore will get lot unnecessary tables, because Spark-Sql natively resides on hive. So it will create a temporary view, which temporarily available in hive for time being and used as any other hive table, once the Spark Context stop it will be removed.
In order to create the view, developer need an utility called createOrReplaceTempView
check the link below, it has the html, css, JS and a live demo :) enjoy
http://codepen.io/senff/pen/ayGvD
// Create a clone of the menu, right next to original._x000D_
$('.menu').addClass('original').clone().insertAfter('.menu').addClass('cloned').css('position','fixed').css('top','0').css('margin-top','0').css('z-index','500').removeClass('original').hide();_x000D_
_x000D_
scrollIntervalID = setInterval(stickIt, 10);_x000D_
_x000D_
_x000D_
function stickIt() {_x000D_
_x000D_
var orgElementPos = $('.original').offset();_x000D_
orgElementTop = orgElementPos.top; _x000D_
_x000D_
if ($(window).scrollTop() >= (orgElementTop)) {_x000D_
// scrolled past the original position; now only show the cloned, sticky element._x000D_
_x000D_
// Cloned element should always have same left position and width as original element. _x000D_
orgElement = $('.original');_x000D_
coordsOrgElement = orgElement.offset();_x000D_
leftOrgElement = coordsOrgElement.left; _x000D_
widthOrgElement = orgElement.css('width');_x000D_
_x000D_
$('.cloned').css('left',leftOrgElement+'px').css('top',0).css('width',widthOrgElement+'px').show();_x000D_
$('.original').css('visibility','hidden');_x000D_
} else {_x000D_
// not scrolled past the menu; only show the original menu._x000D_
$('.cloned').hide();_x000D_
$('.original').css('visibility','visible');_x000D_
}_x000D_
}
_x000D_
* {font-family:arial; margin:0; padding:0;}_x000D_
.logo {font-size:40px; font-weight:bold;color:#00a; font-style:italic;}_x000D_
.intro {color:#777; font-style:italic; margin:10px 0;}_x000D_
.menu {background:#00a; color:#fff; height:40px; line-height:40px;letter-spacing:1px; width:100%;}_x000D_
.content {margin-top:10px;}_x000D_
.menu-padding {padding-top:40px;}_x000D_
.content {padding:10px;}_x000D_
.content p {margin-bottom:20px;}
_x000D_
<div class="intro">Some tagline goes here</div>
_x000D_
I know that this is an old question, but Google threw me here and I think I found a simpler answer.
In Railscasts #179, Ryan Bates used the Ruby standard class OpenURI to do much of what was asked like this:
(Warning: untested code. You might need to change/tweak it.)
require 'open-uri'
File.open("/my/local/path/sample.flv", "wb") do |saved_file|
# the following "open" is provided by open-uri
open("http://somedomain.net/flv/sample/sample.flv", "rb") do |read_file|
saved_file.write(read_file.read)
end
end
I don't think using one printf
statement to print string literals as seen above is a good programming practice; rather, one can use the piece of code below:
printf("name: %s\t",sp->name);
printf("args: %s\t",sp->args);
printf("value: %s\t",sp->value);
printf("arraysize: %s\t",sp->name);
{% for i in range(10) %}
{{ i }}
{% endfor %}
You can try this:table1.GroupBy(t => t.Text).Select(shape => shape.r)).Distinct();
As an alternative to the other answers, it's possible to do this with a syntax similar to the way you originally intended if you do it via a case
statement rather than an if
:
session := Session{}
switch {
case Session{} == session:
fmt.Println("zero")
default:
fmt.Println("not zero")
}
For asp.net users, the .NET framework provides a class to create a content disposition header: System.Net.Mime.ContentDisposition
Basic usage:
var cd = new System.Net.Mime.ContentDisposition();
cd.FileName = "myFile.txt";
cd.ModificationDate = DateTime.UtcNow;
cd.Size = 100;
Response.AppendHeader("content-disposition", cd.ToString());
Neither. You should separate content and presentation, giving your HTML code logical codes. Think of it this way; to a blind person, or on a browser that cannot display colors, what is left of your code? Why do you want it to be red?
Most probably, your decision to make text red is because you want to give it emphasis. So your HTML code should be:
<em>test</em>
This way, even non-visual browsers can make sure they give the text emphasis in one way or another.
Next step is to make the text red. But you don't want to add the color code everywhere, much more efficient to just add it once:
<style>
em { color: red; }
</style>
This way, all emphasized code on your website becomes red, making it more constant.
To rebase the current local tracker branch moving local changes on top of the latest remote state:
$ git fetch && git rebase
More generally, to fast-forward and drop the local changes (hard reset)*:
$ git fetch && git checkout ${the_branch_name} && git reset --hard origin/${the_branch_name}
to fast-forward and keep the local changes (rebase):
$ git fetch && git checkout ${the_branch_name} && git rebase origin/${the_branch_name}
* - to undo the change caused by unintentional hard reset first do git reflog
, that displays the state of the HEAD in reverse order, find the hash the HEAD was pointing to before the reset operation (usually obvious) and hard reset the branch to that hash.
In such cases, you are better off re-adding the whitespace which makes the syntax error immediate apparent:
function(){
if(xmlhttp.readyState==4&&xmlhttp.status==200){
document.getElementById("content").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","data/"+id+".html",true);xmlhttp.send();
}
There's a } too many. Also, after the closing } of the function, you should add a ; before the xmlhttp.open()
And finally, I don't see what that anonymous function does up there. It's never executed or referenced. Are you sure you pasted the correct code?
There are two options. The first (and better) one is using the Fetch as Google option in Webmaster Tools that Mike Flynn commented about. Here are detailed instructions:
With the option above, as long as every page can be reached from some link on the initial page or a page that it links to, Google should recrawl the whole thing. If you want to explicitly tell it a list of pages to crawl on the domain, you can follow the directions to submit a sitemap.
Your second (and generally slower) option is, as seanbreeden pointed out, submitting here: http://www.google.com/addurl/
Update 2019:
.parent {
margin:0 auto;
width:700px;
border:2px solid red;
}
.child {
position:absolute;
width:100%;
border:2px solid blue;
left:0;
top:200px;
}
About access
<ol class="viewer-nav">
<li *ngFor="let section of sections"
[attr.data-sectionvalue]="section.value"
(click)="get_data($event)">
{{ section.text }}
</li>
</ol>
And
get_data(event) {
console.log(event.target.dataset.sectionvalue)
}
unsorted_list.sort(key=lambda x: x[3])
use dataGridView1.Refresh();
:)
Here is my way how do I restore the data without looseness from latin1 to utf8:
/**
* Fixes the data in the database that was inserted into latin1 table using utf8 encoding.
*
* DO NOT execute "SET NAMES UTF8" after mysql_connect.
* Your encoding should be the same as when you firstly inserted the data.
* In my case I inserted all my utf8 data into LATIN1 tables.
* The data in tables was like ДЕТСКИÐ.
* But my page presented the data correctly, without "SET NAMES UTF8" query.
* But phpmyadmin did not present it correctly.
* So this is hack how to convert your data to the correct UTF8 format.
* Execute this code just ONCE!
* Don't forget to make backup first!
*/
public function fixIncorrectUtf8DataInsertedByLatinEncoding() {
// mysql_query("SET NAMES LATIN1") or die(mysql_error()); #uncomment this if you already set UTF8 names somewhere
// get all tables in the database
$tables = array();
$query = mysql_query("SHOW TABLES");
while ($t = mysql_fetch_row($query)) {
$tables[] = $t[0];
}
// you need to set explicit tables if not all tables in your database are latin1 charset
// $tables = array('mytable1', 'mytable2', 'mytable3'); # uncomment this if you want to set explicit tables
// duplicate tables, and copy all data from the original tables to the new tables with correct encoding
// the hack is that data retrieved in correct format using latin1 names and inserted again utf8
foreach ($tables as $table) {
$temptable = $table . '_temp';
mysql_query("CREATE TABLE $temptable LIKE $table") or die(mysql_error());
mysql_query("ALTER TABLE $temptable CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci") or die(mysql_error());
$query = mysql_query("SELECT * FROM `$table`") or die(mysql_error());
mysql_query("SET NAMES UTF8") or die(mysql_error());
while ($row = mysql_fetch_row($query)) {
$values = implode("', '", $row);
mysql_query("INSERT INTO `$temptable` VALUES('$values')") or die(mysql_error());
}
mysql_query("SET NAMES LATIN1") or die(mysql_error());
}
// drop old tables and rename temporary tables
// this actually should work, but it not, then
// comment out this lines if this would not work for you and try to rename tables manually with phpmyadmin
foreach ($tables as $table) {
$temptable = $table . '_temp';
mysql_query("DROP TABLE `$table`") or die(mysql_error());
mysql_query("ALTER TABLE `$temptable` RENAME `$table`") or die(mysql_error());
}
// now you data should be correct
// change the database character set
mysql_query("ALTER DATABASE DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci") or die(mysql_error());
// now you can use "SET NAMES UTF8" in your project and mysql will use corrected data
}
I use git gc after I do a big checkout, and have a lot of new object. it can save space. E.g. if you checkout a big SVN project using git-svn, and do a git gc, you typically save a lot of space
If @papigee does solution doesn't work, maybe you don't have the permissions.
I tried @papigee solution but does't work without sudo.
I did :
sudo docker exec -it <container id or name> /bin/sh
I had the same error and finally (in my particular case) I found a problem in the deployment descriptor (web.xml)
The problem:
<servlet-mapping>
<servlet-name>SessionController</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
...
<welcome-file-list>
<welcome-file>/</welcome-file>
</welcome-file-list>
the solution:
<servlet-mapping>
<servlet-name>SessionController</servlet-name>
<url-pattern>/SessionController</url-pattern>
</servlet-mapping>
...
<welcome-file-list>
<welcome-file>desktop.jsp</welcome-file>
</welcome-file-list>
The explicit way of saying "search until X
but not including X
" is:
(?:(?!X).)*
where X
can be any regular expression.
In your case, though, this might be overkill - here the easiest way would be
[^z]*
This will match anything except z
and therefore stop right before the next z
.
So .*?quick[^z]*
will match The quick fox jumps over the la
.
However, as soon as you have more than one simple letter to look out for, (?:(?!X).)*
comes into play, for example
(?:(?!lazy).)*
- match anything until the start of the word lazy
.
This is using a lookahead assertion, more specifically a negative lookahead.
.*?quick(?:(?!lazy).)*
will match The quick fox jumps over the
.
Explanation:
(?: # Match the following but do not capture it:
(?!lazy) # (first assert that it's not possible to match "lazy" here
. # then match any character
)* # end of group, zero or more repetitions.
Furthermore, when searching for keywords, you might want to surround them with word boundary anchors: \bfox\b
will only match the complete word fox
but not the fox in foxy
.
Note
If the text to be matched can also include linebreaks, you will need to set the "dot matches all" option of your regex engine. Usually, you can achieve that by prepending (?s)
to the regex, but that doesn't work in all regex engines (notably JavaScript).
Alternative solution:
In many cases, you can also use a simpler, more readable solution that uses a lazy quantifier. By adding a ?
to the *
quantifier, it will try to match as few characters as possible from the current position:
.*?(?=(?:X)|$)
will match any number of characters, stopping right before X
(which can be any regex) or the end of the string (if X
doesn't match). You may also need to set the "dot matches all" option for this to work. (Note: I added a non-capturing group around X
in order to reliably isolate it from the alternation)
There is also a more convenient (for some) svnversion
command.
Output might be a single revision number or something like this (from -h):
4123:4168 mixed revision working copy
4168M modified working copy
4123S switched working copy
4123:4168MS mixed revision, modified, switched working copy
I use this python code snippet to extract revision information:
import re
import subprocess
p = subprocess.Popen(["svnversion"], stdout = subprocess.PIPE,
stderr = subprocess.PIPE)
p.wait()
m = re.match(r'(|\d+M?S?):?(\d+)(M?)S?', p.stdout.read())
rev = int(m.group(2))
if m.group(3) == 'M':
rev += 1
On my Windows 7 machine I have the following environment variables:
JAVA_HOME=C:\Program Files\Java\jdk1.7.0_07
M2_HOME=C:\apache-maven-3.0.3
On my PATH
variable, I have (among others) the following:
I tried doing what you've done with %M2%
having the nested %M2_HOME%
and it also works.
I found this sample script here that seems to be working pretty well:
SELECT r.session_id,r.command,CONVERT(NUMERIC(6,2),r.percent_complete)
AS [Percent Complete],CONVERT(VARCHAR(20),DATEADD(ms,r.estimated_completion_time,GetDate()),20) AS [ETA Completion Time],
CONVERT(NUMERIC(10,2),r.total_elapsed_time/1000.0/60.0) AS [Elapsed Min],
CONVERT(NUMERIC(10,2),r.estimated_completion_time/1000.0/60.0) AS [ETA Min],
CONVERT(NUMERIC(10,2),r.estimated_completion_time/1000.0/60.0/60.0) AS [ETA Hours],
CONVERT(VARCHAR(1000),(SELECT SUBSTRING(text,r.statement_start_offset/2,
CASE WHEN r.statement_end_offset = -1 THEN 1000 ELSE (r.statement_end_offset-r.statement_start_offset)/2 END)
FROM sys.dm_exec_sql_text(sql_handle))) AS [SQL]
FROM sys.dm_exec_requests r WHERE command IN ('RESTORE DATABASE','BACKUP DATABASE')
SELECT column_name, COUNT(column_name)
FROM table_name
GROUP BY column_name
This works for me
$("#dropdownid").change(function() {
alert($(this).find("option:selected").text());
});
If the element created dynamically
$(document).on("change", "#dropdownid", function() {
alert($(this).find("option:selected").text());
});
you should android sdk manager install 4.2 api 17 -> ARM EABI v7a System Image
if not installed ARM EABI v7a System Image, you should install all.
Perhaps a little off topic, just be informed that these kind of messages can also be seen when you are debugging your code with a breakpoint inside an async function like setTimeout
like below:
[Violation] 'setTimeout' handler took 43129ms
That number (43129ms) depends on how long you stop in your async function
A very dummy mistake, but you can get this with a class too if you didn't instantiate it.
BankAccount account;
account.addMoney(5);
The above will produce the same error whereas:
class BankAccount
{
int balance = 0;
public void addMoney(int amount)
{
balance += amount;
}
}
Do the following to eliminate the error:
BankAccount account = new BankAccount();
account.addMoney(5);
You can resolve this in several ways:
g++
in stead of gcc
: g++ -g -o MatSim MatSim.cpp
-lstdc++
: gcc -g -o MatSim MatSim.cpp -lstdc++
<string.h>
by <string>
This is a linker problem, not a compiler issue. The same problem is covered in the question iostream linker error – it explains what is going on.
OK, first of all I'm not sure how it works when you create a div using (document.createElement('div'))
, so I might be wrong now, but wouldn't it be possible to use the :target pseudo class selector for this?
If you look at the code below, you can se I've used a link to target the div, but in your case it might be possible to target #new from the script instead and that way make the div fade in without user interaction, or am I thinking wrong?
Here's the code for my example:
HTML
<a href="#new">Click</a>
<div id="new">
Fade in ...
</div>
CSS
#new {
width: 100px;
height: 100px;
border: 1px solid #000000;
opacity: 0;
}
#new:target {
-webkit-transition: opacity 2.0s ease-in;
-moz-transition: opacity 2.0s ease-in;
-o-transition: opacity 2.0s ease-in;
opacity: 1;
}
... and here's a jsFiddle
I was working on a similar problem. @S.Lott said "If you have the list of variables, what's the point of "discovering" their names?" And my answer is just to see if it could be done and if for some reason you want to sort your variables by type into lists. So anyways, in my research I came came across this thread and my solution is a bit expanded and is based on @rlotun solution. One other thing, @unutbu said, "This idea has merit, but note that if two variable names reference the same value (e.g. True), then an unintended variable name might be returned." In this exercise that was true so I dealt with it by using a list comprehension similar to this for each possibility: isClass = [i for i in isClass if i != 'item']
. Without it "item" would show up in each list.
__metaclass__ = type
from types import *
class Class_1: pass
class Class_2: pass
list_1 = [1, 2, 3]
list_2 = ['dog', 'cat', 'bird']
tuple_1 = ('one', 'two', 'three')
tuple_2 = (1000, 2000, 3000)
dict_1 = {'one': 1, 'two': 2, 'three': 3}
dict_2 = {'dog': 'collie', 'cat': 'calico', 'bird': 'robin'}
x = 23
y = 29
pie = 3.14159
eee = 2.71828
house = 'single story'
cabin = 'cozy'
isClass = []; isList = []; isTuple = []; isDict = []; isInt = []; isFloat = []; isString = []; other = []
mixedDataTypes = [Class_1, list_1, tuple_1, dict_1, x, pie, house, Class_2, list_2, tuple_2, dict_2, y, eee, cabin]
print '\nMIXED_DATA_TYPES total count:', len(mixedDataTypes)
for item in mixedDataTypes:
try:
# if isinstance(item, ClassType): # use this for old class types (before 3.0)
if isinstance(item, type):
for k, v in list(locals().iteritems()):
if v is item:
mapping_as_str = k
isClass.append(mapping_as_str)
isClass = [i for i in isClass if i != 'item']
elif isinstance(item, ListType):
for k, v in list(locals().iteritems()):
if v is item:
mapping_as_str = k
isList.append(mapping_as_str)
isList = [i for i in isList if i != 'item']
elif isinstance(item, TupleType):
for k, v in list(locals().iteritems()):
if v is item:
mapping_as_str = k
isTuple.append(mapping_as_str)
isTuple = [i for i in isTuple if i != 'item']
elif isinstance(item, DictType):
for k, v in list(locals().iteritems()):
if v is item:
mapping_as_str = k
isDict.append(mapping_as_str)
isDict = [i for i in isDict if i != 'item']
elif isinstance(item, IntType):
for k, v in list(locals().iteritems()):
if v is item:
mapping_as_str = k
isInt.append(mapping_as_str)
isInt = [i for i in isInt if i != 'item']
elif isinstance(item, FloatType):
for k, v in list(locals().iteritems()):
if v is item:
mapping_as_str = k
isFloat.append(mapping_as_str)
isFloat = [i for i in isFloat if i != 'item']
elif isinstance(item, StringType):
for k, v in list(locals().iteritems()):
if v is item:
mapping_as_str = k
isString.append(mapping_as_str)
isString = [i for i in isString if i != 'item']
else:
for k, v in list(locals().iteritems()):
if v is item:
mapping_as_str = k
other.append(mapping_as_str)
other = [i for i in other if i != 'item']
except (TypeError, AttributeError), e:
print e
print '\n isClass:', len(isClass), isClass
print ' isList:', len(isList), isList
print ' isTuple:', len(isTuple), isTuple
print ' isDict:', len(isDict), isDict
print ' isInt:', len(isInt), isInt
print ' isFloat:', len(isFloat), isFloat
print 'isString:', len(isString), isString
print ' other:', len(other), other
# my output and the output I wanted
'''
MIXED_DATA_TYPES total count: 14
isClass: 2 ['Class_1', 'Class_2']
isList: 2 ['list_1', 'list_2']
isTuple: 2 ['tuple_1', 'tuple_2']
isDict: 2 ['dict_1', 'dict_2']
isInt: 2 ['x', 'y']
isFloat: 2 ['pie', 'eee']
isString: 2 ['house', 'cabin']
other: 0 []
'''
Interesting answers but the docs say differently:
Use the
GetNumericValue
methods to convert aChar
object that represents a number to a numeric value type. UseParse
andTryParse
to convert a character in a string into aChar
object. UseToString
to convert aChar
object to aString
object.
I had to use:
table, tbody {
width: 100%;
}
The table
alone wasn't enough, the tbody
was also needed for it to work for me.
$output = preg_replace('/\s+/', ' ',$input);
\s is shorthand for [ \t\n\r]
. Multiple spaces will be replaced with single space.
I had similar problem as Pietro,
I am on Window 10 and using "Git Bash". I tried to execute >>cmake -G "MinGW Makefiles", but I got the same error as Pietro.
Then, I tried >>cmake -G "MSYS Makefiles", but realized that I need to set my environment correctly.
Make sure set a path to C:\MinGW\msys\1.0\bin and check if you have gcc.exe there. If gcc.exe is not there then you have to run C:/MinGW/bin/mingw-get.exe and install gcc from MSYS.
After that it works fine for me
You can also use:
Get-WmiObject -Class "Win32_computersystem" | Select *
This will show the same result as Format-List * used in the other answers here.
public function getdata(){
$this->db->select('c.country_name as country, s.state_name as state, ct.city_name as city, t.id as id');
$this->db->from('tblmaster t');
$this->db->join('country c', 't.country=c.country_id');
$this->db->join('state s', 't.state=s.state_id');
$this->db->join('city ct', 't.city=ct.city_id');
$this->db->order_by('t.id','desc');
$query = $this->db->get();
return $query->result();
}
have you tried to remove the timezone awareness?
from http://pytz.sourceforge.net/
naive = dt.replace(tzinfo=None)
may have to add time zone conversion as well.
edit: Please be aware the age of this answer. An answer involving ADDing the timezone info instead of removing it in python 3 is below. https://stackoverflow.com/a/25662061/93380
With Java 8 Stream API:
List<String> myList = Arrays.asList(" A", "B ", " C ");
return myList.stream().anyMatch(str -> str.trim().equals("B"));
It is rather messy but you need to do something like the following:
START "do something window" dir
FOR /F "tokens=2" %I in ('TASKLIST /NH /FI "WINDOWTITLE eq do something window"' ) DO SET PID=%I
ECHO %PID%
TASKKILL /PID %PID%
Found this on this page.
(This kind of thing is much easier if you have a UNIX / LINUX system ... or if you run Cygwin or similar on Windows.)
It's just what it says:
inputFile = open((x), encoding = "utf8", "r")
You have specified encoding
as a keyword argument, but "r"
as a positional argument. You can't have positional arguments after keyword arguments. Perhaps you wanted to do:
inputFile = open((x), "r", encoding = "utf8")
There is an interesting point you need to catch about csv.reader() object. The csv.reader object is not list
type, and not subscriptable.
This works:
for r in csv.reader(file_obj): # file not closed
print r
This does not:
r = csv.reader(file_obj)
print r[0]
So, you first have to convert to list type in order to make the above code work.
r = list( csv.reader(file_obj) )
print r[0]
Since Dheeraj Bhaskar
's answer is relatively old as many years past.
Here is my latest (2019 year) answer:
from dex
to java sourcecode
, currently has two kind of solution:
One Step
: directly convert dex
to java sourcecode
Two Step
: first convert dex
to jar
, second convert jar
to java sourcecode
dex
directly to java sourcecode
bin
folder can see command line jadx
or GUI version jadx-gui
, double click to run GUI version: jadx-gui
dex
filethen can show java source code:
File
-> save as gradle project
then got java sourcecode:
dex
to jar
download dex2jar zip, unzip got d2j-dex2jar.sh
, then:
apk
to jar
: sh d2j-dex2jar.sh -f ~/path/to/apk_to_decompile.apk
dex
to jar
: sh d2j-dex2jar.sh -f ~/path/to/dex_to_decompile.dex
example:
? v3.4.8 /Users/crifan/dev/dev_tool/android/reverse_engineering/dex-tools/dex-tools-2.1-SNAPSHOT/d2j-dex2jar.sh -f com.huili.readingclub8825612.dex
dex2jar com.huili.readingclub8825612.dex -> ./com.huili.readingclub8825612-dex2jar.jar
? v3.4.8 ll
-rw------- 1 crifan staff 9.5M 3 21 10:00 com.huili.readingclub8825612-dex2jar.jar
-rw------- 1 crifan staff 8.4M 3 19 14:04 com.huili.readingclub8825612.dex
jar
to java sourcecode
many
code will decompile errorminor
code will decompile errorno
code decompile error
Procyon
here demo Procyon
convert jar to java source code:
download procyon-decompiler-0.5.34.jar
then using syntax:
java -jar /path/to/procyon-decompiler-0.5.34.jar -jar your_to_decompile.jar -o outputFolderName
example:
java -jar /Users/crifan/dev/dev_tool/android/reverse_engineering/Procyon/procyon-decompiler-0.5.34.jar -jar com.huili.readingclub8825612-dex2jar.jar -o com.huili.readingclub8825612
using editor VSCode to open exported source code, look like this:
Conversion correctness : Jadx
> Procyon
> CRF
> JD-GUI
Recommend use: (One step solution's) Jadx
for more detailed explanation, please refer my online Chinese ebook: ??????????
Well I think the forloop you've provided in the question is about as good as it gets, but I want to point out that unused variables that have to be assigned can be assigned to the variable named _
, a convention for "discarding" the value assigned. Though the _
reference will hold the value you gave it, code linters and other developers will understand you aren't using that reference. So here's an example:
for _ in range(2):
print('Hello')
Are you sure you want to use __getattribute__
? What are you actually trying to achieve?
The easiest way to do what you ask is:
class D(object):
def __init__(self):
self.test = 20
self.test2 = 21
test = 0
or:
class D(object):
def __init__(self):
self.test = 20
self.test2 = 21
@property
def test(self):
return 0
Edit:
Note that an instance of D
would have different values of test
in each case. In the first case d.test
would be 20, in the second it would be 0. I'll leave it to you to work out why.
Edit2:
Greg pointed out that example 2 will fail because the property is read only and the __init__
method tried to set it to 20. A more complete example for that would be:
class D(object):
def __init__(self):
self.test = 20
self.test2 = 21
_test = 0
def get_test(self):
return self._test
def set_test(self, value):
self._test = value
test = property(get_test, set_test)
Obviously, as a class this is almost entirely useless, but it gives you an idea to move on from.
Alt + p for previous command from histroy, Alt + n for next command from history.
This is default configure, and you can change these key shortcut at your preference from Options -> Configure IDLE.
Another nice way to put your logic in data is something like this:
# Initialization.
CAR_TYPES = {
foo_type: ['honda', 'acura', 'mercedes'],
bar_type: ['toyota', 'lexus']
# More...
}
@type_for_name = {}
CAR_TYPES.each { |type, names| names.each { |name| @type_for_name[type] = name } }
case @type_for_name[car]
when :foo_type
# do foo things
when :bar_type
# do bar things
end
This works fine in bash
:
END=5
i=1 ; while [[ $i -le $END ]] ; do
echo $i
((i = i + 1))
done
I got this warning from an incomplete method check:
if hasattr(w, 'to_json'):
return w.to_json()
######### warning, 'str' object is not callable
It assumed w.to_json
was a string. The solution was to add a callable()
check:
if hasattr(w, 'to_json') and callable(w.to_json):
Then the warning went away.
All string data must be UTF-8 encoded.
$out = array(
'render' => utf8_encode($renderOutput),
'text' => utf8_encode($textOutput)
);
$out = json_encode($out);
die($out);
For Drupal 8 you can do this :
$url = 'YOUR_URL';
$url = \Drupal\Core\Url::fromUserInput('/' . $url, array('absolute' => 'true'))->toString();
I have this problem when using STS. After edited something, I see that, some workspaces when create a project will happen this problem, and others will not. So I just create a new project in workspaces will not happen.
This link should satisfy your curiosity.
Basically (forgetting your third example which is bad), the different between 1 and 2 is that 1 allocates space for a pointer to the array.
But in the code, you can manipulate them as pointers all the same -- only thing, you cannot reallocate the second.
make sure you download the x86 SDK instead of only the x64 SDK for visual studio.
Your item
variable holds Array
instance (in [hash_key, hash_value]
format), so it doesn't expect Symbol
in []
method.
This is how you could do it using Hash#each
:
def format(hash)
output = Hash.new
hash.each do |key, value|
output[key] = cleanup(value)
end
output
end
or, without this:
def format(hash)
output = hash.dup
output[:company_name] = cleanup(output[:company_name])
output[:street] = cleanup(output[:street])
output
end
I would try to avoid changing the xticklabels
if possible, otherwise it can get very confusing if you for example overplot your histogram with additional data.
Defining the range of your grid is probably the best and with imshow
it can be done by adding the extent
keyword. This way the axes gets adjusted automatically. If you want to change the labels i would use set_xticks
with perhaps some formatter. Altering the labels directly should be the last resort.
fig, ax = plt.subplots(figsize=(6,6))
ax.imshow(hist, cmap=plt.cm.Reds, interpolation='none', extent=[80,120,32,0])
ax.set_aspect(2) # you may also use am.imshow(..., aspect="auto") to restore the aspect ratio
dict.allKeys
is not a String. It is a [String]
, exactly as the error message tells you (assuming, of course, that the keys are all strings; this is exactly what you are asserting when you say that).
So, either start by typing componentArray
as [AnyObject]
, because that is how it is typed in the Cocoa API, or else, if you cast dict.allKeys
, cast it to [String]
, because that is how you have typed componentArray
.
You're thinking too much in pure Javascript. Get rid of your listeners on those React lifecycle methods and use event.key
instead of event.keyCode
(because this is not a JS event object, it is a React SyntheticEvent). Your entire component could be as simple as this (assuming you haven't bound your methods in a constructor).
onKeyPressed(e) {
console.log(e.key);
}
render() {
let player = this.props.boards.dungeons[this.props.boards.currentBoard].player;
return (
<div
className="player"
style={{ position: "absolute" }}
onKeyDown={this.onKeyPressed}
>
<div className="light-circle">
<div className="image-wrapper">
<img src={IMG_URL+player.img} />
</div>
</div>
</div>
)
}
$newarr=arsort($arr);
$max_key=array_shift(array_keys($new_arr));
The $.getJSON()
method is shorthand that does not let you specify advanced options like that. To do that, you need to use the full $.ajax()
method.
Notice in the documentation at http://api.jquery.com/jQuery.getJSON/:
This is a shorthand Ajax function, which is equivalent to:
$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback
});
So just use $.ajax()
and provide all the extra parameters you need.
For getting key
var a = {"a":"1","b":"2"};
var keys = []
for(var k in a){
keys.push(k)
}
For getting value.
var a = {"a":"1","b":"2"};
var values = []
for(var k in a){
values.push(a[k]);
}
You can use .gitignore in the top level to ignore all directories in the project with the same name. For example:
Debug/
Release/
This should update immediately so it's visible when you do git status. Ensure that these directories are not already added to git, as that will override the ignores.
This script helps you to switch over from a Parent window to a Child window and back cntrl to Parent window
String parentWindow = driver.getWindowHandle();
Set<String> handles = driver.getWindowHandles();
for(String windowHandle : handles)
{
if(!windowHandle.equals(parentWindow))
{
driver.switchTo().window(windowHandle);
<!--Perform your operation here for new window-->
driver.close(); //closing child window
driver.switchTo().window(parentWindow); //cntrl to parent window
}
}
On my linux system, I start Tomcat with the startup.sh script. To know whether it is running or not, i use
ps -ef | grep tomcat
If the output result contains the whole path to my tomcat folder, then it is running
Try this:
public void LoadData()
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Stocks;Integrated Security=True;Pooling=False");
SqlDataAdapter sda = new SqlDataAdapter("Select * From [Stocks].[dbo].[product]", con);
DataTable dt = new DataTable();
sda.Fill(dt);
DataGridView1.Rows.Clear();
foreach (DataRow item in dt.Rows)
{
int n = DataGridView1.Rows.Add();
DataGridView1.Rows[n].Cells[0].Value = item["ProductCode"].ToString();
DataGridView1.Rows[n].Cells[1].Value = item["Productname"].ToString();
DataGridView1.Rows[n].Cells[2].Value = item["qty"].ToString();
if ((bool)item["productstatus"])
{
DataGridView1.Rows[n].Cells[3].Value = "Active";
}
else
{
DataGridView1.Rows[n].Cells[3].Value = "Deactive";
}
Here is the configuration for those trying to accomplish the original goal (wildcards all pointing to same codebase -- install nothing, dev environment ie, XAMPP)
file: /etc/hosts (non-windows)
127.0.0.1 example.local
file: /XAMPP/etc/httpd.conf
# Virtual hosts
Include etc/extra/httpd-vhosts.conf
file: XAMPP/etc/extra/httpd-vhosts.conf
<VirtualHost *:80>
ServerAdmin [email protected]
DocumentRoot "/path_to_XAMPP/htdocs"
ServerName example.local
ServerAlias *.example.local
# SetEnv APP_ENVIRONMENT development
# ErrorLog "logs/example.local-error_log"
# CustomLog "logs/example.local-access_log" common
</VirtualHost>
restart apache
save as whatever.pac wherever you want to and then load the file in the browser's network>proxy>auto_configuration settings (reload if you alter this)
function FindProxyForURL(url, host) {
if (shExpMatch(host, "*example.local")) {
return "PROXY example.local";
}
return "DIRECT";
}
char[] result = "Stack Me 123 Heppa1 oeu".toCharArray();
For AWS if the user is ubuntu use the following to connect to remote server.
chmod 400 mykey.pem
ssh -i mykey.pem ubuntu@your-ip
I have win 7 64 bit + Excel 2010 32 bit. The registry is HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\14.0\Registration{90140000-002A-0000-1000-0000000FF1CE}
So this can tell bitness of OS, not bitness of Office
The answer for the last two can also be deducted from the golden rule in C:
Declaration follows use.
int (*arr2)[8];
What happens if you dereference arr2
? You get an array of 8 integers.
int *(arr3[8]);
What happens if you take an element from arr3
? You get a pointer to an integer.
This also helps when dealing with pointers to functions. To take sigjuice's example:
float *(*x)(void )
What happens when you dereference x
? You get a function that you can call with no arguments. What happens when you call it? It will return a pointer to a float
.
Operator precedence is always tricky, though. However, using parentheses can actually also be confusing because declaration follows use. At least, to me, intuitively arr2
looks like an array of 8 pointers to ints, but it is actually the other way around. Just takes some getting used to. Reason enough to always add a comment to these declarations, if you ask me :)
edit: example
By the way, I just stumbled across the following situation: a function that has a static matrix and that uses pointer arithmetic to see if the row pointer is out of bounds. Example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NUM_ELEM(ar) (sizeof(ar) / sizeof((ar)[0]))
int *
put_off(const int newrow[2])
{
static int mymatrix[3][2];
static int (*rowp)[2] = mymatrix;
int (* const border)[] = mymatrix + NUM_ELEM(mymatrix);
memcpy(rowp, newrow, sizeof(*rowp));
rowp += 1;
if (rowp == border) {
rowp = mymatrix;
}
return *rowp;
}
int
main(int argc, char *argv[])
{
int i = 0;
int row[2] = {0, 1};
int *rout;
for (i = 0; i < 6; i++) {
row[0] = i;
row[1] += i;
rout = put_off(row);
printf("%d (%p): [%d, %d]\n", i, (void *) rout, rout[0], rout[1]);
}
return 0;
}
Output:
0 (0x804a02c): [0, 0]
1 (0x804a034): [0, 0]
2 (0x804a024): [0, 1]
3 (0x804a02c): [1, 2]
4 (0x804a034): [2, 4]
5 (0x804a024): [3, 7]
Note that the value of border never changes, so the compiler can optimize that away. This is different from what you might initially want to use: const int (*border)[3]
: that declares border as a pointer to an array of 3 integers that will not change value as long as the variable exists. However, that pointer may be pointed to any other such array at any time. We want that kind of behaviour for the argument, instead (because this function does not change any of those integers). Declaration follows use.
(p.s.: feel free to improve this sample!)
The child can only take a height if the parent has one already set. See this exaple : Vertical Scrolling 100% height
html, body {
height: 100%;
margin: 0;
}
.header{
height: 10%;
background-color: #a8d6fe;
}
.middle {
background-color: #eba5a3;
min-height: 80%;
}
.footer {
height: 10%;
background-color: #faf2cc;
}
$(function() {_x000D_
$('a[href*="#nav-"]').click(function() {_x000D_
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {_x000D_
var target = $(this.hash);_x000D_
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');_x000D_
if (target.length) {_x000D_
$('html, body').animate({_x000D_
scrollTop: target.offset().top_x000D_
}, 500);_x000D_
return false;_x000D_
}_x000D_
}_x000D_
});_x000D_
});
_x000D_
html,_x000D_
body {_x000D_
height: 100%;_x000D_
margin: 0;_x000D_
}_x000D_
.header {_x000D_
height: 100%;_x000D_
background-color: #a8d6fe;_x000D_
}_x000D_
.middle {_x000D_
background-color: #eba5a3;_x000D_
min-height: 100%;_x000D_
}_x000D_
.footer {_x000D_
height: 100%;_x000D_
background-color: #faf2cc;_x000D_
}_x000D_
nav {_x000D_
position: fixed;_x000D_
top: 10px;_x000D_
left: 0px;_x000D_
}_x000D_
nav li {_x000D_
display: inline-block;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<body>_x000D_
<nav>_x000D_
<ul>_x000D_
<li>_x000D_
<a href="#nav-a">got to a</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#nav-b">got to b</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#nav-c">got to c</a>_x000D_
</li>_x000D_
</ul>_x000D_
</nav>_x000D_
<div class="header" id="nav-a">_x000D_
_x000D_
</div>_x000D_
<div class="middle" id="nav-b">_x000D_
_x000D_
</div>_x000D_
<div class="footer" id="nav-c">_x000D_
_x000D_
</div>
_x000D_
esp
is as you say it is, the top of the stack.
ebp
is usually set to esp
at the start of the function. Function parameters and local variables are accessed by adding and subtracting, respectively, a constant offset from ebp
. All x86 calling conventions define ebp
as being preserved across function calls. ebp
itself actually points to the previous frame's base pointer, which enables stack walking in a debugger and viewing other frames local variables to work.
Most function prologs look something like:
push ebp ; Preserve current frame pointer
mov ebp, esp ; Create new frame pointer pointing to current stack top
sub esp, 20 ; allocate 20 bytes worth of locals on stack.
Then later in the function you may have code like (presuming both local variables are 4 bytes)
mov [ebp-4], eax ; Store eax in first local
mov ebx, [ebp - 8] ; Load ebx from second local
FPO or frame pointer omission optimization which you can enable will actually eliminate this and use ebp
as another register and access locals directly off of esp
, but this makes debugging a bit more difficult since the debugger can no longer directly access the stack frames of earlier function calls.
EDIT:
For your updated question, the missing two entries in the stack are:
var_C = dword ptr -0Ch
var_8 = dword ptr -8
var_4 = dword ptr -4
*savedFramePointer = dword ptr 0*
*return address = dword ptr 4*
hInstance = dword ptr 8h
PrevInstance = dword ptr 0C
hlpCmdLine = dword ptr 10h
nShowCmd = dword ptr 14h
This is because the flow of the function call is:
hInstance
, etc.)ebp
Consider following code
<ul id="myTask">
<li>Coding</li>
<li>Answering</li>
<li>Getting Paid</li>
</ul>
Now, here goes the difference
// Remove the myTask item when clicked.
$('#myTask').children().click(function () {
$(this).remove()
});
Now, what if we add a myTask again?
$('#myTask').append('<li>Answer this question on SO</li>');
Clicking this myTask item will not remove it from the list, since it doesn't have any event handlers bound. If instead we'd used .on
, the new item would work without any extra effort on our part. Here's how the .on version would look:
$('#myTask').on('click', 'li', function (event) {
$(event.target).remove()
});
Summary:
The difference between .on()
and .click()
would be that .click()
may not work when the DOM elements associated with the .click()
event are added dynamically at a later point while .on()
can be used in situations where the DOM elements associated with the .on()
call may be generated dynamically at a later point.
This issue might also be caused by a broken Maven repository.
I observe the SEVERE: A child container failed during start
message from time to time when working with Eclipse. My Eclipse workspace has several projects. Some of the projects have common external dependencies. If Maven repository is empty (or I add new dependencies into pom.xml
files), Eclipse starts downloading libraries specified in pom.xml
into Maven repository. And Eclipse does that in parallel for several projects in the workspace. It might happen that several Eclipse threads would be downloading the same file simultaneously into the same place in Maven repository. As a result, this file becomes corrupted.
So, this is how you could resolve the issue.
rm -rf $HOME/.m2
).mvn package
in the command line. It is important to run the command for each project one-by-one, not in parallel; thus, you ensure that only one instance of Maven runs each time.You can also use XMLPad (free to use) found here http://www.wmhelp.com to generate your xml samples. From the menu : XSD -> generate sample XML file.
In order to capture deadlock graphs without using a trace (you don't need profiler necessarily), you can enable trace flag 1222. This will write deadlock information to the error log. However, the error log is textual, so you won't get nice deadlock graph pictures - you'll have to read the text of the deadlocks to figure it out.
I would set this as a startup trace flag (in which case you'll need to restart the service). However, you can run it only for the current running instance of the service (which won't require a restart, but which won't resume upon the next restart) using the following global trace flag command:
DBCC TRACEON(1222, -1);
A quick search yielded this tutorial:
http://www.mssqltips.com/sqlservertip/2130/finding-sql-server-deadlocks-using-trace-flag-1222/
Also note that if your system experiences a lot of deadlocks, this can really hammer your error log, and can become quite a lot of noise, drowning out other, important errors.
Have you considered third party monitoring tools? SQL Sentry Performance Advisor, for example, has a much nicer deadlock graph, showing you object / index names as well as the order in which the locks were taken. As a bonus, these are captured for you automatically on monitored servers without having to configure trace flags, run your own traces, etc.:
Disclaimer: I work for SQL Sentry.
To set an existing column right/left of another, based on their names:
def df_move_column(df, col_to_move, col_left_of_destiny="", right_of_col_bool=True):
cols = list(df.columns.values)
index_max = len(cols) - 1
if not right_of_col_bool:
# set left of a column "c", is like putting right of column previous to "c"
# ... except if left of 1st column, then recursive call to set rest right to it
aux = cols.index(col_left_of_destiny)
if not aux:
for g in [x for x in cols[::-1] if x != col_to_move]:
df = df_move_column(
df,
col_to_move=g,
col_left_of_destiny=col_to_move
)
return df
col_left_of_destiny = cols[aux - 1]
index_old = cols.index(col_to_move)
index_new = 0
if len(col_left_of_destiny):
index_new = cols.index(col_left_of_destiny) + 1
if index_old == index_new:
return df
if index_new < index_old:
index_new = np.min([index_new, index_max])
cols = (
cols[:index_new]
+ [cols[index_old]]
+ cols[index_new:index_old]
+ cols[index_old + 1 :]
)
else:
cols = (
cols[:index_old]
+ cols[index_old + 1 : index_new]
+ [cols[index_old]]
+ cols[index_new:]
)
df = df[cols]
return df
E.g.
cols = list("ABCD")
df2 = pd.DataFrame(np.arange(4)[np.newaxis, :], columns=cols)
for k in cols:
print(30 * "-")
for g in [x for x in cols if x != k]:
df_new = df_move_column(df2, k, g)
print(f"{k} after {g}: {df_new.columns.values}")
for k in cols:
print(30 * "-")
for g in [x for x in cols if x != k]:
df_new = df_move_column(df2, k, g, right_of_col_bool=False)
print(f"{k} before {g}: {df_new.columns.values}")
Output:
curl -s http://google.com > temp.html
works for curl version 7.19.5 on Ubuntu 9.10 (no progress bar). But if for some reason that does not work on your platform, you could always redirect stderr to /dev/null:
curl http://google.com 2>/dev/null > temp.html
If you define the ListView
in XAML:
<ListView x:Name="listView"/>
Then you can add columns and populate it in C#:
public Window()
{
// Initialize
this.InitializeComponent();
// Add columns
var gridView = new GridView();
this.listView.View = gridView;
gridView.Columns.Add(new GridViewColumn {
Header = "Id", DisplayMemberBinding = new Binding("Id") });
gridView.Columns.Add(new GridViewColumn {
Header = "Name", DisplayMemberBinding = new Binding("Name") });
// Populate list
this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}
See definition of MyItem
below.
However, it's easier to define the columns in XAML (inside the ListView
definition):
<ListView x:Name="listView">
<ListView.View>
<GridView>
<GridViewColumn Header="Id" DisplayMemberBinding="{Binding Id}"/>
<GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/>
</GridView>
</ListView.View>
</ListView>
And then just populate the list in C#:
public Window()
{
// Initialize
this.InitializeComponent();
// Populate list
this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}
See definition of MyItem
below.
MyItem
DefinitionMyItem
is defined like this:
public class MyItem
{
public int Id { get; set; }
public string Name { get; set; }
}
In my case:
PHImageRequestOptions *requestOptions = [PHImageRequestOptions new];
requestOptions.synchronous = NO;
Was trying to do this with dispatch_group
I suggest that you use a profiler to test which is faster.
My personal opinion is that you should use Lists.
I work on a large codebase and a previous group of developers used arrays everywhere. It made the code very inflexible. After changing large chunks of it to Lists we noticed no difference in speed.
You can draw the image on the canvas and let the user draw on top of that.
The drawImage()
function will help you with that, see https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Using_images
You can also just delay some operation this way:
setTimeout(function (){
// Something you want delayed.
}, 5000); // How long do you want the delay to be (in milliseconds)?
The only way to do that is running the exe and collect the MSI. The thing you must take care of is that if you are tranforming the MSI using MST they might get lost.
I use this batch commandline:
SET TMP=c:\msipath
MD "%TMP%"
SET TEMP=%TMP%
start /d "c:\install" install.exe /L1033
PING 1.1.1.1 -n 1 -w 10000 >NUL
for /R "%TMP%" %%f in (*.msi) do copy "%%f" "%TMP%"
taskkill /F /IM msiexec.exe /T
I had errors 10060 and 10061. The reason was in my antivirus(Eset Nod 32). Try to turn off the Firewall of your antivirus as I did or just delete it for a time to test the program. If everything started to work properly, add that program to the exclusion or switch to another antivirus. Also, try to change the 'host' variable to an empty string:
host = ''
And add socket.AF_INET, socket.SOCK_STREAM to the 's' variable:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Regarding you question about betterhost and such, see host; basically every IP address is a host.
I suggest you start reading-up from host and only than go on to localhost (which is a type of host)
Sorry, it is a reponse to an old thread, but might still be usefull.
In addition to above reponses, This genrally happens when two columns with same name, even from different tables are included in the same query. for example if we joining two tables city and state where tables have column name e.g. city.name and state.name. when such a query is added to the dataset, ssrs removes the table name or the table alias and only keeps the name, whih eventually appears twice in the query and errors as duplicate key. The best way to avoid it is to use alias such as calling the column names city.name as c_name state.name as s_name. This will resolve the issue.
Popen.communicate
will set the returncode
attribute when it's done(*). Here's the relevant documentation section:
Popen.returncode
The child return code, set by poll() and wait() (and indirectly by communicate()).
A None value indicates that the process hasn’t terminated yet.
A negative value -N indicates that the child was terminated by signal N (Unix only).
So you can just do (I didn't test it but it should work):
import subprocess as sp
child = sp.Popen(openRTSP + opts.split(), stdout=sp.PIPE)
streamdata = child.communicate()[0]
rc = child.returncode
(*) This happens because of the way it's implemented: after setting up threads to read the child's streams, it just calls wait
.
If you want to make your code work as above, the function printInformation() needs to be declared and implemented as a static function.
If, on the other hand, it is supposed to print information about a specific object, you need to create the object first.
Use ?
:
<form action="?" method="post">
It will send the user back to the same page.
Your question is mixing a few different concepts. You started out saying you wanted to run sites on the same server using the same domain, but in different folders. That doesn't require any special setup. Once you get the single domain running, you just create folders under that docroot.
Based on the rest of your question, what you really want to do is run various sites on the same server with their own domain names.
The best documentation you'll find on the topic is the virtual host documentation in the apache manual.
There are two types of virtual hosts: name-based and IP-based. Name-based allows you to use a single IP address, while IP-based requires a different IP for each site. Based on your description above, you want to use name-based virtual hosts.
The initial error you were getting was due to the fact that you were using different ports than the NameVirtualHost
line. If you really want to have sites served from ports other than 80, you'll need to have a NameVirtualHost
entry for each port.
Assuming you're starting from scratch, this is much simpler than it may seem.
If you are using 2.3 or earlier, the first thing you need to do is tell Apache that you're going to use name-based virtual hosts.
NameVirtualHost *:80
If you are using 2.4 or later do not add a NameVirtualHost line. Version 2.4 of Apache deprecated the NameVirtualHost
directive, and it will be removed in a future version.
Now your vhost definitions:
<VirtualHost *:80>
DocumentRoot "/home/user/site1/"
ServerName site1
</VirtualHost>
<VirtualHost *:80>
DocumentRoot "/home/user/site2/"
ServerName site2
</VirtualHost>
You can run as many sites as you want on the same port. The ServerName
being different is enough to tell Apache which vhost to use. Also, the ServerName
directive is always the domain/hostname and should never include a path.
If you decide to run sites on a port other than 80, you'll always have to include the port number in the URL when accessing the site. So instead of going to http://example.com you would have to go to http://example.com:81
As JoshC said, the class .sr-only
is used to visually hide the information used for screen readers only. But not only to hide labels. You might consider hiding various other elements such as "skip to main content" link, icons which have an alternative texts etc.
BTW. you can also use .sr-only sr-only-focusable
if you need the element to become visible when focused e.g. "skip to main content"
If you want make your website even more accessible I recommend to start here:
Why?
According to the World Health Organization, 285 million people have vision impairments. So making a website accessible is important.
IMPORTANT: Avoid treating disabled users differently. Generally speaking try to avoid developing a different content for different groups of users. Instead try to make accessible the existing content so that it simply works out-of-the-box and for all not specifically targeting e.g. screen readers. In other words don't try to reinvent the wheel. Otherwise the resulting accessibility will often be worse than if there was nothing developed at all. We developers should not assume how those users will use our website. So be very careful when you need to develop such solutions. Obviously a "skip link" is a good example of such content if it's made visible when focused. But there many bad examples too. Such would be hiding from a screen reader a "zoom" button on the map assuming that it has no relevance to blind users. But surprisingly, a zoom function indeed is used among blind users! They like to download images like many other users do (even in high resolution), for sending them to somebody else or for using them in some other context. Source - Read more @ADG: Bad ARIA practices
Using a table would be one (and easy) option.
Other options are all about setting fixed width on the and making it text-aligned to the right:
label {
width: 200px;
display: inline-block;
text-align: right;
}
or, as was pointed out, make them all float instead of inline.
@Cermbo's answer is not related to this question. In their answer, Laravel will give you all Events
if each Event
has 'participants'
with IdUser
of 1
.
But if you want to get all Events
with all 'participants'
provided that all 'participants'
have a IdUser
of 1, then you should do something like this :
Event::with(["participants" => function($q){
$q->where('participants.IdUser', '=', 1);
}])
N.B:
in where
use your table name, not Model name.
If you look deeper into the other uses of size
you can see that you can actually get a vector of the size of each dimension. This link shows you the documentation:
www.mathworks.com/access/helpdesk/help/techdoc/ref/size.html
After getting the size vector, iterate over that vector. Something like this (pardon my syntax since I have not used Matlab since college):
d = size(m);
dims = ndims(m);
for dimNumber = 1:dims
for i = 1:d[dimNumber]
...
Make this into actual Matlab-legal syntax, and I think it would do what you want.
Also, you should be able to do Linear Indexing as described here.
Your countLines(String filename)
method throws IOException.
You can't use it in a member declaration. You'll need to perform the operation in a main(String[] args)
method.
Your main(String[] args)
method will get the IOException thrown to it by countLines and it will need to handle or declare it.
Try this to just throw the IOException from main
public class MyClass {
private int lineCount;
public static void main(String[] args) throws IOException {
lineCount = LineCounter.countLines(sFileName);
}
}
or this to handle it and wrap it in an unchecked IllegalArgumentException:
public class MyClass {
private int lineCount;
private String sFileName = "myfile";
public static void main(String[] args) throws IOException {
try {
lineCount = LineCounter.countLines(sFileName);
} catch (IOException e) {
throw new IllegalArgumentException("Unable to load " + sFileName, e);
}
}
}
remove
user.setId(1);
because it is auto generate on the DB, and continue with persist command.
const data = res
const lista = []
let newElement: any
if (data && data.length > 0) {
data.forEach(element => {
newElement = element
Object.entries(newElement).map(([key, value]) =>
Object.assign(newElement, {
[key.toLowerCase()]: value
}, delete newElement[key], delete newElement['_id'])
)
lista.push(newElement)
})
}
return lista
getActivity().finish();
System.exit(0);
this is the best way to exit your app.!!!
The best solution for me.
Kyle's solution worked perfectly fine for me so I made my research in order to avoid any Js and CSS, but just sticking with HTML.
Adding a value of selected
to the item we want to appear as a header forces it to show in the first place as a placeholder.
Something like:
<option selected disabled>Choose here</option>
The complete markup should be along these lines:
<select>
<option selected disabled>Choose here</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
You can take a look at this fiddle, and here's the result:
If you do not want the sort of placeholder text to appear listed in the options once a user clicks on the select box just add the hidden
attribute like so:
<select>
<option selected disabled hidden>Choose here</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
Check the fiddle here and the screenshot below.
Here is the solution:
<select>
<option style="display:none;" selected>Select language</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
You want to use BigInteger.toByteArray()
String msg = "Hello there!";
BigInteger bi = new BigInteger(msg.getBytes());
System.out.println(new String(bi.toByteArray())); // prints "Hello there!"
The way I understand it is that you're doing the following transformations:
String -----------------> byte[] ------------------> BigInteger
String.getBytes() BigInteger(byte[])
And you want the reverse:
BigInteger ------------------------> byte[] ------------------> String
BigInteger.toByteArray() String(byte[])
Note that you probably want to use overloads of String.getBytes()
and String(byte[])
that specifies an explicit encoding, otherwise you may run into encoding issues.
When using JPA and Hibernate, an entity can be in one of the following 4 states:
To become persisted we need to either explicitly call the persist
method or make use of the transitive persistence mechanism.
Any change made to such an entity is going to be detected and propagated to the database (during the Session flush-time).
Detached - Once the currently running Persistence Context is closed all the previously managed entities become detached. Successive changes will no longer be tracked and no automatic database synchronization is going to happen.
Removed - Although JPA demands that managed entities only are allowed to be removed, Hibernate can also delete detached entities (but only through a remove
method call).
To move an entity from one state to the other, you can use the persist
, remove
or merge
methods.
The issue you are describing in your question:
object references an unsaved transient instance - save the transient instance before flushing
is caused by associating an entity in the state of New to an entity that's in the state of Managed.
This can happen when you are associating a child entity to a one-to-many collection in the parent entity, and the collection does not cascade
the entity state transitions.
So, you can fix this by adding cascade to the entity association that triggered this failure, as follows:
@OneToOne
association@OneToOne(
mappedBy = "post",
orphanRemoval = true,
cascade = CascadeType.ALL)
private PostDetails details;
Notice the
CascadeType.ALL
value we added for thecascade
attribute.
@OneToMany
association@OneToMany(
mappedBy = "post",
orphanRemoval = true,
cascade = CascadeType.ALL)
private List<Comment> comments = new ArrayList<>();
Again, the CascadeType.ALL
is suitable for the bidirectional @OneToMany
associations.
Now, in order for the cascade to work properly in a bidirectional, you also need to make sure that the parent and child associations are in sync.
@ManyToMany
association@ManyToMany(
mappedBy = "authors",
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
}
)
private List<Book> books = new ArrayList<>();
In a @ManyToMany
association, you cannot use CascadeType.ALL
or orphanRemoval
as this will propagate the delete entity state transition from one parent to another parent entity.
Therefore, for @ManyToMany
associations, you usually cascade the CascadeType.PERSIST
or CascadeType.MERGE
operations. Alternatively, you can expand that to DETACH
or REFRESH
.
Update (2017/01/05):
GitHub has published an update that allows you now to search within commit messages from within their UI. See blog post for more information.
I had the same question and contacted someone GitHub yesterday:
Since they switched their search engine to Elasticsearch it's not possible to search for commit messages using the GitHub UI. But that feature is on the team's wishlist.
Unfortunately there's no release date for that function right now.
var clist = document.getElementsByTagName("input");
for (var i = 0; i < clist.length; ++i) { clist[i].checked = false; }
$('input:checkbox').each(function() { this.checked = false; });
To do opposite, see: Select All Checkboxes By ID/Class
Off the top of my head, this will do it without any sort of error checking nor ability to configure anything. That is "left to the reader".
outFile = open( 'newFile', 'w' )
for line in open( 'oldFile' ):
items = line.split( ',' )
outFile.write( ','.join( items[:2] + items[ 3: ] ) )
outFile.close()
When creating a file, use slashes to specify the directory. For example:
Name the file:
repositoryname/newfoldername/filename
GitHub will automatically create a folder with the name newfoldername.
Use the monthdelta package, it works just like timedelta but for calendar months rather than days/hours/etc.
Here's an example:
from monthdelta import MonthDelta
def prev_month(date):
"""Back one month and preserve day if possible"""
return date + MonthDelta(-1)
Compare that to the DIY approach:
def prev_month(date):
"""Back one month and preserve day if possible"""
day_of_month = date.day
if day_of_month != 1:
date = date.replace(day=1)
date -= datetime.timedelta(days=1)
while True:
try:
date = date.replace(day=day_of_month)
return date
except ValueError:
day_of_month -= 1
The WITH syntax appears to be valid in an inline view, e.g.
UPDATE (WITH comp AS ...
SELECT SomeColumn, ComputedValue FROM t INNER JOIN comp ...)
SET SomeColumn=ComputedValue;
But in the quick tests I did this always failed with ORA-01732: data manipulation operation not legal on this view
, although it succeeded if I rewrote to eliminate the WITH clause. So the refactoring may interfere with Oracle's ability to guarantee key-preservation.
You should be able to use a MERGE, though. Using the simple example you've posted this doesn't even require a WITH clause:
MERGE INTO mytable t
USING (select *, 42 as ComputedValue from mytable where id = 1) comp
ON (t.id = comp.id)
WHEN MATCHED THEN UPDATE SET SomeColumn=ComputedValue;
But I understand you have a more complex subquery you want to factor out. I think that you will be able to make the subquery in the USING
clause arbitrarily complex, incorporating multiple WITH
clauses.
Maybe I'm missing something, but why try to parse the file? Why not just load the YAML and examine the object(s) that result?
If your sample YAML is in some.yml
, then this:
require 'yaml'
thing = YAML.load_file('some.yml')
puts thing.inspect
gives me
{"javascripts"=>[{"fo_global"=>["lazyload-min", "holla-min"]}]}
Assuming that you're constrained to using Date
, you can do the following:
Date diff = new Date(d2.getTime() - d1.getTime());
Here you're computing the differences in milliseconds since the "epoch", and creating a new Date object at an offset from the epoch. Like others have said: the answers in the duplicate question are probably better alternatives (if you aren't tied down to Date
).
What worked for me, using jQuery and tested in IE8, Chrome and Firefox, is:
$(window).bind("beforeunload",function(event) {
if(hasChanged) return "You have unsaved changes";
});
It is important not to return anything if no prompt is required as there are differences between IE and other browser behaviours here.
The command you want is 'du -sk' du = "disk usage"
The -k flag gives you output in kilobytes, rather than the du default of disk sectors (512-byte blocks).
The -s flag will only list things in the top level directory (i.e., the current directory, by default, or the directory specified on the command line). It's odd that du has the opposite behavior of ls in this regard. By default du will recursively give you the disk usage of each sub-directory. In contrast, ls will only give list files in the specified directory. (ls -R gives you recursive behavior.)
It seems to me you are using the wrong version...
TAP-Win32 should not be installed on the 64bit version. Download the right one and try again!
If you would like to use linq, so you can try following:
Dictionary<string, object> dict = new Dictionary<string, object>();
var arr = dict.Select(z => z.Value).ToArray();
I don't know which one is faster or better. Both work for me.
First of all go to the /home directorty then open invisible shell script with some text editor, ~/.bash_profile (macOS) or ~/.bashrc (linux)
go to the bottom, you would see something like this,
export LD_LIBRARY_PATH = /usr/local/lib
change this like that( remove blank point around the =
),
export LD_LIBRARY_PATH=/usr/local/lib
it should be useful.
From commons-lang3
org.apache.commons.lang3.text.WordUtils.capitalizeFully(String str)
window.scroll({top: 0, left: 0, behavior: 'smooth' });
Got it from an article about Smooth Scrolling.
If needed, there are some polyfills available.
If you only have as "click event handler", use a <button>
instead. A link has a specific semantic meaning.
E.g.:
<button onclick="ShowOld(2367,146986,2)">
<img title="next page" alt="next page" src="/themes/me/img/arrn.png">
</button>
This solution does not require of you to define a width and height to your popup div.
And instead of calculating the size of the popup, and minus half to the top, javascript is resizeing the popupContainer to fill out the whole screen...
(100% height, does not work when useing display:table-cell; (wich is required to center something vertically))...
Anyway it works :)
Like that. Except char hi=hello;
should be char hi=hello.charAt(0)
. (Don't forget your break;
statements).
find()
will consider the sub-string against the regular expression where as matches()
will consider complete expression.
find()
will returns true only if the sub-string of the expression matches the pattern.
public static void main(String[] args) {
Pattern p = Pattern.compile("\\d");
String candidate = "Java123";
Matcher m = p.matcher(candidate);
if (m != null){
System.out.println(m.find());//true
System.out.println(m.matches());//false
}
}
Java generics work by checking types at compile time and inserting appropriate casts, but erasing the types in the compiled files. This makes generic libraries usable by code which doesn't understand generics (which was a deliberate design decision) but which means you can't normally find out what the type is at run time.
The public Stack(Class<T> clazz,int capacity)
constructor requires you to pass a Class object at run time, which means class information is available at runtime to code that needs it. And the Class<T>
form means that the compiler will check that the Class object you pass is precisely the Class object for type T. Not a subclass of T, not a superclass of T, but precisely T.
This then means that you can create an array object of the appropriate type in your constructor, which means that the type of the objects you store in your collection will have their types checked at the point they are added to the collection.
Implementing Comparable
means "I can compare myself with another object." This is typically useful when there's a single natural default comparison.
Implementing Comparator
means "I can compare two other objects." This is typically useful when there are multiple ways of comparing two instances of a type - e.g. you could compare people by age, name etc.
Add the Below code in your CSS File to import Google Web Fonts.
@import url(https://fonts.googleapis.com/css?family=Open+Sans);
Replace the Open+Sans parameter value with your Font name.
Your CSS file should look like:
@import url(https://fonts.googleapis.com/css?family=Open+Sans);
body{
font-family: 'Open Sans',serif;
}
Two possibilities:
You can see which table it was (one of them, anyway) by doing a "SHOW ENGINE INNODB STATUS" after the drop fails.
If it turns out to be the latter case, I'd dump and restore the whole server if you can.
MySQL 5.1 and above will give you the name of the table with the FK in the error message.
A bit late to the party but might be valuable to someone with this error..
I just straight copied a bunch of files into an Xcode project, if you forget to add them to your projects Build Phases you will get the error "Undefined symbols for architecture i386". So add your implementation files to Compile Sources, and Xib files to Copy Bundle Resources.
The error was telling me that there was no link to my classes simply because they weren't included in the Compile Sources, quite obvious really but may save someone a headache.
Here is a simple approach in up to 4 steps:
0 - Advise the team you are going to fix the repository
Connect with the team and let them know of the upcoming changes.
1 - Remove the last commit
Assuming your target branch is master
:
$ git checkout master # move to the target branch
$ git reset --hard HEAD^ # remove the last commit
$ git push -f # push to fix the remote
At this point you are done if you are working alone.
2 - Fix your teammate's local repositories
On your teammate's:
$ git checkout master # move to the target branch
$ git fetch # update the local references but do not merge
$ git reset --hard origin/master # match the newly fetched remote state
If your teammate had no new commits, you are done at this point and you should be in sync.
3 - Bringing back lost commits
Let's say a teammate had a new and unpublished commit that were lost in this process.
$ git reflog # find the new commit hash
$ git cherry-pick <commit_hash>
Do this for as many commits as necessary.
I have successfully used this approach many times. It requires a team effort to make sure everything is synchronized.
BufferedImage is a(n) Image, so the implicit cast that you're doing in the second line is able to be compiled directly. If you knew an Image was really a BufferedImage, you would have to cast it explicitly like so:
Image image = ImageIO.read(new File(file));
BufferedImage buffered = (BufferedImage) image;
Because BufferedImage extends Image, it can fit in an Image container. However, any Image can fit there, including ones that are not a BufferedImage, and as such you may get a ClassCastException at runtime if the type does not match, because a BufferedImage cannot hold any other type unless it extends BufferedImage.
You may want to check out my library called DCKit.
You'd be able to make a rounded corner text view (as well as text field/button/plain UIView
) from the Interface Builder
directly:
It also has many other useful features, such as text fields with validation, controls with borders, dashed borders, circle and hairline views etc.
The concatenation operator +
is a binary infix operator which, when applied to lists, returns a new list containing all the elements of each of its two operands. The list.append()
method is a mutator
on list
which appends its single object
argument (in your specific example the list c
) to the subject list
. In your example this results in c
appending a reference to itself (hence the infinite recursion).
The list.extend()
method is also a mutator method which concatenates its sequence
argument with the subject list
. Specifically, it appends each of the elements of sequence
in iteration order.
Being an operator, +
returns the result of the expression as a new value. Being a non-chaining mutator
method, list.extend()
modifies the subject list in-place and returns nothing.
I've added this due to the potential confusion which the Abel's answer above may cause by mixing the discussion of lists, sequences and arrays.
Arrays
were added to Python after sequences and lists, as a more efficient way of storing arrays of integral data types. Do not confuse arrays
with lists
. They are not the same.
From the array docs:
Arrays are sequence types and behave very much like lists, except that the type of objects stored in them is constrained. The type is specified at object creation time by using a type code, which is a single character.
You have to use bracket notation:
var obj = {};
obj[a[i]] = 0;
x.push(obj);
The result will be:
x = [{left: 0}, {top: 0}];
Maybe instead of an array of objects, you just want one object with two properties:
var x = {};
and
x[a[i]] = 0;
This will result in x = {left: 0, top: 0}
.
All: Evidently this is working as designed. Please see new ref man dated 2019-7-23, Section 6.1.6, Security Issues with LOAD DATA LOCAL.
Actually, there are different ways to downcast float to int, depending on the result you want to achieve:
(for int i
, float f
)
round (the closest integer to given float)
i = Math.round(f);
f = 2.0 -> i = 2 ; f = 2.22 -> i = 2 ; f = 2.68 -> i = 3
f = -2.0 -> i = -2 ; f = -2.22 -> i = -2 ; f = -2.68 -> i = -3
note: this is, by contract, equal to (int) Math.floor(f + 0.5f)
truncate (i.e. drop everything after the decimal dot)
i = (int) f;
f = 2.0 -> i = 2 ; f = 2.22 -> i = 2 ; f = 2.68 -> i = 2
f = -2.0 -> i = -2 ; f = -2.22 -> i = -2 ; f = -2.68 -> i = -2
ceil/floor (an integer always bigger/smaller than a given value if it has any fractional part)
i = (int) Math.ceil(f);
f = 2.0 -> i = 2 ; f = 2.22 -> i = 3 ; f = 2.68 -> i = 3
f = -2.0 -> i = -2 ; f = -2.22 -> i = -2 ; f = -2.68 -> i = -2
i = (int) Math.floor(f);
f = 2.0 -> i = 2 ; f = 2.22 -> i = 2 ; f = 2.68 -> i = 2
f = -2.0 -> i = -2 ; f = -2.22 -> i = -3 ; f = -2.68 -> i = -3
For rounding positive values, you can also just use (int)(f + 0.5)
, which works exactly as Math.Round
in those cases (as per doc).
You can also use Math.rint(f)
to do the rounding to the nearest even integer; it's arguably useful if you expect to deal with a lot of floats with fractional part strictly equal to .5 (note the possible IEEE rounding issues), and want to keep the average of the set in place; you'll introduce another bias, where even numbers will be more common than odd, though.
See
http://mindprod.com/jgloss/round.html
http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html
for more information and some examples.
The above problem can be solved by adding the following dependencies in your project, as i was facing the same problem.For more detail answer to this solution please refer link SEVERE:MessageBodyWriter not found for media type=application/xml type=class java.util.HashMap
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.25</version>
</dependency>
Python 2 didn't have closures - it had workarounds that resembled closures.
There are plenty of examples in answers already given - copying in variables to the inner function, modifying an object on the inner function, etc.
In Python 3, support is more explicit - and succinct:
def closure():
count = 0
def inner():
nonlocal count
count += 1
print(count)
return inner
Usage:
start = closure()
start() # prints 1
start() # prints 2
start() # prints 3
The nonlocal
keyword binds the inner function to the outer variable explicitly mentioned, in effect enclosing it. Hence more explicitly a 'closure'.
I cannot solve it with source ./myscript.sh
. It says the source not found error.
Failed also when using . ./myscript.sh
. It gives can't open myscript.sh.
So my option is put it in a text file to be called in the next script.
#!/bin/sh
echo "Perform Operation in su mode"
echo "ARCH=arm" >> environment.txt
echo "Export ARCH=arm Executed"
export PATH="/home/linux/Practise/linux-devkit/bin/:$PATH"
echo "Export path done"
export "CROSS_COMPILE='/home/linux/Practise/linux-devkit/bin/arm-arago-linux-gnueabi-' ## What's next to -?" >> environment.txt
echo "Export CROSS_COMPILE done"
# continue your compilation commands here
...
Tnen call it whenever is needed:
while read -r line; do
line=$(sed -e 's/[[:space:]]*$//' <<<${line})
var=`echo $line | cut -d '=' -f1`; test=$(echo $var)
if [ -z "$(test)" ];then eval export "$line";fi
done <environment.txt
You should put it into command line in windows.
mysqladmin -u [username] -p flush-hosts
**** [MySQL password]
or
mysqladmin flush-hosts -u [username] -p
**** [MySQL password]
For network login use the following command:
mysqladmin -h <RDS ENDPOINT URL> -P <PORT> -u <USER> -p flush-hosts
mysqladmin -h [YOUR RDS END POINT URL] -P 3306 -u [DB USER] -p flush-hosts
you can permanently solution your problem by editing my.ini file[Mysql configuration file] change variables max_connections = 10000;
or
login into MySQL using command line -
mysql -u [username] -p
**** [MySQL password]
put the below command into MySQL window
SET GLOBAL max_connect_errors=10000;
set global max_connections = 200;
check veritable using command-
show variables like "max_connections";
show variables like "max_connect_errors";
import cv2 as cv
capture = cv.VideoCapture(0)
while True:
isTrue,frame = capture.read()
cv.imshow('Video',frame)
if cv.waitKey(20) & 0xFF==ord('d'):
break
capture.release()
cv.destroyAllWindows()
0 <-- refers to the camera , replace it with file path to read a video file
cv.waitKey(20) & 0xFF==ord('d') <-- to destroy window when key is pressed