You can add the src
folder to build path by:
- Select Java perspective.
- Right click on
src
folder. - Select Build Path > Use a source folder.
And you are done. Hope this help.
EDIT: Refer to the Eclipse documentation
I have had this problem when I also recieved a TCP error in the event log...
Drop the DB with sql or right click on it in manager "delete" And restore again.
I have actually started doing this by default. Script the DB drop, recreate and then restore.
As said by Faiyaz, to get default backup location for the instance, you cannot get it into msdb, but you have to look into Registry. You can get it in T-SQL in using xp_instance_regread stored procedure like this:
EXEC master.dbo.xp_instance_regread
N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQLServer',N'BackupDirectory'
The double backslash (\\) is because the spaces into that key name part (Microsoft SQL Server). The "MSSQL12.MSSQLSERVER" part is for default instance name for SQL 2014. You have to adapt to put your own instance name (look into Registry).
Combine Remove Old Backup files with above script then this can perform backup by a scheduler, keep last 10 backup files
echo off
:: set folder to save backup files ex. BACKUPPATH=c:\backup
set BACKUPPATH=<<back up folder here>>
:: set Sql Server location ex. set SERVERNAME=localhost\SQLEXPRESS
set SERVERNAME=<<sql host here>>
:: set Database name to backup
set DATABASENAME=<<db name here>>
:: filename format Name-Date (eg MyDatabase-2009-5-19_1700.bak)
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b)
For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set mytime=%%a%%b)
set DATESTAMP=%mydate%_%mytime%
set BACKUPFILENAME=%BACKUPPATH%\%DATABASENAME%-%DATESTAMP%.bak
echo.
sqlcmd -E -S %SERVERNAME% -d master -Q "BACKUP DATABASE [%DATABASENAME%] TO DISK = N'%BACKUPFILENAME%' WITH INIT , NOUNLOAD , NAME = N'%DATABASENAME% backup', NOSKIP , STATS = 10, NOFORMAT"
echo.
:: In this case, we are choosing to keep the most recent 10 files
:: Also, the files we are looking for have a 'bak' extension
for /f "skip=10 delims=" %%F in ('dir %BACKUPPATH%\*.bak /s/b/o-d/a-d') do del "%%F"
Here is my code, This will backup MySQL database and store it in the specified path.
<?php
function backup_mysql_database($options){
$mtables = array(); $contents = "-- Database: `".$options['db_to_backup']."` --\n";
$mysqli = new mysqli($options['db_host'], $options['db_uname'], $options['db_password'], $options['db_to_backup']);
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
$results = $mysqli->query("SHOW TABLES");
while($row = $results->fetch_array()){
if (!in_array($row[0], $options['db_exclude_tables'])){
$mtables[] = $row[0];
}
}
foreach($mtables as $table){
$contents .= "-- Table `".$table."` --\n";
$results = $mysqli->query("SHOW CREATE TABLE ".$table);
while($row = $results->fetch_array()){
$contents .= $row[1].";\n\n";
}
$results = $mysqli->query("SELECT * FROM ".$table);
$row_count = $results->num_rows;
$fields = $results->fetch_fields();
$fields_count = count($fields);
$insert_head = "INSERT INTO `".$table."` (";
for($i=0; $i < $fields_count; $i++){
$insert_head .= "`".$fields[$i]->name."`";
if($i < $fields_count-1){
$insert_head .= ', ';
}
}
$insert_head .= ")";
$insert_head .= " VALUES\n";
if($row_count>0){
$r = 0;
while($row = $results->fetch_array()){
if(($r % 400) == 0){
$contents .= $insert_head;
}
$contents .= "(";
for($i=0; $i < $fields_count; $i++){
$row_content = str_replace("\n","\\n",$mysqli->real_escape_string($row[$i]));
switch($fields[$i]->type){
case 8: case 3:
$contents .= $row_content;
break;
default:
$contents .= "'". $row_content ."'";
}
if($i < $fields_count-1){
$contents .= ', ';
}
}
if(($r+1) == $row_count || ($r % 400) == 399){
$contents .= ");\n\n";
}else{
$contents .= "),\n";
}
$r++;
}
}
}
if (!is_dir ( $options['db_backup_path'] )) {
mkdir ( $options['db_backup_path'], 0777, true );
}
$backup_file_name = $options['db_to_backup'] . " sql-backup- " . date( "d-m-Y--h-i-s").".sql";
$fp = fopen($options['db_backup_path'] . '/' . $backup_file_name ,'w+');
if (($result = fwrite($fp, $contents))) {
echo "Backup file created '--$backup_file_name' ($result)";
}
fclose($fp);
return $backup_file_name;
}
$options = array(
'db_host'=> 'localhost', //mysql host
'db_uname' => 'root', //user
'db_password' => '', //pass
'db_to_backup' => 'attendance', //database name
'db_backup_path' => '/htdocs', //where to backup
'db_exclude_tables' => array() //tables to exclude
);
$backup_file_name=backup_mysql_database($options);
In this problem, the answer is not updated in a timely. So it's happy to say that in 2020 Migrating to MsSQL
into MySQL
is that much easy. An online converter like RebaseData will do your job with one click. You can just upload your .bak
file which is from MsSQL
and convert it into .sql
format which is readable to MySQL
.
Additional note: This can not only convert your .bak
files but also this site is for all types of Database migrations that you want.
There is the 99% solution to get bak file from remote sql server to your local pc. I described it there in my post http://www.ok.unsode.com/post/2015/06/27/remote-sql-backup-to-local-pc
In general it will look like this:
execute sql script to generate bak files
execute sql script to insert each bak file into temp table with varbinary field type and select this row and download data
repeat prev. step as many time as you have bak files
execute sql script to remove all temporary resources
that's it, you have your bak files on your local pc.
cat db.dump | docker exec ...
way didn't work for my dump (~2Gb). It took few hours and ended up with out-of-memory error.
Instead, I cp'ed dump into container and pg_restore'ed it from within.
Assuming that container id is CONTAINER_ID
and db name is DB_NAME
:
# copy dump into container
docker cp local/path/to/db.dump CONTAINER_ID:/db.dump
# shell into container
docker exec -it CONTAINER_ID bash
# restore it from within
pg_restore -U postgres -d DB_NAME --no-owner -1 /db.dump
I have had to unpack a .ab
-file, too and found this post while looking for an answer. My suggested solution is Android Backup Extractor, a free Java tool for Windows, Linux and Mac OS.
Make sure to take a look at the README, if you encounter a problem. You might have to download further files, if your .ab
-file is password-protected.
Usage:java -jar abe.jar [-debug] [-useenv=yourenv] unpack <backup.ab> <backup.tar> [password]
Example:
Let's say, you've got a file test.ab
, which is not password-protected, you're using Windows and want the resulting .tar
-Archive to be called test.tar
. Then your command should be:
java.exe -jar abe.jar unpack test.ab test.tar ""
You cannot use the SQL Server agent in SQL Server Express. The way I have done it before is to create a SQL Script, and then run it as a scheduled task each day, you could have multiple scheduled tasks to fit in with your backup schedule/retention. The command I use in the scheduled task is:
"C:\Program Files\Microsoft SQL Server\90\Tools\Binn\SQLCMD.EXE" -i"c:\path\to\sqlbackupScript.sql"
Try wih :
SELECT * FROM sys.dm_exec_requests where command like '%BACKUP%'
SELECT command, percent_complete, start_time FROM sys.dm_exec_requests where command like '%BACKUP%'
SELECT command, percent_complete,total_elapsed_time, estimated_completion_time, start_time
FROM sys.dm_exec_requests
WHERE command IN ('RESTORE DATABASE','BACKUP DATABASE')
Here is how to do dump the database (with just the schema):
mysqldump -u root -p"passwd" --no-data --add-drop-database --databases my_db_name | sed 's#/[*]!40000 DROP DATABASE IF EXISTS my_db_name;#' >my_db_name.sql
If you also want the data, remove the --no-data
option.
A workaround, if you want it to be absolutely silent, is to redirect the output to a file (and optionally delete it later).
Robocopy src dest > output.log
del output.log
git bundle
I like that method, as it results in only one file, easier to copy around.
See ProGit: little bundle of joy.
See also "How can I email someone a git repository?", where the command
git bundle create /tmp/foo-all --all
is detailed:
git bundle
will only package references that are shown by git show-ref: this includes heads, tags, and remote heads.
It is very important that the basis used be held by the destination.
It is okay to err on the side of caution, causing the bundle file to contain objects already in the destination, as these are ignored when unpacking at the destination.
For using that bundle, you can clone it, specifying a non-existent folder (outside of any git repo):
git clone /tmp/foo-all newFolder
xcopy "C:\SomeFolderName" "D:\SomeFolderName" /h /i /c /k /e /r /y
Use the above command. It will definitely work.
In this command data will be copied from c:\ to D:\, even folders and system files as well. Here's what the flags do:
/h
copies hidden and system files also/i
if destination does not exist and copying more than one file, assume that destination must be a directory/c
continue copying even if error occurs/k
copies attributes/e
copies directories and subdirectories, including empty ones/r
overwrites read-only files/y
suppress prompting to confirm whether you want to overwrite a fileHere is the simplest command for it
mysql -h<hostname> -u<username> -p<password> -e 'select * from databaseName.tableNaame' | sed 's/\t/,/g' > output.csv
If there is a comma in the column value then we can generate .tsv instead of .csv with the following command
mysql -h<hostname> -u<username> -p<password> -e 'select * from databaseName.tableNaame' > output.csv
You could use something like (Linux):
svnadmin dump repositorypath | gzip > backupname.svn.gz
Since Windows does not support GZip it is just:
svnadmin dump repositorypath > backupname.svn
The best solution seem to be to create a file list and then archive files because you can use other sources and do something else with the list.
For example this allows using the list to calculate size of the files being archived:
#!/bin/sh
backupFileName="backup-big-$(date +"%Y%m%d-%H%M")"
backupRoot="/var/www"
backupOutPath=""
archivePath=$backupOutPath$backupFileName.tar.gz
listOfFilesPath=$backupOutPath$backupFileName.filelist
#
# Make a list of files/directories to archive
#
echo "" > $listOfFilesPath
echo "${backupRoot}/uploads" >> $listOfFilesPath
echo "${backupRoot}/extra/user/data" >> $listOfFilesPath
find "${backupRoot}/drupal_root/sites/" -name "files" -type d >> $listOfFilesPath
#
# Size calculation
#
sizeForProgress=`
cat $listOfFilesPath | while read nextFile;do
if [ ! -z "$nextFile" ]; then
du -sb "$nextFile"
fi
done | awk '{size+=$1} END {print size}'
`
#
# Archive with progress
#
## simple with dump of all files currently archived
#tar -czvf $archivePath -T $listOfFilesPath
## progress bar
sizeForShow=$(($sizeForProgress/1024/1024))
echo -e "\nRunning backup [source files are $sizeForShow MiB]\n"
tar -cPp -T $listOfFilesPath | pv -s $sizeForProgress | gzip > $archivePath
Unicode or other character set characters falling through?
I have seen similar "strange" characters show up on sites I have worked on often when the text is copied from an email or some other document format (e.g. word) into a text editor. The editor can display the non ASCII characters but the browser can't. For the website, I would suggest looking up the HTML entity code for the character and inserting that instead ... or switch to more standard ones.
I encountered this while using Heroku on Ubuntu, and here's how I fixed it:
Add the PostgreSQL apt repository as described at "Linux downloads (Ubuntu) ". (There are similar pages for other operating systems.)
Upgrade to the latest version (9.3 for me) with:
sudo apt-get install postgresql
Recreate the symbolic link in /usr/bin
with:
sudo ln -s /usr/lib/postgresql/9.3/bin/pg_dump /usr/bin/pg_dump --force
The version number in the /usr/lib/postgresql/...
path above should match the server version
number in the error you received. So if your error says, pg_dump: server version: 9.9
, then link to /usr/lib/postgresql/9.9/...
.
I experienced this problem when the .BAK file was temporarily stored in a folder encrypted with BitLocker. It retained the encryption after it was moved to a different folder.
The NETWORK SERVICE account was unable to decrypt the file and gave this thoroughly informative error message.
Removing BitLocker encryption (by unchecking "Encrypt contents to secure data" in the file properties) on the .BAK file resolved the issue.
Table should present with same structure in both dump and database.
`zgrep -a ^"INSERT INTO \`table_name" DbDump-backup.sql.tar.gz | mysql -u<user> -p<password> database_name`
or
`zgrep -a ^"INSERT INTO \`table_name" DbDump-backup.sql | mysql -u<user> -p<password> database_name`
If you just need a simple backup to an archive, you can try my little utility: https://github.com/loomchild/volume-backup
Example
Backup:
docker run -v some_volume:/volume -v /tmp:/backup --rm loomchild/volume-backup backup archive1
will archive volume named some_volume
to /tmp/archive1.tar.bz2
archive file
Restore:
docker run -v some_volume:/volume -v /tmp:/backup --rm loomchild/volume-backup restore archive1
will wipe and restore volume named some_volume
from /tmp/archive1.tar.bz2
archive file.
More info: https://medium.com/@loomchild/backup-restore-docker-named-volumes-350397b8e362
To backup a single database from the command line, use osql or sqlcmd.
"C:\Program Files\Microsoft SQL Server\90\Tools\Binn\osql.exe"
-E -Q "BACKUP DATABASE mydatabase TO DISK='C:\tmp\db.bak' WITH FORMAT"
You'll also want to read the documentation on BACKUP and RESTORE and general procedures.
This code worked for me, it kills all existing connections of a database. All you have to do is change the line Set @dbname = 'databaseName' so it has your database name.
Use Master
Go
Declare @dbname sysname
Set @dbname = 'databaseName'
Declare @spid int
Select @spid = min(spid) from master.dbo.sysprocesses
where dbid = db_id(@dbname)
While @spid Is Not Null
Begin
Execute ('Kill ' + @spid)
Select @spid = min(spid) from master.dbo.sysprocesses
where dbid = db_id(@dbname) and spid > @spid
End
after this I was able to restore it
You can use the free Database Publishing Wizard from Microsoft to generate text files with SQL scripts (CREATE TABLE and INSERT INTO).
You can create such a file for a single table, and you can "restore" the complete table including the data by simply running the SQL script.
1. Create .bat File with backup sqlcmd command
for backup
SqlCmd -E -S Server_Name –Q “BACKUP DATABASE [Name_of_Database] TO DISK=’X:PathToBackupLocation[Name_of_Database].bak'”
for restore
SqlCmd -E -S Server_Name –Q “RESTORE DATABASE [Name_of_Database] FROM DISK=’X:PathToBackupFile[File_Name].bak'”
2. Run the the bat file with WPF/C# code
FileInfo file = new FileInfo("DB\\batfile.bat");
Process process = new Process();
process.StartInfo.FileName = file.FullName;
process.StartInfo.Arguments = @"-X";
process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
process.StartInfo.UseShellExecute = false; //Changed Line
process.StartInfo.RedirectStandardOutput = true; //Changed Line
process.Start();
string output = process.StandardOutput.ReadToEnd(); //Changed Line
process.WaitForExit(); //Moved Line
It looks like the SQL Server doesn't have permission to access file C:\backup.bak. I would check the permissions of the account that is assigned to the SQL Server service account.
As part of the solution, you may want to save your backup files to somewhere other that the root of the C: drive. That might be one reason why you are having permission problems.
pg_dump -h localhost -p 5432 -U postgres -d mydb -t my_table > backup.sql
You can take the backup of a single table but I would suggest to take the backup of whole database and then restore whichever table you need. It is always good to have backup of whole database.
I've used:
pg_restore -c -d database_name filename.dump
Dump
mysqldump db_name table_name > table_name.sql
Dumping from a remote database
mysqldump -u <db_username> -h <db_host> -p db_name table_name > table_name.sql
For further reference:
http://www.abbeyworkshop.com/howto/lamp/MySQL_Export_Backup/index.html
Restore
mysql -u <user_name> -p db_name
mysql> source <full_path>/table_name.sql
or in one line
mysql -u username -p db_name < /path/to/table_name.sql
Credit: John McGrath
Dump
mysqldump db_name table_name | gzip > table_name.sql.gz
Restore
gunzip < table_name.sql.gz | mysql -u username -p db_name
Sorry, but it might even be more complicated, involving pbkdf2, or even a variation of it. Listen to the WWDC 2010 session #209, which mainly talks about the security measures in iOS 4, but also mentions briefly the separate encryption of backups and how they're related.
You can be pretty sure that without knowing the password, there's no way you can decrypt it, even by brute force.
Let's just assume you want to try to enable people who KNOW the password to get to the data of their backups.
I fear there's no way around looking at the actual code in iTunes in order to figure out which algos are employed.
Back in the Newton days, I had to decrypt data from a program and was able to call its decryption function directly (knowing the password, of course) without the need to even undersand its algorithm. It's not that easy anymore, unfortunately.
I'm sure there are skilled people around who could reverse engineer that iTunes code - you just have to get them interested.
In theory, Apple's algos should be designed in a way that makes the data still safe (i.e. practically unbreakable by brute force methods) to any attacker knowing the exact encryption method. And in WWDC session 209 they went pretty deep into details about what they do to accomplish this. Maybe you can actually get answers directly from Apple's security team if you tell them your good intentions. After all, even they should know that security by obfuscation is not really efficient. Try their security mailing list. Even if they do not repond, maybe someone else silently on the list will respond with some help.
Good luck!
I finished my work on this stuff - that is, iOS 4 + iTunes 9.2 update of my backup decoder library for Python - http://www.iki.fi/fingon/iphonebackupdb.py
It does what I need, little documentation, but feel free to copy ideas from there ;-)
(Seems to work fine with my backups at least.)
If you are restoring the folder don't forget to chown the files to mysql:mysql chown -R mysql:mysql /var/lib/mysql-data
otherwise you will get errors when trying to drop a database or add new column etc..
and restart MySQL
service mysql restart
This worked for me:
pg_restore --verbose --clean --no-acl --no-owner --host=localhost --dbname=db_name --username=username latest.dump
Okay, here is a solution to reduce the physical size of the transaction file, but without changing the recovery mode to simple.
Within your database, locate the file_id of the log file using the following query.
SELECT * FROM sys.database_files;
In my instance, the log file is file_id 2. Now we want to locate the virtual logs in use, and do this with the following command.
DBCC LOGINFO;
Here you can see if any virtual logs are in use by seeing if the status is 2 (in use), or 0 (free). When shrinking files, empty virtual logs are physically removed starting at the end of the file until it hits the first used status. This is why shrinking a transaction log file sometimes shrinks it part way but does not remove all free virtual logs.
If you notice a status 2's that occur after 0's, this is blocking the shrink from fully shrinking the file. To get around this do another transaction log backup, and immediately run these commands, supplying the file_id found above, and the size you would like your log file to be reduced to.
-- DBCC SHRINKFILE (file_id, LogSize_MB)
DBCC SHRINKFILE (2, 100);
DBCC LOGINFO;
This will then show the virtual log file allocation, and hopefully you'll notice that it's been reduced somewhat. Because virtual log files are not always allocated in order, you may have to backup the transaction log a couple of times and run this last query again; but I can normally shrink it down within a backup or two.
Using the "point" leads to the creation of a folder named "point" (on Ubuntu 16).
tar -tf site1.bz2 -C /var/www/site1/ .
I dealt with this in more detail and prepared an example. Multi-line recording, plus an exception.
tar -tf site1.bz2\
-C /var/www/site1/ style.css\
-C /var/www/site1/ index.html\
-C /var/www/site1/ page2.html\
-C /var/www/site1/ page3.html\
--exclude=images/*.zip\
-C /var/www/site1/ images/
-C /var/www/site1/ subdir/
/
If you have a full DB dump:
PGPASSWORD="your_pass" psql -h "your_host" -U "your_user" -d "your_database" -f backup.sql
If you have schemas kept separately, however, that won't work. Then you'll need to disable triggers for data insertion, akin to pg_restore --disable-triggers
. You can then use this:
cat database_data_only.gzip | gunzip | PGPASSWORD="your_pass" psql -h "your_host" -U root "your_database" -c 'SET session_replication_role = replica;' -f /dev/stdin
On a side note, it is a very unfortunate downside of postgres, I think. The default way of creating a dump in pg_dump
is incompatible with pg_restore
. With some additional keys, however, it is. WTF?
In addition to the --routines flag you will need to grant the backup user permissions to read the stored procedures:
GRANT SELECT ON `mysql`.`proc` TO <backup user>@<backup host>;
My minimal set of GRANT privileges for the backup user are:
GRANT USAGE ON *.* TO ...
GRANT SELECT, LOCK TABLES ON <target_db>.* TO ...
GRANT SELECT ON `mysql`.`proc` TO ...
Try this:
In the Restore DB wizard window, go to Files tab, Uncheck "Relocate All files to folder" check box then change the restore destination from C: to some other drive. Then proceed with the regular restore process. It will get restored successfully.
SQL Server 2008 R2:
For an existing database that you wish to "restore: from a backup of a different database follow these steps:
I started hacking away a bit on Yar's script and the result is on github, including man pages and install script:
https://github.com/najamelan/git-backup
Installation:
git clone "https://github.com/najamelan/git-backup.git"
cd git-backup
sudo ./install.sh
Welcoming all suggestions and pull request on github.
#!/usr/bin/env ruby
#
# For documentation please sea man git-backup(1)
#
# TODO:
# - make it a class rather than a function
# - check the standard format of git warnings to be conform
# - do better checking for git repo than calling git status
# - if multiple entries found in config file, specify which file
# - make it work with submodules
# - propose to make backup directory if it does not exists
# - depth feature in git config (eg. only keep 3 backups for a repo - like rotate...)
# - TESTING
# allow calling from other scripts
def git_backup
# constants:
git_dir_name = '.git' # just to avoid magic "strings"
filename_suffix = ".git.bundle" # will be added to the filename of the created backup
# Test if we are inside a git repo
`git status 2>&1`
if $?.exitstatus != 0
puts 'fatal: Not a git repository: .git or at least cannot get zero exit status from "git status"'
exit 2
else # git status success
until File::directory?( Dir.pwd + '/' + git_dir_name ) \
or File::directory?( Dir.pwd ) == '/'
Dir.chdir( '..' )
end
unless File::directory?( Dir.pwd + '/.git' )
raise( 'fatal: Directory still not a git repo: ' + Dir.pwd )
end
end
# git-config --get of version 1.7.10 does:
#
# if the key does not exist git config exits with 1
# if the key exists twice in the same file with 2
# if the key exists exactly once with 0
#
# if the key does not exist , an empty string is send to stdin
# if the key exists multiple times, the last value is send to stdin
# if exaclty one key is found once, it's value is send to stdin
#
# get the setting for the backup directory
# ----------------------------------------
directory = `git config --get backup.directory`
# git config adds a newline, so remove it
directory.chomp!
# check exit status of git config
case $?.exitstatus
when 1 : directory = Dir.pwd[ /(.+)\/[^\/]+/, 1]
puts 'Warning: Could not find backup.directory in your git config file. Please set it. See "man git config" for more details on git configuration files. Defaulting to the same directroy your git repo is in: ' + directory
when 2 : puts 'Warning: Multiple entries of backup.directory found in your git config file. Will use the last one: ' + directory
else unless $?.exitstatus == 0 then raise( 'fatal: unknown exit status from git-config: ' + $?.exitstatus ) end
end
# verify directory exists
unless File::directory?( directory )
raise( 'fatal: backup directory does not exists: ' + directory )
end
# The date and time prefix
# ------------------------
prefix = ''
prefix_date = Time.now.strftime( '%F' ) + ' - ' # %F = YYYY-MM-DD
prefix_time = Time.now.strftime( '%H:%M:%S' ) + ' - '
add_date_default = true
add_time_default = false
prefix += prefix_date if git_config_bool( 'backup.prefix-date', add_date_default )
prefix += prefix_time if git_config_bool( 'backup.prefix-time', add_time_default )
# default bundle name is the name of the repo
bundle_name = Dir.pwd.split('/').last
# set the name of the file to the first command line argument if given
bundle_name = ARGV[0] if( ARGV[0] )
bundle_name = File::join( directory, prefix + bundle_name + filename_suffix )
puts "Backing up to bundle #{bundle_name.inspect}"
# git bundle will print it's own error messages if it fails
`git bundle create #{bundle_name.inspect} --all --remotes`
end # def git_backup
# helper function to call git config to retrieve a boolean setting
def git_config_bool( option, default_value )
# get the setting for the prefix-time from git config
config_value = `git config --get #{option.inspect}`
# check exit status of git config
case $?.exitstatus
# when not set take default
when 1 : return default_value
when 0 : return true unless config_value =~ /(false|no|0)/i
when 2 : puts 'Warning: Multiple entries of #{option.inspect} found in your git config file. Will use the last one: ' + config_value
return true unless config_value =~ /(false|no|0)/i
else raise( 'fatal: unknown exit status from git-config: ' + $?.exitstatus )
end
end
# function needs to be called if we are not included in another script
git_backup if __FILE__ == $0
From SQL Server 2008 SSMS (SQL Server Management Studio), simply:
Either:
Right-click, Tasks, Restore, Database
PS: Again, I emphasize: you can easily do this on a "scratch database" - you do not need to overwrite your current database. But you do need to RESTORE.
PPS: You can also accomplish the same thing with T-SQL commands, if you wished to script it.
You can use sklearn.preprocessing:
from sklearn.preprocessing import normalize
data = np.array([
[1000, 10, 0.5],
[765, 5, 0.35],
[800, 7, 0.09], ])
data = normalize(data, axis=0, norm='max')
print(data)
>>[[ 1. 1. 1. ]
[ 0.765 0.5 0.7 ]
[ 0.8 0.7 0.18 ]]
Firstly add a div with id.
<div id="my_map_add" style="width:100%;height:300px;"></div>
<script type="text/javascript">
function my_map_add() {
var myMapCenter = new google.maps.LatLng(28.5383866, 77.34916609);
var myMapProp = {center:myMapCenter, zoom:12, scrollwheel:false, draggable:false, mapTypeId:google.maps.MapTypeId.ROADMAP};
var map = new google.maps.Map(document.getElementById("my_map_add"),myMapProp);
var marker = new google.maps.Marker({position:myMapCenter});
marker.setMap(map);
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=your_key&callback=my_map_add"></script>
Below is the code for drop down using MySql
and PHP
:
<?
$sql="Select PcID from PC"
$q=mysql_query($sql)
echo "<select name=\"pcid\">";
echo "<option size =30 ></option>";
while($row = mysql_fetch_array($q))
{
echo "<option value='".$row['PcID']."'>".$row['PcID']."</option>";
}
echo "</select>";
?>
Try to use anyMatch
of Lambda Expression. It is much better approach.
boolean idExists = tabPane.getTabs().stream()
.anyMatch(t -> t.getId().equals(idToCheck));
Create a Batch file (.bat) in Windows with the following command in it:
%ANDROID_HOME%\tools\bin\sdkmanager.bat --list && pause
NOTE: Using && pause
is necessary to be able to review the information, once it is listed. If not used, the batch file will simply run, show the information in just mere few seconds and exit right away.
You can use apache commons StringUtils isEmpty() or isNotEmpty().
Predicate<Client> hasSameNameAsOneUser =
c -> users.stream().anyMatch(u -> u.getName().equals(c.getName()));
return clients.stream()
.filter(hasSameNameAsOneUser)
.collect(Collectors.toList());
But this is quite inefficient, because it's O(m * n). You'd better create a Set of acceptable names:
Set<String> acceptableNames =
users.stream()
.map(User::getName)
.collect(Collectors.toSet());
return clients.stream()
.filter(c -> acceptableNames.contains(c.getName()))
.collect(Collectors.toList());
Also note that it's not strictly equivalent to the code you have (if it compiled), which adds the same client twice to the list if several users have the same name as the client.
You can also put the tooltip onto one line by removing the "title":
this.chart = new Chart(ctx, {
type: this.props.horizontal ? 'horizontalBar' : 'bar',
options: {
legend: {
display: false,
},
tooltips: {
callbacks: {
label: tooltipItem => `${tooltipItem.yLabel}: ${tooltipItem.xLabel}`,
title: () => null,
}
},
},
});
<%= Html.TextBoxFor(m => Model.Events.Subscribed[i].Action, new {readonly=true})%>
SELECT terms.*
FROM terms JOIN terms_relation ON id=term_id
WHERE taxonomy='categ'
For an empty line in Markdown, escape a space (\
), and then add a new line.
Example:
"\
"
Remember: escape a space and escape a new line. That way is Markdown compliant and should compile properly in any compiler. You may have to select the example text to see how it is set up.
Applying the Observer Pattern with delegates and events in c# is named "Event Pattern" according to MSDN which is a slight variation.
In this Article you will find well structured examples of how to apply the pattern in c# both the classic way and using delegates and events.
Exploring the Observer Design Pattern
public class Stock
{
//declare a delegate for the event
public delegate void AskPriceChangedHandler(object sender,
AskPriceChangedEventArgs e);
//declare the event using the delegate
public event AskPriceChangedHandler AskPriceChanged;
//instance variable for ask price
object _askPrice;
//property for ask price
public object AskPrice
{
set
{
//set the instance variable
_askPrice = value;
//fire the event
OnAskPriceChanged();
}
}//AskPrice property
//method to fire event delegate with proper name
protected void OnAskPriceChanged()
{
AskPriceChanged(this, new AskPriceChangedEventArgs(_askPrice));
}//AskPriceChanged
}//Stock class
//specialized event class for the askpricechanged event
public class AskPriceChangedEventArgs : EventArgs
{
//instance variable to store the ask price
private object _askPrice;
//constructor that sets askprice
public AskPriceChangedEventArgs(object askPrice) { _askPrice = askPrice; }
//public property for the ask price
public object AskPrice { get { return _askPrice; } }
}//AskPriceChangedEventArgs
Go to Providers->RouteServiceProvider.php
There change the route, given below:
class RouteServiceProvider extends ServiceProvider
{
protected $namespace = 'App\Http\Controllers';
/**
* The path to the "home" route for your application.
*
* @var string
*/
public const HOME = '/dashboard';
My controller test in big shortcut:
@RunWith(SpringRunner.class)
@SpringBootTest
public class TaskControllerTest {
//...
//tests
//
}
I just removed "public" and magically it worked.
You're trying to use k
(which is a list) as a key for d
. Lists are mutable and can't be used as dict keys.
Also, you're never initializing the lists in the dictionary, because of this line:
if k not in d == False:
Which should be:
if k not in d == True:
Which should actually be:
if k not in d:
You have upgraded to Razor 3. Remember that VS 12 (until update 4) doesn't support it. Install The Razor 3 from nuget or downgrade it through these step
geekswithblogs.net/anirugu/archive/2013/11/04/how-to-downgrade-razor-3-and-fix-the-issue-that.aspx
Everybody describes issue with getting annotations, but the problem is in definition of your annotation. You should to add to your annotation definition a @Retention(RetentionPolicy.RUNTIME)
:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MyAnnotation{
int id();
}
Jupyter Lab 1.0.4:
In the top menu, go to: Settings->Advanced Settings Editor->Keyboard Shortcuts
Paste this code in the User Preferences
window:
{
"shortcuts": [
{
"command": "runmenu:run-all",
"keys": [
"R",
"R"
],
"selector": "[data-jp-kernel-user]:focus"
}
]
}
user-preferences
window)This will be effective immediately. Here, two consecutive 'R' presses runs all cells (just like two '0' for kernel restart).
Notably, system defaults
has empty templates for all menu commands, including this code (search for run-all
). The selector
was copied from kernelmenu:restart
, to allow printing r
within cells. This system defaults
copy-paste can be generalized to any command.
Try simple & lightweight PathJS lib.
Simple example:
Path.map("#/page").to(function(){
alert('page!');
});
You can use css3 animations to flash an element
.flash {
-moz-animation: flash 1s ease-out;
-moz-animation-iteration-count: 1;
-webkit-animation: flash 1s ease-out;
-webkit-animation-iteration-count: 1;
-ms-animation: flash 1s ease-out;
-ms-animation-iteration-count: 1;
}
@keyframes flash {
0% { background-color: transparent; }
50% { background-color: #fbf8b2; }
100% { background-color: transparent; }
}
@-webkit-keyframes flash {
0% { background-color: transparent; }
50% { background-color: #fbf8b2; }
100% { background-color: transparent; }
}
@-moz-keyframes flash {
0% { background-color: transparent; }
50% { background-color: #fbf8b2; }
100% { background-color: transparent; }
}
@-ms-keyframes flash {
0% { background-color: transparent; }
50% { background-color: #fbf8b2; }
100% { background-color: transparent; }
}
And you jQuery to add the class
jQuery(selector).addClass("flash");
There is not a really pythonic way of repeating something. However, it is a better way:
map(lambda index:do_something(), xrange(10))
If you need to pass the index then:
map(lambda index:do_something(index), xrange(10))
Consider that it returns the results as a collection. So, if you need to collect the results it can help.
I am not sure,how you are opening popup or say model in your code. But you can try something like this..
<html ng-app="MyApp">
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<link rel="stylesheet" href="css/bootstrap.min.css" />
<script type="text/javascript">
var myApp = angular.module("MyApp", []);
myApp.controller('MyController', function ($scope) {
$scope.open = function(){
var modalInstance = $modal.open({
templateUrl: '/assets/yourOpupTemplatename.html',
backdrop:'static',
keyboard:false,
controller: function($scope, $modalInstance) {
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
$scope.ok = function () {
$modalInstance.close();
};
}
});
}
});
</script>
</head>
<body ng-controller="MyController">
<button class="btn btn-primary" ng-click="open()">Test Modal</button>
<!-- Confirmation Dialog -->
<div class="modal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Delete confirmation</h4>
</div>
<div class="modal-body">
<p>Are you sure?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" ng-click="cancel()">No</button>
<button type="button" class="btn btn-primary" ng-click="ok()">Yes</button>
</div>
</div>
</div>
</div>
<!-- End of Confirmation Dialog -->
</body>
</html>
As you are in python3 , use dict.items()
instead of dict.iteritems()
iteritems()
was removed in python3, so you can't use this method anymore.
Take a look at Python 3.0 Wiki Built-in Changes section, where it is stated:
Removed
dict.iteritems()
,dict.iterkeys()
, anddict.itervalues()
.Instead: use
dict.items()
,dict.keys()
, anddict.values()
respectively.
What about :
The '
character in SQL is used for string constants. In this case it is used for ending the string constant and not for comment.
In regards to PowerShell 5.1 (this is so much easier in PowerShell 7)...
Operating off the assumption that we have a file named jsonConfigFile.json
with the following content from your post:
{
"Stuffs": [
{
"Name": "Darts",
"Type": "Fun Stuff"
},
{
"Name": "Clean Toilet",
"Type": "Boring Stuff"
}
]
}
This will create an ordered hashtable from a JSON file to help make retrieval easier:
$json = [ordered]@{}
(Get-Content "jsonConfigFile.json" -Raw | ConvertFrom-Json).PSObject.Properties |
ForEach-Object { $json[$_.Name] = $_.Value }
$json.Stuffs
will list a nice hashtable, but it gets a little more complicated from here. Say you want the Type
key's value associated with the Clean Toilet
key, you would retrieve it like this:
$json.Stuffs.Where({$_.Name -eq "Clean Toilet"}).Type
It's a pain in the ass, but if your goal is to use JSON on a barebones Windows 10 installation, this is the best way to do it as far as I've found.
If you are accessing your repositories over the SSH protocol, you will receive a warning message each time your client connects to a new IP address for github.com. As long as the IP address from the warning is in the range of IP addresses , you shouldn't be concerned. Specifically, the new addresses that are being added this time are in the range from
192.30.252.0 to 192.30.255.255
. The warning message looks like this:Warning: Permanently added the RSA host key for IP address '$IP' to the list of
To make an image responsive use the following:
CSS
.responsive-image {
width: 950px;//Any width you want to set the image to.
max-width: 100%;
height: auto;
}
HTML
<img class="responsive-image" src="IMAGE URL">
What you are passing to JSON.parse method must be a valid JSON after removing the wrapping quotes for string.
so something
is not a valid JSON but "something"
is.
A valid JSON is -
JSON = null
/* boolean literal */
or true or false
/* A JavaScript Number Leading zeroes are prohibited; a decimal point must be followed by at least one digit.*/
or JSONNumber
/* Only a limited sets of characters may be escaped; certain control characters are prohibited; the Unicode line separator (U+2028) and paragraph separator (U+2029) characters are permitted; strings must be double-quoted.*/
or JSONString
/* Property names must be double-quoted strings; trailing commas are forbidden. */
or JSONObject
or JSONArray
Examples -
JSON.parse('{}'); // {}
JSON.parse('true'); // true
JSON.parse('"foo"'); // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse('null'); // null
JSON.parse("'foo'"); // error since string should be wrapped by double quotes
You may want to look JSON.
Check the MySQL Datetime Functions:
Try this:
SELECT *
FROM tableA
WHERE YEAR(columnName) = YEAR(CURRENT_DATE()) AND
MONTH(columnName) = MONTH(CURRENT_DATE());
To include CSS and jQuery in your plugin is easy, try this:
// register jquery and style on initialization
add_action('init', 'register_script');
function register_script() {
wp_register_script( 'custom_jquery', plugins_url('/js/custom-jquery.js', __FILE__), array('jquery'), '2.5.1' );
wp_register_style( 'new_style', plugins_url('/css/new-style.css', __FILE__), false, '1.0.0', 'all');
}
// use the registered jquery and style above
add_action('wp_enqueue_scripts', 'enqueue_style');
function enqueue_style(){
wp_enqueue_script('custom_jquery');
wp_enqueue_style( 'new_style' );
}
I found this great snipped from this site How to include jQuery and CSS in WordPress – The WordPress Way
Hope that helps.
If you can create a string xml you can easily transform it to the xml document object e.g. -
String xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><a><b></b><c></c></a>";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xmlString)));
} catch (Exception e) {
e.printStackTrace();
}
You can use the document object and xml parsing libraries or xpath to get back the ip address.
You dont need call addSheet()
method. After creating sheet, it already add to excel. Here i fixed some codes:
//First sheet
$sheet = $objPHPExcel->getActiveSheet();
//Start adding next sheets
$i=0;
while ($i < 10) {
// Add new sheet
$objWorkSheet = $objPHPExcel->createSheet($i); //Setting index when creating
//Write cells
$objWorkSheet->setCellValue('A1', 'Hello'.$i)
->setCellValue('B2', 'world!')
->setCellValue('C1', 'Hello')
->setCellValue('D2', 'world!');
// Rename sheet
$objWorkSheet->setTitle("$i");
$i++;
}
Add *.DS_Store
to your .gitignore file. That works for me perfectly
getTimeZoneOffset() and toLocaleString are good for basic date work, but if you need real timezone support, look at mde's TimeZone.js.
There's a few more options discussed in the answer to this question
I think the best codes are these:
$('#accordion1').collapse({
toggle: false
}).on('show',function (e) {
$(e.target).parent().find(".icon-chevron-down").removeClass("icon-chevron-down").addClass("icon-chevron-up");
}).on('hide', function (e) {
$(e.target).parent().find(".icon-chevron-up").removeClass("icon-chevron-up").addClass("icon-chevron-down");
});
A simple way to find actionbar height is from Activity onPrepareOptionMenu
method.
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
....
int actionBarHeight = getActionBar().getHeight());
.....
}
The button code should be moved to the PlaceholderFragment()
class. There you will call the layout fragment_main.xml
in the onCreateView
method. Like so
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
Button buttonClick = (Button) view.findViewById(R.id.button);
buttonClick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onButtonClick((Button) view);
}
});
return view;
}
Yes this is the way:
Right click on your program, select run -> run configuration then on vm argument
-Denv=EnvironmentName -Dcucumber.options="--tags @ifThereisAnyTag"
Then you can apply and close.
you could get your clock() value and check if it is odd or even. I dont know if it is %50 of true
And you can custom-create your random function:
static double s=System.nanoTime();//in the instantiating of main applet
public static double randoom()
{
s=(double)(((555555555* s+ 444444)%100000)/(double)100000);
return s;
}
numbers 55555.. and 444.. are the big numbers to get a wide range function please ignore that skype icon :D
If you only want to have a list of large files, then I'd like to provide you with the following one-liner:
join -o "1.1 1.2 2.3" <(git rev-list --objects --all | sort) <(git verify-pack -v objects/pack/*.idx | sort -k3 -n | tail -5 | sort) | sort -k3 -n
Whose output will be:
commit file name size in bytes
72e1e6d20... db/players.sql 818314
ea20b964a... app/assets/images/background_final2.png 6739212
f8344b9b5... data_test/pg_xlog/000000010000000000000001 1625545
1ecc2395c... data_development/pg_xlog/000000010000000000000001 16777216
bc83d216d... app/assets/images/background_1forfinal.psd 95533848
The last entry in the list points to the largest file in your git history.
You can use this output to assure that you're not deleting stuff with BFG you would have needed in your history.
Be aware, that you need to clone your repository with --mirror
for this to work.
Pseudo code, something like:
CASE
When CHARINDEX('lactulose', dbo.Table.Column) > 0 Then 'BP Medication'
ELSE ''
END AS 'Medication Type'
This does not care where the keyword is found in the list and avoids depending on formatting of spaces and commas.
Simply add this to the head of your document:
<link rel="shortcut icon" type="image/png" href="/img/icon-192x192.png">
<link rel="shortcut icon" sizes="192x192" href="/img/icon-192x192.png">
<link rel="apple-touch-icon" href="/img/icon-192x192.png">
The last link is for Apple (home screen), the second one for Android (home screen) and the first one for the rest.
Note that this solution does not support "tiles" in Windows 8/10. It does, however, support images in shortcuts, bookmarks and browser-tabs.
The size is exactly the size the Android home screen uses. The Apple home screen icon size is 60px (3x), so 180px and will be scaled down. Other platforms use the default shortcut icon, which will be scaled down too.
function addAttr(scope, el, attrName, attrValue) {
el.replaceWith($compile(el.clone().attr(attrName, attrValue))(scope));
}
This appears to be a bug in Bundler not recognizing the default gems installed along with ruby 2.x. I still experienced the problem even with the latest version of bundler (1.5.3).
One solution is to simply delete json-1.8.1.gemspec from the default gemspec directory.
rm ~/.rubies/ruby-2.1.0/lib/ruby/gems/2.1.0/specifications/default/json-1.8.1.gemspec
After doing this, bundler should have no problem locating the gem. Note that I am using chruby. If you're using some other ruby manager, you'll have to update your path accordingly.
I've got this error and I finally solved it with the command below.
restorecon -r /var/www/html
The issue is caused when you mv something from one place to another. It preserves the selinux context of the original when you move it, so if you untar something in /home or /tmp it gets given an selinux context that matches its location. Now you mv that to /var/www/html and it takes the context saying it belongs in /tmp or /home with it and httpd is not allowed by policy to access those files.
If you cp the files instead of mv them, the selinux context gets assigned according to the location you're copying to, not where it's coming from. Running restorecon puts the context back to its default and fixes it too.
Here's one way:
import os
import shutil
def copy_over(path, from_name, to_name):
for path, dirname, fnames in os.walk(path):
for fname in fnames:
if fname == from_name:
shutil.copy(os.path.join(path, from_name), os.path.join(path, to_name))
copy_over('.', 'index.tpl', 'index.html')
One click answer:
open this URL:
https://portal.azure.com/#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/Properties
In case of enum both are correct and right!!
You can use this code to find correct browser and you can make changes for any target browser.....
function myFunction() { _x000D_
if((navigator.userAgent.indexOf("Opera") || navigator.userAgent.indexOf('OPR')) != -1 ){_x000D_
alert('Opera');_x000D_
}_x000D_
else if(navigator.userAgent.indexOf("Chrome") != -1 ){_x000D_
alert('Chrome');_x000D_
}_x000D_
else if(navigator.userAgent.indexOf("Safari") != -1){_x000D_
alert('Safari');_x000D_
}_x000D_
else if(navigator.userAgent.indexOf("Firefox") != -1 ){_x000D_
alert('Firefox');_x000D_
}_x000D_
else if((navigator.userAgent.indexOf("MSIE") != -1 ) || (!!document.documentMode == true )){_x000D_
alert('IE'); _x000D_
} _x000D_
else{_x000D_
alert('unknown');_x000D_
}_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title>Browser detector</title>_x000D_
_x000D_
</head>_x000D_
<body onload="myFunction()">_x000D_
// your code here _x000D_
</body>_x000D_
</html>
_x000D_
Easiest way, as I see it, is to use a for loop that calls a second batch file for processing, passing that second file the base name.
According to the for /? help, basename can be extracted using the nifty ~n option. So, the base script would read:
for %%f in (*.in) do call process.cmd %%~nf
Then, in process.cmd, assume that %0 contains the base name and act accordingly. For example:
echo The file is %0
copy %0.in %0.out
ren %0.out monkeys_are_cool.txt
There might be a better way to do this in one script, but I've always been a bit hazy on how to pull of multiple commands in a single for loop in a batch file.
EDIT: That's fantastic! I had somehow missed the page in the docs that showed that you could do multi-line blocks in a FOR loop. I am going to go have to go back and rewrite some batch files now...
Easiest and correct way on a single line:
sqlite3 old.db ".dump mytable" | sqlite3 new.db
The primary key and the columns types will be kept.
we have to install the M2E Eclipse WTP plugin To install: Preferences->Maven->Discovery->Open Catalog and choose the WTP plugin.
And restart eclipse
edtFTPnet is a free, fast, open source FTP library for .NET, written in C#.
Try explode:
$myString = "9,[email protected],8";
$myArray = explode(',', $myString);
print_r($myArray);
Output :
Array
(
[0] => 9
[1] => [email protected]
[2] => 8
)
If you are on Mac OS X just use Simulator. I don't know if it is available by default but it looks like it is a part of the Xcode suite.
Anyway it is free and really useful, it allows you to simulate many popular Apple devices:
I was getting this error though there were no (obvious) brackets in my URL, and in my situation the --globoff command will not solve the issue.
For example (doing this on on mac in iTerm2):
for endpoint in $(grep some_string output.txt); do curl "http://1.2.3.4/api/v1/${endpoint}" ; done
I have grep aliased to "grep --color=always". As a result, the above command will result in this error, with some_string highlighted in whatever colour you have grep set to:
curl: (3) bad range in URL position 31:
http://1.2.3.4/api/v1/lalalasome_stringlalala
The terminal was transparently translating the [colour\codes]some_string[colour\codes] into the expected no-special-characters URL when viewed in terminal, but behind the scenes the colour codes were being sent in the URL passed to curl, resulting in brackets in your URL.
Solution is to not use match highlighting.
Old versions of JavaScript (< ES5) require using a for..in
loop:
for (var key in data) {
if (data.hasOwnProperty(key)) {
// do something with key
}
}
ES5 introduces Object.keys and Array#forEach which makes this a little easier:
var data = { foo: 'bar', baz: 'quux' };
Object.keys(data); // ['foo', 'baz']
Object.keys(data).map(function(key){ return data[key] }) // ['bar', 'quux']
Object.keys(data).forEach(function (key) {
// do something with data[key]
});
ES2017 introduces Object.values
and Object.entries
.
Object.values(data) // ['bar', 'quux']
Object.entries(data) // [['foo', 'bar'], ['baz', 'quux']]
You could add another empty layout below that one and set them both to have the same layout weight. They should get 50% of the space each.
I managed to monitor app navigation going to background and back to foreground by implementing a BaseActivity that exploits the use of onResume, onPause and onStop activity callbacks. Here is my implementations.
override fun onResume() {
super.onResume()
if (AppActivityState.state == AppState.ON_LAUNCHED) {
// We are in the first launch.
onLaunched()
} else {
if (AppActivityState.state == AppState.ON_BACKGROUND) {
// We came from background to foreground.
AppActivityState.state = AppState.ON_FOREGROUND
onForeground()
} else {
// We are just navigating through pages.
AppActivityState.state = AppState.RESUMED
}
}
}
override fun onPause() {
super.onPause()
// If state is followed by onStop then it means we will going to background.
AppActivityState.state = AppState.PAUSED
}
override fun onStop() {
super.onStop()
// App will go to background base on the 'pause' cue.
if (AppActivityState.state == AppState.PAUSED) {
AppActivityState.state = AppState.ON_BACKGROUND
onBackground()
}
}
After creating BaseActivity, you just have to extend this activity to any activity on your app.
In these type of implementation, you can accurately detect the following: - onBackground > app will go to background - onForeground > app will go back to foreground - onLaunch > app just opened
I hope this will help you :)
I hope my script help you.
<i class="mostrar-producto">mostrar...</i>
<div class="producto" style="display:none;position: absolute;">Producto</div>
My script
<script>
$(".mostrar-producto").mouseover(function(){
$(".producto").fadeIn();
});
$(".mostrar-producto").mouseleave(function(){
$(".producto").fadeOut();
});
</script>
#footer{
position: fixed;
bottom: 0;
}
I had the same problem. No matter how much I was increasing memory_limit (even tried 4GB) I was getting the same error, until I figured out it was because of wrong database credentials setted up in .env
file
Yes, it's called System.arraycopy(Object, int, Object, int, int) .
It's still going to perform a loop somewhere though, unless this can get optimized into something like REP STOSW
by the JIT (in which case the loop is inside the CPU).
int[] src = new int[] {1, 2, 3, 4, 5};
int[] dst = new int[3];
System.arraycopy(src, 1, dst, 0, 3); // Copies 2, 3, 4 into dst
Try making
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"MyFile"];
as
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"MyFile.txt"];
If you want the whole record,here is a lambda way:
var q = _context
.lasttraces
.GroupBy(s => s.AccountId)
.Select(s => s.OrderByDescending(x => x.Date).FirstOrDefault());
Glide.with(context)
.load("http://test.com/yourimage.jpg")
.asBitmap() // ????????? ??? ? ?????? ??????
.fitCenter()
.into(new SimpleTarget<Bitmap>(100,100) {
@Override
public void onResourceReady(Bitmap bitmap, GlideAnimation<? super Bitmap> glideAnimation) {
// do something with you bitmap
bitmap
}
});
A complete solution in swift, in your view controller
// you can use your own logic to determine if you need to hide status bar
// I just put a var here for now
var hideStatusBar = false
override func preferStatusBarHidden() -> Bool {
return hideStatus
}
// in other method to manually toggle status bar
func updateUI() {
hideStatusBar = true
// call this method to update status bar
prefersStatusBarHidden()
}
Put it all in one document and use this:
/* Smartphones (portrait and landscape) ----------- */
@media only screen
and (min-device-width : 320px)
and (max-device-width : 480px) {
/* Styles */
}
/* Smartphones (landscape) ----------- */
@media only screen
and (min-width : 321px) {
/* Styles */
}
/* Smartphones (portrait) ----------- */
@media only screen
and (max-width : 320px) {
/* Styles */
}
/* iPads (portrait and landscape) ----------- */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px) {
/* Styles */
}
/* iPads (landscape) ----------- */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : landscape) {
/* Styles */
}
/* iPads (portrait) ----------- */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : portrait) {
/* Styles */
}
/* Desktops and laptops ----------- */
@media only screen
and (min-width : 1224px) {
/* Styles */
}
/* Large screens ----------- */
@media only screen
and (min-width : 1824px) {
/* Styles */
}
/* iPhone 4 - 5s ----------- */
@media
only screen and (-webkit-min-device-pixel-ratio : 1.5),
only screen and (min-device-pixel-ratio : 1.5) {
/* Styles */
}
/* iPhone 6 ----------- */
@media
only screen and (max-device-width: 667px)
only screen and (-webkit-device-pixel-ratio: 2) {
/* Styles */
}
/* iPhone 6+ ----------- */
@media
only screen and (min-device-width : 414px)
only screen and (-webkit-device-pixel-ratio: 3) {
/*** You've spent way too much on a phone ***/
}
/* Samsung Galaxy S7 Edge ----------- */
@media only screen
and (-webkit-min-device-pixel-ratio: 3),
and (min-resolution: 192dpi)and (max-width:640px) {
/* Styles */
}
Source: http://css-tricks.com/snippets/css/media-queries-for-standard-devices/
At this point, I would definitely consider using em
values instead of pixels. For more information, check this post: https://zellwk.com/blog/media-query-units/.
Make resource controller with Model.
php artisan make:controller PostController --model=Post
You can try this also
input[type="text"] {
outline-style: none;
}
or
.classname input{
outline-style: none;
}
The -m
switch of PuTTY takes a path to a script file as an argument, not a command.
Reference: https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter3.html#using-cmdline-m
So you have to save your command (command_run
) to a plain text file (e.g. c:\path\command.txt
) and pass that to PuTTY:
putty.exe -ssh user@host -pw password -m c:\path\command.txt
Though note that you should use Plink (a command-line connection tool from PuTTY suite). It's a console application, so you can redirect its output to a file (what you cannot do with PuTTY).
A command-line syntax is identical, an output redirection added:
plink.exe -ssh user@host -pw password -m c:\path\command.txt > output.txt
See Using the command-line connection tool Plink.
And with Plink, you can actually provide the command directly on its command-line:
plink.exe -ssh user@host -pw password command > output.txt
Similar questions:
Automating running command on Linux from Windows using PuTTY
Executing command in Plink from a batch file
This comes in useful when you have global variables. You declare the existence of global variables in a header, so that each source file that includes the header knows about it, but you only need to “define” it once in one of your source files.
To clarify, using extern int x;
tells the compiler that an object of type int
called x
exists somewhere. It's not the compilers job to know where it exists, it just needs to know the type and name so it knows how to use it. Once all of the source files have been compiled, the linker will resolve all of the references of x
to the one definition that it finds in one of the compiled source files. For it to work, the definition of the x
variable needs to have what's called “external linkage”, which basically means that it needs to be declared outside of a function (at what's usually called “the file scope”) and without the static
keyword.
#ifndef HEADER_H
#define HEADER_H
// any source file that includes this will be able to use "global_x"
extern int global_x;
void print_global_x();
#endif
#include "header.h"
// since global_x still needs to be defined somewhere,
// we define it (for example) in this source file
int global_x;
int main()
{
//set global_x here:
global_x = 5;
print_global_x();
}
#include <iostream>
#include "header.h"
void print_global_x()
{
//print global_x here:
std::cout << global_x << std::endl;
}
No. Regular expressions in Python are handled by the re
module.
article = re.sub(r'(?is)</html>.+', '</html>', article)
In general:
text_after = re.sub(regex_search_term, regex_replacement, text_before)
CEF offers lot of flexibility and options for customisation. But if the intent is to develop quickly node-webkit is also a good option. Node-web kit also offers ability to call node modules directly from DOM.
If there aren't any native modules to integrate Node-Webkit can offer better mileage. With native modules C/C++ or even C# it is better with CEF.
I went through all the examples and answers and in a way or another they didn't address my need. So I will list her a scenario that I need more help and I hope this can explain the idea more.
I need to develop a tool which is getting a file to process it and it needs some optional configuration file to be used to configure the tool.
so what I need is something like the following
mytool.py file.text -config config-file.json
Here is the solution code
import argparse
def main():
parser = argparse.ArgumentParser(description='This example for a tool to process a file and configure the tool using a config file.')
parser.add_argument('filename', help="Input file either text, image or video")
# parser.add_argument('config_file', help="a JSON file to load the initial configuration ")
# parser.add_argument('-c', '--config_file', help="a JSON file to load the initial configuration ", default='configFile.json', required=False)
parser.add_argument('-c', '--config', default='configFile.json', dest='config_file', help="a JSON file to load the initial configuration " )
parser.add_argument('-d', '--debug', action="store_true", help="Enable the debug mode for logging debug statements." )
args = parser.parse_args()
filename = args.filename
configfile = args.config_file
print("The file to be processed is", filename)
print("The config file is", configfile)
if args.debug:
print("Debug mode enabled")
else:
print("Debug mode disabled")
print("and all arguments are: ", args)
if __name__ == '__main__':
main()
I will show the solution in multiple enhancements to show the idea
List all input as mandatory inputs so second argument will be
parser.add_argument('config_file', help="a JSON file to load the initial configuration ")
When we get the help command for this tool we find the following outcome
(base) > python .\argparser_example.py -h
usage: argparser_example.py [-h] filename config_file
This example for a tool to process a file and configure the tool using a config file.
positional arguments:
filename Input file either text, image or video
config_file a JSON file to load the initial configuration
optional arguments:
-h, --help show this help message and exit
and when I execute it as the following
(base) > python .\argparser_example.py filename.txt configfile.json
the outcome will be
The file to be processed is filename.txt
The config file is configfile.json
and all arguments are: Namespace(config_file='configfile.json', filename='filename.txt')
But the config file should be optional, I removed it from the arguments
(base) > python .\argparser_example.py filename.txt
The outcome will be is:
usage: argparser_example.py [-h] filename config_file
argparser_example.py: error: the following arguments are required: c
Which means we have a problem in the tool
So to make it optional I modified the program as follows
parser.add_argument('-c', '--config', help="a JSON file to load the initial configuration ", default='configFile.json', required=False)
The help outcome should be
usage: argparser_example.py [-h] [-c CONFIG] filename
This example for a tool to process a file and configure the tool using a config file.
positional arguments:
filename Input file either text, image or video
optional arguments:
-h, --help show this help message and exit
-c CONFIG, --config CONFIG
a JSON file to load the initial configuration
so when I execute the program
(base) > python .\argparser_example.py filename.txt
the outcome will be
The file to be processed is filename.txt
The config file is configFile.json
and all arguments are: Namespace(config_file='configFile.json', filename='filename.txt')
with arguments like
(base) > python .\argparser_example.py filename.txt --config_file anotherConfig.json
The outcome will be
The file to be processed is filename.txt
The config file is anotherConfig.json
and all arguments are: Namespace(config_file='anotherConfig.json', filename='filename.txt')
to change the flag name from --config_file
to --config
while we keep the variable name as is we modify the code to include dest='config_file'
as the following:
parser.add_argument('-c', '--config', help="a JSON file to load the initial configuration ", default='configFile.json', dest='config_file')
and the command will be
(base) > python .\argparser_example.py filename.txt --config anotherConfig.json
To add the support for having a debug mode flag, we need to add a flag in the arguments to support a boolean debug flag. To implement it i added the following:
parser.add_argument('-d', '--debug', action="store_true", help="Enable the debug mode for logging debug statements." )
the tool command will be:
(carnd-term1-38) > python .\argparser_example.py image.jpg -c imageConfig,json --debug
the outcome will be
The file to be processed is image.jpg
The config file is imageConfig,json
Debug mode enabled
and all arguments are: Namespace(config_file='imageConfig,json', debug=True, filename='image.jpg')
Managed to get answer after do some google..
echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
apt-get update
# Java 7
apt-get install oracle-java7-installer
# For Java 8 command is:
apt-get install oracle-java8-installer
This worked great for me. Don't forget to put a filler div in there where the navigation bar used to be, or else the content will jump every time it's fixed/unfixed.
function setSkrollr(){
var objDistance = $navbar.offset().top;
$(window).scroll(function() {
var myDistance = $(window).scrollTop();
if (myDistance > objDistance){
$navbar.addClass('navbar-fixed-top');
}
if (objDistance > myDistance){
$navbar.removeClass('navbar-fixed-top');
}
});
}
It is unclearly why this error happened with me but I solved. I used same layout, in-line or using include, both of them cause NPE error. So I think it's not layout issue.
I had an abstract class call BaseActivity extends ActionBarActivity which have initActionBar() method. I override and call this method in OnCreate of child class. Something like that:
android.support.v7.app.ActionBar mActionBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book_appointment);
// Inject View using ButterKnife
ButterKnife.inject(this);
// Init toolbar & status bar
initActionBar();
}
@Override
protected void initActionBar() {
super.initActionBar();
setSupportActionBar(mToolBar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mActionBar = getSupportActionBar();
mActionBar.setDisplayHomeAsUpEnabled(true);
mActionBar.setHomeButtonEnabled(true);
}
I HAD NPE ERROR WITH ABOVE CODE. I DON'T KNOW WHY I'M WRONG. I SOLVE BY BELOW CODE AND IT'S LOOK SAME.
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book_appointment);
ButterKnife.inject(this);
setSupportActionBar(mToolBar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mActionBar = getSupportActionBar();
mActionBar.setDisplayHomeAsUpEnabled(true);
mActionBar.setHomeButtonEnabled(true);
initActionBar();
}
@Override
protected void initActionBar() {
super.initActionBar();
}
I'd like to expand on Leor's suggestion for anyone confused on how to compute the nearest location and actually provide a working solution:
I'm using markers in a markers
array e.g. var markers = [];
.
Then let's have our position as something like var location = new google.maps.LatLng(51.99, -0.74);
Then we simply reduce our markers against the location we have like so:
markers.reduce(function (prev, curr) {
var cpos = google.maps.geometry.spherical.computeDistanceBetween(location.position, curr.position);
var ppos = google.maps.geometry.spherical.computeDistanceBetween(location.position, prev.position);
return cpos < ppos ? curr : prev;
}).position
What pops out is your closest marker LatLng
object.
This depend on how you want to incorporate it. The scenario 1. click on a link 2. explorer window popped up
<a href="\\server\folder\path" target="_blank">click</a>
If there is a need in a fancy UI - then it will barely serve as a solution.
Given a list of dates dates
:
Max date is max(dates)
Min date is min(dates)
summation
and your other functions are defined after they're used in main
, and so the compiler has made a guess about it's signature; in other words, an implicit declaration has been assumed.
You should declare the function before it's used and get rid of the warning. In the C99 specification, this is an error.
Either move the function bodies before main
, or include method signatures before main
, e.g.:
#include <stdio.h>
int summation(int *, int *, int *);
int main()
{
// ...
Just add box-sizing:
input[type="text"] {
box-sizing: border-box;
}
This worked for me:
<video src="file.mp4" controls style="max-width:100%; height:auto"></video>
The docs indicate that numpy.correlate
is not what you are looking for:
numpy.correlate(a, v, mode='valid', old_behavior=False)[source]
Cross-correlation of two 1-dimensional sequences.
This function computes the correlation as generally defined in signal processing texts:
z[k] = sum_n a[n] * conj(v[n+k])
with a and v sequences being zero-padded where necessary and conj being the conjugate.
Instead, as the other comments suggested, you are looking for a Pearson correlation coefficient. To do this with scipy try:
from scipy.stats.stats import pearsonr
a = [1,4,6]
b = [1,2,3]
print pearsonr(a,b)
This gives
(0.99339926779878274, 0.073186395040328034)
You can also use numpy.corrcoef
:
import numpy
print numpy.corrcoef(a,b)
This gives:
[[ 1. 0.99339927]
[ 0.99339927 1. ]]
SELECT * FROM table WHERE field1 NOT LIKE '%$x%';
(Make sure you escape $x properly beforehand to avoid SQL injection)
Edit: NOT IN
does something a bit different - your question isn't totally clear so pick which one to use. LIKE 'xxx%'
can use an index. LIKE '%xxx'
or LIKE '%xxx%'
can't.
You can use
helpers.<helper>
in Rails 5+ (or ActionController::Base.helpers.<helper>
)view_context.<helper>
(Rails 4 & 3) (WARNING: this instantiates a new view instance per call)@template.<helper>
(Rails 2) singleton.helper
include
the helper in the controller (WARNING: will make all helper methods into controller actions)To run the .bat, and have access to the last exit code, run it as:
& .\my-app\my-fle.bat
Try this:-
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Online Student Portal</title>
</head>
<body>
<form action="">
<input type="button" value="Add Students" onclick="window.location.href='Students.html';"/>
<input type="button" value="Add Courses" onclick="window.location.href='Courses.html';"/>
<input type="button" value="Student Payments" onclick="window.location.href='Payment.html';"/>
</form>
</body>
</html>
You need an HTML element for each column in your layout.
I’d suggest:
<div class="two-col">
<div class="col1">
<label for="field1">Field One:</label>
<input id="field1" name="field1" type="text">
</div>
<div class="col2">
<label for="field2">Field Two:</label>
<input id="field2" name="field2" type="text">
</div>
</div>
.two-col {
overflow: hidden;/* Makes this div contain its floats */
}
.two-col .col1,
.two-col .col2 {
width: 49%;
}
.two-col .col1 {
float: left;
}
.two-col .col2 {
float: right;
}
.two-col label {
display: block;
}
For multiple files; note the newer "multiple" attribute for input:
Form:
@using (Html.BeginForm("FileImport","Import",FormMethod.Post, new {enctype = "multipart/form-data"}))
{
<label for="files">Filename:</label>
<input type="file" name="files" multiple="true" id="files" />
<input type="submit" />
}
Controller:
[HttpPost]
public ActionResult FileImport(IEnumerable<HttpPostedFileBase> files)
{
return View();
}
Here's an example that lists all tags of all images on the registry. It handles a registry configured for HTTP Basic auth too.
THE_REGISTRY=localhost:5000
# Get username:password from docker configuration. You could
# inject these some other way instead if you wanted.
CREDS=$(jq -r ".[\"auths\"][\"$THE_REGISTRY\"][\"auth\"]" .docker/config.json | base64 -d)
curl -s --user $CREDS https://$THE_REGISTRY/v2/_catalog | \
jq -r '.["repositories"][]' | \
xargs -I @REPO@ curl -s --user $CREDS https://$THE_REGISTRY/v2/@REPO@/tags/list | \
jq -M '.["name"] + ":" + .["tags"][]'
Explanation:
here is one in c# that doesn't run out of memory when splitting into large chunks! I needed to split 95M file into 10M x line files.
var fileSuffix = 0;
int lines = 0;
Stream fstream = File.OpenWrite($"{filename}.{(++fileSuffix)}");
StreamWriter sw = new StreamWriter(fstream);
using (var file = File.OpenRead(filename))
using (var reader = new StreamReader(file))
{
while (!reader.EndOfStream)
{
sw.WriteLine(reader.ReadLine());
lines++;
if (lines >= 10000000)
{
sw.Close();
fstream.Close();
lines = 0;
fstream = File.OpenWrite($"{filename}.{(++fileSuffix)}");
sw = new StreamWriter(fstream);
}
}
}
sw.Close();
fstream.Close();
use
statusCode: {
404: function() {
alert('page not found');
}
}
-
$.ajax({
type: 'POST',
url: '/controller/action',
data: $form.serialize(),
success: function(data){
alert('horray! 200 status code!');
},
statusCode: {
404: function() {
alert('page not found');
},
400: function() {
alert('bad request');
}
}
});
The 'yes' command will echo 'y' (or whatever you ask it to) indefinitely. Use it as:
yes | command-that-asks-for-input
or, if a capital 'Y' is required:
yes Y | command-that-asks-for-input
I had the same problem with Xcode. I followed steps you gave and it didn't work. I became crazy because in every forum I saw, all clues for this problem are the one you gave. I finally saw I put a space after the malloc_error_break, I suppressed it and now it works. A dumb problem but if the solution doesn't work, be sure you haven't put any space before and after the malloc_error_break.
Hope this message will help..
Well, if you have a number like 0.123456
that is the result of a division to give a percentage, multiply it by 100 and then either round it or use toFixed
like in your example.
Math.round(0.123456 * 100) //12
Here is a jQuery plugin to do that:
jQuery.extend({
percentage: function(a, b) {
return Math.round((a / b) * 100);
}
});
Usage:
alert($.percentage(6, 10));
Note: I believe this to be a solid, portable, ready-made solution, which is invariably lengthy for that very reason.
Below is a fully POSIX-compliant script / function that is therefore cross-platform (works on macOS too, whose readlink
still doesn't support -f
as of 10.12 (Sierra)) - it uses only POSIX shell language features and only POSIX-compliant utility calls.
It is a portable implementation of GNU's readlink -e
(the stricter version of readlink -f
).
You can run the script with sh
or source the function in bash
, ksh
, and zsh
:
For instance, inside a script you can use it as follows to get the running's script true directory of origin, with symlinks resolved:
trueScriptDir=$(dirname -- "$(rreadlink "$0")")
rreadlink
script / function definition:
The code was adapted with gratitude from this answer.
I've also created a bash
-based stand-alone utility version here, which you can install with
npm install rreadlink -g
, if you have Node.js installed.
#!/bin/sh
# SYNOPSIS
# rreadlink <fileOrDirPath>
# DESCRIPTION
# Resolves <fileOrDirPath> to its ultimate target, if it is a symlink, and
# prints its canonical path. If it is not a symlink, its own canonical path
# is printed.
# A broken symlink causes an error that reports the non-existent target.
# LIMITATIONS
# - Won't work with filenames with embedded newlines or filenames containing
# the string ' -> '.
# COMPATIBILITY
# This is a fully POSIX-compliant implementation of what GNU readlink's
# -e option does.
# EXAMPLE
# In a shell script, use the following to get that script's true directory of origin:
# trueScriptDir=$(dirname -- "$(rreadlink "$0")")
rreadlink() ( # Execute the function in a *subshell* to localize variables and the effect of `cd`.
target=$1 fname= targetDir= CDPATH=
# Try to make the execution environment as predictable as possible:
# All commands below are invoked via `command`, so we must make sure that
# `command` itself is not redefined as an alias or shell function.
# (Note that command is too inconsistent across shells, so we don't use it.)
# `command` is a *builtin* in bash, dash, ksh, zsh, and some platforms do not
# even have an external utility version of it (e.g, Ubuntu).
# `command` bypasses aliases and shell functions and also finds builtins
# in bash, dash, and ksh. In zsh, option POSIX_BUILTINS must be turned on for
# that to happen.
{ \unalias command; \unset -f command; } >/dev/null 2>&1
[ -n "$ZSH_VERSION" ] && options[POSIX_BUILTINS]=on # make zsh find *builtins* with `command` too.
while :; do # Resolve potential symlinks until the ultimate target is found.
[ -L "$target" ] || [ -e "$target" ] || { command printf '%s\n' "ERROR: '$target' does not exist." >&2; return 1; }
command cd "$(command dirname -- "$target")" # Change to target dir; necessary for correct resolution of target path.
fname=$(command basename -- "$target") # Extract filename.
[ "$fname" = '/' ] && fname='' # !! curiously, `basename /` returns '/'
if [ -L "$fname" ]; then
# Extract [next] target path, which may be defined
# *relative* to the symlink's own directory.
# Note: We parse `ls -l` output to find the symlink target
# which is the only POSIX-compliant, albeit somewhat fragile, way.
target=$(command ls -l "$fname")
target=${target#* -> }
continue # Resolve [next] symlink target.
fi
break # Ultimate target reached.
done
targetDir=$(command pwd -P) # Get canonical dir. path
# Output the ultimate target's canonical path.
# Note that we manually resolve paths ending in /. and /.. to make sure we have a normalized path.
if [ "$fname" = '.' ]; then
command printf '%s\n' "${targetDir%/}"
elif [ "$fname" = '..' ]; then
# Caveat: something like /var/.. will resolve to /private (assuming /var@ -> /private/var), i.e. the '..' is applied
# AFTER canonicalization.
command printf '%s\n' "$(command dirname -- "${targetDir}")"
else
command printf '%s\n' "${targetDir%/}/$fname"
fi
)
rreadlink "$@"
A tangent on security:
jarno, in reference to the function ensuring that builtin command
is not shadowed by an alias or shell function of the same name, asks in a comment:
What if
unalias
orunset
and[
are set as aliases or shell functions?
The motivation behind rreadlink
ensuring that command
has its original meaning is to use it to bypass (benign) convenience aliases and functions often used to shadow standard commands in interactive shells, such as redefining ls
to include favorite options.
I think it's safe to say that unless you're dealing with an untrusted, malicious environment, worrying about unalias
or unset
- or, for that matter, while
, do
, ... - being redefined is not a concern.
There is something that the function must rely on to have its original meaning and behavior - there is no way around that.
That POSIX-like shells allow redefinition of builtins and even language keywords is inherently a security risk (and writing paranoid code is hard in general).
To address your concerns specifically:
The function relies on unalias
and unset
having their original meaning. Having them redefined as shell functions in a manner that alters their behavior would be a problem; redefinition as an alias is
not necessarily a concern, because quoting (part of) the command name (e.g., \unalias
) bypasses aliases.
However, quoting is not an option for shell keywords (while
, for
, if
, do
, ...) and while shell keywords do take precedence over shell functions, in bash
and zsh
aliases have the highest precedence, so to guard against shell-keyword redefinitions you must run unalias
with their names (although in non-interactive bash
shells (such as scripts) aliases are not expanded by default - only if shopt -s expand_aliases
is explicitly called first).
To ensure that unalias
- as a builtin - has its original meaning, you must use \unset
on it first, which requires that unset
have its original meaning:
unset
is a shell builtin, so to ensure that it is invoked as such, you'd have to make sure that it itself is not redefined as a function. While you can bypass an alias form with quoting, you cannot bypass a shell-function form - catch 22.
Thus, unless you can rely on unset
to have its original meaning, from what I can tell, there is no guaranteed way to defend against all malicious redefinitions.
df.index.rename('new name', inplace=True)
Is the only one that does the job for me (pandas 0.22.0).
Without the inplace=True, the name of the index is not set in my case.
it doesn't matter that you declare your minSdk in build.gradle. You have to copy overrideLibrary
in your AndroidManifest.xml
, as documented here.
<manifest
... >
<uses-sdk tools:overrideLibrary="com.example.lib1, com.example.lib2"/>
...
</manifest>
The system automatically ignores the sdkVersion declared in AndroidManifest.xml.
I hope this solve your problem.
char *line = strdup("user name"); // don't do char *line = "user name"; see Note
char *first_part = strtok(line, " "); //first_part points to "user"
char *sec_part = strtok(NULL, " "); //sec_part points to "name"
Note: strtok
modifies the string, so don't hand it a pointer to string literal.
You might use Form
tag with action attribute to submit the mailto
.
Here is an example:
<form method="post" action="mailto:[email protected]" >
<input type="submit" value="Send Email" />
</form>
I found this nice and easy-to-follow guide on how to download the GIT source and compile it yourself (and install it). If the accepted answer does not give you the version you want, try the following instructions:
http://tecadmin.net/install-git-2-0-on-centos-rhel-fedora/
(And pasted/reformatted from above source in case it is removed later)
Step 1: Install Required Packages
Firstly we need to make sure that we have installed required packages on your system. Use following command to install required packages before compiling Git source.
# yum install curl-devel expat-devel gettext-devel openssl-devel zlib-devel
# yum install gcc perl-ExtUtils-MakeMaker
Step 2: Uninstall old Git RPM
Now remove any prior installation of Git through RPM file or Yum package manager. If your older version is also compiled through source, then skip this step.
# yum remove git
Step 3: Download and Compile Git Source
Download git source code from kernel git or simply use following command to download Git 2.5.3.
# cd /usr/src
# wget https://www.kernel.org/pub/software/scm/git/git-2.5.3.tar.gz
# tar xzf git-2.5.3.tar.gz
After downloading and extracting Git source code, Use following command to compile source code.
# cd git-2.5.3
# make prefix=/usr/local/git all
# make prefix=/usr/local/git install
# echo 'pathmunge /usr/local/git/bin/' > /etc/profile.d/git.sh
# chmod +x /etc/profile.d/git.sh
# source /etc/bashrc
Step 4. Check Git Version
On completion of above steps, you have successfully install Git in your system. Use the following command to check the git version
# git --version
git version 2.5.3
I also wanted to add that the "Getting Started" guide at the GIT website also includes instructions on how to download and compile it yourself:
http://git-scm.com/book/en/v2/Getting-Started-Installing-Git
I have been reading about using model concerns to skin-nize fat models as well as DRY up your model codes. Here is an explanation with examples:
Consider a Article model, a Event model and a Comment model. An article or an event has many comments. A comment belongs to either Article or Event.
Traditionally, the models may look like this:
Comment Model:
class Comment < ActiveRecord::Base
belongs_to :commentable, polymorphic: true
end
Article Model:
class Article < ActiveRecord::Base
has_many :comments, as: :commentable
def find_first_comment
comments.first(created_at DESC)
end
def self.least_commented
#return the article with least number of comments
end
end
Event Model
class Event < ActiveRecord::Base
has_many :comments, as: :commentable
def find_first_comment
comments.first(created_at DESC)
end
def self.least_commented
#returns the event with least number of comments
end
end
As we can notice, there is a significant piece of code common to both Event and Article. Using concerns we can extract this common code in a separate module Commentable.
For this create a commentable.rb file in app/models/concerns.
module Commentable
extend ActiveSupport::Concern
included do
has_many :comments, as: :commentable
end
# for the given article/event returns the first comment
def find_first_comment
comments.first(created_at DESC)
end
module ClassMethods
def least_commented
#returns the article/event which has the least number of comments
end
end
end
And now your models look like this :
Comment Model:
class Comment < ActiveRecord::Base
belongs_to :commentable, polymorphic: true
end
Article Model:
class Article < ActiveRecord::Base
include Commentable
end
Event Model:
class Event < ActiveRecord::Base
include Commentable
end
Consider a Event model. A event has many attenders and comments.
Typically, the event model might look like this
class Event < ActiveRecord::Base
has_many :comments
has_many :attenders
def find_first_comment
# for the given article/event returns the first comment
end
def find_comments_with_word(word)
# for the given event returns an array of comments which contain the given word
end
def self.least_commented
# finds the event which has the least number of comments
end
def self.most_attended
# returns the event with most number of attendes
end
def has_attendee(attendee_id)
# returns true if the event has the mentioned attendee
end
end
Models with many associations and otherwise have tendency to accumulate more and more code and become unmanageable. Concerns provide a way to skin-nize fat modules making them more modularized and easy to understand.
The above model can be refactored using concerns as below:
Create a attendable.rb
and commentable.rb
file in app/models/concerns/event folder
attendable.rb
module Attendable
extend ActiveSupport::Concern
included do
has_many :attenders
end
def has_attender(attender_id)
# returns true if the event has the mentioned attendee
end
module ClassMethods
def most_attended
# returns the event with most number of attendes
end
end
end
commentable.rb
module Commentable
extend ActiveSupport::Concern
included do
has_many :comments
end
def find_first_comment
# for the given article/event returns the first comment
end
def find_comments_with_word(word)
# for the given event returns an array of comments which contain the given word
end
module ClassMethods
def least_commented
# finds the event which has the least number of comments
end
end
end
And now using Concerns, your Event model reduces to
class Event < ActiveRecord::Base
include Commentable
include Attendable
end
* While using concerns its advisable to go for 'domain' based grouping rather than 'technical' grouping. Domain Based grouping is like 'Commentable', 'Photoable', 'Attendable'. Technical grouping will mean 'ValidationMethods', 'FinderMethods' etc
In my case, all console messages were not showing because I had left a string in the "filter" textbox.
Remove the filter it by clicking the X as shown:
Thanks, Varun Rathore
. It works perfectly!
For those who want graceful collapse from 4 items per row to 2 items per row depending on the screen width:
<ul class="list-group row">
<li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_1</li>
<li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_2</li>
<li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_3</li>
<li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_4</li>
<li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_5</li>
<li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_6</li>
<li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_7</li>
</ul>
fs.Promises
readdir
const { promises: fs } = require("fs");
async function myF() {
let names;
try {
names = await fs.readdir("path/to/dir");
} catch (e) {
console.log("e", e);
}
if (names === undefined) {
console.log("undefined");
} else {
console.log("First Name", names[0]);
}
}
myF();
readFile
const { promises: fs } = require("fs");
async function getContent(filePath, encoding = "utf-8") {
if (!filePath) {
throw new Error("filePath required");
}
return fs.readFile(filePath, { encoding });
}
(async () => {
const content = await getContent("./package.json");
console.log(content);
})();
I think only push operation suffers, is enough. My implementation includes a stack of nodes. Each node contain the data item and also the minimum on that moment. This minimum is updated each time a push operation is done.
Here are some points for understanding:
I implemented the stack using Linked List.
A pointer top always points to the last pushed item. When there is no item in that stack top is NULL.
When an item is pushed a new node is allocated which has a next pointer that points to the previous stack and top is updated to point to this new node.
Only difference with normal stack implementation is that during push it updates a member min for the new node.
Please have a look at code which is implemented in C++ for demonstration purpose.
/*
* Implementation of Stack that can give minimum in O(1) time all the time
* This solution uses same data structure for minimum variable, it could be implemented using pointers but that will be more space consuming
*/
#include <iostream>
using namespace std;
typedef struct stackLLNodeType stackLLNode;
struct stackLLNodeType {
int item;
int min;
stackLLNode *next;
};
class DynamicStack {
private:
int stackSize;
stackLLNode *top;
public:
DynamicStack();
~DynamicStack();
void push(int x);
int pop();
int getMin();
int size() { return stackSize; }
};
void pushOperation(DynamicStack& p_stackObj, int item);
void popOperation(DynamicStack& p_stackObj);
int main () {
DynamicStack stackObj;
pushOperation(stackObj, 3);
pushOperation(stackObj, 1);
pushOperation(stackObj, 2);
popOperation(stackObj);
popOperation(stackObj);
popOperation(stackObj);
popOperation(stackObj);
pushOperation(stackObj, 4);
pushOperation(stackObj, 7);
pushOperation(stackObj, 6);
popOperation(stackObj);
popOperation(stackObj);
popOperation(stackObj);
popOperation(stackObj);
return 0;
}
DynamicStack::DynamicStack() {
// initialization
stackSize = 0;
top = NULL;
}
DynamicStack::~DynamicStack() {
stackLLNode* tmp;
// chain memory deallocation to avoid memory leak
while (top) {
tmp = top;
top = top->next;
delete tmp;
}
}
void DynamicStack::push(int x) {
// allocate memory for new node assign to top
if (top==NULL) {
top = new stackLLNode;
top->item = x;
top->next = NULL;
top->min = top->item;
}
else {
// allocation of memory
stackLLNode *tmp = new stackLLNode;
// assign the new item
tmp->item = x;
tmp->next = top;
// store the minimum so that it does not get lost after pop operation of later minimum
if (x < top->min)
tmp->min = x;
else
tmp->min = top->min;
// update top to new node
top = tmp;
}
stackSize++;
}
int DynamicStack::pop() {
// check if stack is empty
if (top == NULL)
return -1;
stackLLNode* tmp = top;
int curItem = top->item;
top = top->next;
delete tmp;
stackSize--;
return curItem;
}
int DynamicStack::getMin() {
if (top == NULL)
return -1;
return top->min;
}
void pushOperation(DynamicStack& p_stackObj, int item) {
cout<<"Just pushed: "<<item<<endl;
p_stackObj.push(item);
cout<<"Current stack min: "<<p_stackObj.getMin()<<endl;
cout<<"Current stack size: "<<p_stackObj.size()<<endl<<endl;
}
void popOperation(DynamicStack& p_stackObj) {
int popItem = -1;
if ((popItem = p_stackObj.pop()) == -1 )
cout<<"Cannot pop. Stack is empty."<<endl;
else {
cout<<"Just popped: "<<popItem<<endl;
if (p_stackObj.getMin() == -1)
cout<<"No minimum. Stack is empty."<<endl;
else
cout<<"Current stack min: "<<p_stackObj.getMin()<<endl;
cout<<"Current stack size: "<<p_stackObj.size()<<endl<<endl;
}
}
And the output of the program looks like this:
Just pushed: 3
Current stack min: 3
Current stack size: 1
Just pushed: 1
Current stack min: 1
Current stack size: 2
Just pushed: 2
Current stack min: 1
Current stack size: 3
Just popped: 2
Current stack min: 1
Current stack size: 2
Just popped: 1
Current stack min: 3
Current stack size: 1
Just popped: 3
No minimum. Stack is empty.
Current stack size: 0
Cannot pop. Stack is empty.
Just pushed: 4
Current stack min: 4
Current stack size: 1
Just pushed: 7
Current stack min: 4
Current stack size: 2
Just pushed: 6
Current stack min: 4
Current stack size: 3
Just popped: 6
Current stack min: 4
Current stack size: 2
Just popped: 7
Current stack min: 4
Current stack size: 1
Just popped: 4
No minimum. Stack is empty.
Current stack size: 0
Cannot pop. Stack is empty.
You have to escape each \
to be \\
:
var ttt = "aa ///\\\\\\";
Updated: I think this question is not about the escape character in string at all. The asker doesn't seem to explain the problem correctly.
because you had to show a message to user that user can't give a name which has (\) character.
I think the scenario is like:
var user_input_name = document.getElementById('the_name').value;
Then the asker wants to check if user_input_name
contains any [\
]. If so, then alert the user.
If user enters [aa ///\
] in HTML input box, then if you alert(user_input_name)
, you will see [aaa ///\
]. You don't need to escape, i.e. replace [\
] to be [\\
] in JavaScript code. When you do escaping, that is because you are trying to make of a string which contain special characters in JavaScript source code. If you don't do it, it won't be parsed correct. Since you already get a string, you don't need to pass it into an escaping function. If you do so, I am guessing you are generating another JavaScript code from a JavaScript code, but it's not the case here.
I am guessing asker wants to simulate the input, so we can understand the problem. Unfortunately, asker doesn't understand JavaScript well. Therefore, a syntax error code being supplied to us:
var ttt = "aa ///\";
Hence, we assume the asker having problem with escaping.
If you want to simulate, you code must be valid at first place.
var ttt = "aa ///\\"; // <- This is correct
// var ttt = "aa ///\"; // <- This is not.
alert(ttt); // You will see [aa ///\] in dialog, which is what you expect, right?
Now, you only need to do is
var user_input_name = document.getElementById('the_name').value;
if (user_input_name.indexOf("\\") >= 0) { // There is a [\] in the string
alert("\\ is not allowed to be used!"); // User reads [\ is not allowed to be used]
do_something_else();
}
Edit: I used []
to quote text to be shown, so it would be less confused than using ""
.
echo -e "hello\c" ;sleep 1 ; echo -e "\rbye "
What the above command will do :
It will print hello and the cursor will remain at "o" (using \c)
Then it will wait for 1 sec (sleep 1)
Then it will replace hello with bye.(using \r)
NOTE : Using ";", We can run multiple command in a single go.
I think this is similar to what the last podcast discussed. The "Be liberal in what you accept" means that extra work had to be put into the Javascript parser to fix cases where semicolons were left out. Now we have a boatload of pages out there floating around with bad syntax, that might break one day in the future when some browser decides to be a little more stringent on what it accepts. This type of rule should also apply to HTML and CSS. You can write broken HTML and CSS, but don't be surprise when you get weird and hard to debug behaviors when some browser doesn't properly interpret your incorrect code.
With Java 9
, we can use ProcessHandle which makes it easier to identify and control native processes:
ProcessHandle
.allProcesses()
.filter(p -> p.info().commandLine().map(c -> c.contains("firefox")).orElse(false))
.findFirst()
.ifPresent(ProcessHandle::destroy)
where "firefox" is the process to kill.
This:
First lists all processes running on the system as a Stream<ProcessHandle>
Lazily filters this stream to only keep processes whose launched command line contains "firefox". Both commandLine
or command
can be used depending on how we want to retrieve the process.
Finds the first filtered process meeting the filtering condition.
And if at least one process' command line contained "firefox", then kills it using destroy
.
No import necessary as ProcessHandle
is part of java.lang
.
I solved the problem in this way:
and no more error.
If you have a ConstraintLayout
with some size, and a child View
with some smaller size, you can achieve centering by constraining the child's two edges to the same two edges of the parent. That is, you can write:
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
or
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
Because the view is smaller, these constraints are impossible. But ConstraintLayout
will do the best it can, and each constraint will "pull" at the child view equally, thereby centering it.
This concept works with any target view, not just the parent.
Below is XML that achieves your desired UI with no nesting of views and no Guideline
s (though guidelines are not inherently evil).
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#eee">
<TextView
android:id="@+id/title1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:gravity="center"
android:textColor="#777"
android:textSize="22sp"
android:text="10"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toLeftOf="@+id/divider1"
app:layout_constraintBottom_toBottomOf="parent"/>
<TextView
android:id="@+id/label1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="#777"
android:textSize="12sp"
android:text="Streak"
app:layout_constraintTop_toBottomOf="@+id/title1"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toLeftOf="@+id/divider1"/>
<View
android:id="@+id/divider1"
android:layout_width="1dp"
android:layout_height="55dp"
android:layout_marginTop="12dp"
android:layout_marginBottom="12dp"
android:background="#ccc"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toRightOf="@+id/title1"
app:layout_constraintRight_toLeftOf="@+id/title2"
app:layout_constraintBottom_toBottomOf="parent"/>
<TextView
android:id="@+id/title2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:gravity="center"
android:textColor="#777"
android:textSize="22sp"
android:text="243"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toRightOf="@+id/divider1"
app:layout_constraintRight_toLeftOf="@+id/divider2"
app:layout_constraintBottom_toBottomOf="parent"/>
<TextView
android:id="@+id/label2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="#777"
android:textSize="12sp"
android:text="Calories Burned"
app:layout_constraintTop_toBottomOf="@+id/title2"
app:layout_constraintLeft_toRightOf="@+id/divider1"
app:layout_constraintRight_toLeftOf="@+id/divider2"/>
<View
android:id="@+id/divider2"
android:layout_width="1dp"
android:layout_height="55dp"
android:layout_marginTop="12dp"
android:layout_marginBottom="12dp"
android:background="#ccc"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toRightOf="@+id/title2"
app:layout_constraintRight_toLeftOf="@+id/title3"
app:layout_constraintBottom_toBottomOf="parent"/>
<TextView
android:id="@+id/title3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:gravity="center"
android:textColor="#777"
android:textSize="22sp"
android:text="3200"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toRightOf="@+id/divider2"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"/>
<TextView
android:id="@+id/label3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="#777"
android:textSize="12sp"
android:text="Steps"
app:layout_constraintTop_toBottomOf="@+id/title3"
app:layout_constraintLeft_toRightOf="@+id/divider2"
app:layout_constraintRight_toRightOf="parent"/>
</android.support.constraint.ConstraintLayout>
Another advantage of using the '[[' operator is that it works both with data.frame and data.table. So if the function has to be made running for both data.frame and data.table, and you want to extract a column from it as a vector then
data[["column_name"]]
is best.
This works for me:
My pip
is not work after upgrade, so the first thing I need to do is to fix it with
sudo gedit /usr/bin/pip
Change the line
from pip import main
to
from pip._internal import main
Then,
sudo pip install -U numpy
In your code:
var obj = {
myProp: string;
};
You are actually creating a object literal and assigning the variable string to the property myProp. Although very bad practice this would actually be valid TS code (don't use this!):
var string = 'A string';
var obj = {
property: string
};
However, what you want is that the object literal is typed. This can be achieved in various ways:
Interface:
interface myObj {
property: string;
}
var obj: myObj = { property: "My string" };
Type alias:
type myObjType = {
property: string
};
var obj: myObjType = { property: "My string" };
Object type literal:
var obj: { property: string; } = { property: "Mystring" };
If you need access to the index as you iterate through the string, use enumerate()
:
>>> for i, c in enumerate('test'):
... print i, c
...
0 t
1 e
2 s
3 t
Since the question was labeled with Github
, adding another remote like https_origin
and add the https
connection can force you always to enter the password:
git remote add https_origin https://github.com/.../...
Your code has some conceptual issues:
First,
@Html.DropDownListFor(n => n.OrderTemplates, new SelectList(Model.OrderTemplates, "OrderTemplateId", "OrderTemplateName", 1), "Please select an order template")
When using DropDownListFor, the first parameter is the property where your selected value is stored once you submit the form. So, in your case, you should have a SelectedOrderId
as part of your model or something like that, in order to use it in this way:
@Html.DropDownListFor(n => n.SelectedOrderId, new SelectList(Model.OrderTemplates, "OrderTemplateId", "OrderTemplateName", 1), "Please select an order template")
Second,
Aside from using ViewBag, that is not wrong but there are better ways (put that information in the ViewModel instead), there is a "little bug" (or an unspected behavior) when your ViewBag property, where you are holding the SelectList, is the same name of the property where you put the selected value. To avoid this, just use another name when naming the property holding the list of items.
Some code I would use if I were you to avoid this issues and write better MVC code:
Viewmodel:
public class MyViewModel{
public int SelectedOrderId {get; set;}
public SelectList OrderTemplates {get; set;}
// Other properties you need in your view
}
Controller:
public ActionResult MyAction(){
var model = new MyViewModel();
model.OrderTemplates = new SelectList(db.OrderTemplates, "OrderTemplateId", "OrderTemplateName", 1);
//Other initialization code
return View(model);
}
In your View:
@Html.DropDownListFor(n => n.SelectedOrderId, Model.OrderTemplates, "Please select an order template")
Some Theory
$
is the name of a function like any other name you give to a function. Anyone can create a function in JavaScript and name it $
as shown below:
$ = function() {
alert('I am in the $ function');
}
JQuery is a very famous JavaScript library and they have decided to put their entire framework inside a function named jQuery
. To make it easier for people to use the framework and reduce typing the whole word jQuery
every single time they want to call the function, they have also created an alias for it. That alias is $
. Therefore $
is the name of a function. Within the jQuery source code, you can see this yourself:
window.jQuery = window.$ = jQuery;
Answer To Your Question
So what is $(function() { });?
Now that you know that $
is the name of the function, if you are using the jQuery library, then you are calling the function named $
and passing the argument function() {}
into it. The jQuery library will call the function at the appropriate time. When is the appropriate time? According to jQuery documentation, the appropriate time is once all the DOM elements of the page are ready to be used.
The other way to accomplish this is like this:
$(document).ready(function() { });
As you can see this is more verbose so people prefer $(function() { })
So the reason why some functions cannot be called, as you have noticed, is because those functions do not exist yet. In other words the DOM has not loaded yet. But if you put them inside the function you pass to $
as an argument, the DOM is loaded by then. And thus the function has been created and ready to be used.
Another way to interpret $(function() { })
is like this:
Hey $ or jQuery, can you please call this function I am passing as an argument once the DOM has loaded?
Check the connection string again.
Make sure the user you are connecting with still has permission to read from [__MigrationHistory]
and has permission to edit the schema.
You can also try changing the connection string in the App or Web config file to use Integrated Security (Windows Auth) to run the add-migration command as yourself.
For example:
connectionString="data source=server;initial catalog=db;persist security info=True;Integrated Security=SSPI;"
This connection string would go in the App.config file of the project where the DbContext is located.
You can specify the StartUp project on the command line or you can right click the project with the DbContext
, Configuration
and Migrations folder and select Set as StartUp project. I'm serious, this can actually help.
I had this exact error code and after checking my repository discovered that there were no go files but actually just more directories. So it was more of a red herring than an error for me.
I would recommend doing
go env
and making sure that everything is as it should be, check your environment variables in your OS and check to make sure your shell (bash or w/e ) isn't compromising it via something like a .bash_profile or .bashrc file. good luck.
Did you enable the profile for SQL Server Agent? This a common step that is missed when creating Email profiles in DatabaseMail.
Steps:
At the extreme ranges, an unsigned int can become larger than an int.
Therefore, the compiler generates a warning. If you are sure that this is not a problem, feel free to cast the types to the same type so the warning disappears (use C++ cast so that they are easy to spot).
Alternatively, make the variables the same type to stop the compiler from complaining.
I mean, is it possible to have a negative padding? If so then keep it as an int. Otherwise you should probably use unsigned int and let the stream catch the situations where the user types in a negative number.
That's the other way around. You should write:
$("table.planning_grid").on({
mouseenter: function() {
// Handle mouseenter...
},
mouseleave: function() {
// Handle mouseleave...
},
click: function() {
// Handle click...
}
}, "td");
The commands module is a reasonably high-level way to do this:
import commands
status, output = commands.getstatusoutput("cat /etc/services")
status is 0, output is the contents of /etc/services.
echo -e $lines | while read line
...
done
The while
loop is executed in a subshell. So any changes you do to the variable will not be available once the subshell exits.
Instead you can use a here string to re-write the while loop to be in the main shell process; only echo -e $lines
will run in a subshell:
while read line
do
if [[ "$line" == "second line" ]]
then
foo=2
echo "Variable \$foo updated to $foo inside if inside while loop"
fi
echo "Value of \$foo in while loop body: $foo"
done <<< "$(echo -e "$lines")"
You can get rid of the rather ugly echo
in the here-string above by expanding the backslash sequences immediately when assigning lines
. The $'...'
form of quoting can be used there:
lines=$'first line\nsecond line\nthird line'
while read line; do
...
done <<< "$lines"
This is not really 'slick' but it's faster to do integer operations than to do string concatenations for each padding 0
.
function ZeroPadNumber ( nValue )
{
if ( nValue < 10 )
{
return ( '000' + nValue.toString () );
}
else if ( nValue < 100 )
{
return ( '00' + nValue.toString () );
}
else if ( nValue < 1000 )
{
return ( '0' + nValue.toString () );
}
else
{
return ( nValue );
}
}
This function is also hardcoded to your particular need (4 digit padding), so it's not generic.
Quick and dirty version:
byte[] fileBytes = File.ReadAllBytes(inputFilename);
StringBuilder sb = new StringBuilder();
foreach(byte b in fileBytes)
{
sb.Append(Convert.ToString(b, 2).PadLeft(8, '0'));
}
File.WriteAllText(outputFilename, sb.ToString());
Note: if you limit that log to the last n commit (last 3 commits for instance, git log -3), make sure to put a space between 'n' and your branch:
git log -3 master..
Before Git 2.1 (August 2014), this mistake: git log -3master..
would actually show you the last 3 commits of the current branch (here my_experiment
), ignoring the master
limit (meaning if my_experiment
contains only one commit, 3 would still be listed, 2 of them from master
)
See commit e3fa568 by Junio C Hamano (gitster
):
git log -<count>
" more carefullyThis mistyped command line simply ignores "
master
" and ends up showing two commits from the currentHEAD
:
$ git log -2master
because we feed "
2master
" toatoi()
without making sure that the whole string is parsed as an integer.Use the
strtol_i()
helper function instead.
Elem e = enumerable.FirstOrDefault();
//do something with e
Using sortBy...
could help.
$users = User::all()->with('rated')->get()->sortByDesc('rated.rating');
mFragmentFavorite
in your code is a FragmentActivity
which is not the same thing as a Fragment
. That's why you're getting the type mismatch. Also, you should never call new
on an Activity
as that is not the proper way to start one.
If you want to start a new instance of mFragmentFavorite
, you can do so via an Intent
.
From a Fragment
:
Intent intent = new Intent(getActivity(), mFragmentFavorite.class);
startActivity(intent);
From an Activity
Intent intent = new Intent(this, mFragmentFavorite.class);
startActivity(intent);
If you want to start aFavorite
instead of mFragmentFavorite
then you only need to change out their names in the created Intent
.
Also, I recommend changing your class names to be more accurate. Calling something mFragmentFavorite
is improper in that it's not a Fragment
at all. Also, class declarations in Java typically start with a capital letter. You'd do well to name your class something like FavoriteActivity
to be more accurate and conform to the language conventions. You will also need to rename the file to FavoriteActivity.java if you choose to do this since Java requires class names match the file name.
UPDATE
Also, it looks like you actually meant formFragmentFavorite
to be a Fragment
instead of a FragmentActivity
based on your use of onCreateView
. If you want mFragmentFavorite
to be a Fragment
then change the following line of code:
public class mFragmentFavorite extends FragmentActivity{
Make this instead read:
public class mFragmentFavorite extends Fragment {
An exemple of the only solution that works for me in the simple usecase where I am on a fork and I want to checkout a new branch from a tag that is on the main project repository ( here upstream )
git fetch upstream --tags
Give me
From https://github.com/keycloak/keycloak
90b29b0e31..0ba9055d28 stage -> upstream/stage
* [new tag] 11.0.0 -> 11.0.0
Then I can create a new branch from this tag and checkout on it
git checkout -b tags/<name> <newbranch>
git checkout tags/11.0.0 -b v11.0.0
Follow these steps:
Add path to gitignore
file
Run this command
git rm -r --cached foldername
commit changes as usually.
I'm surprised there's been no mention of filter_var here for this being such an old question...
PHP has a built in method of doing this using sanitization filters. Specifically, the one to use in this situation is FILTER_SANITIZE_NUMBER_FLOAT
with the FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND
flags. Like so:
$numeric_filtered = filter_var("AR3,373.31", FILTER_SANITIZE_NUMBER_FLOAT,
FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND);
echo $numeric_filtered; // Will print "3,373.31"
It might also be worthwhile to note that because it's built-in to PHP, it's slightly faster than using regex with PHP's current libraries (albeit literally in nanoseconds).
transparent is the default for background-color
Try this simple program:
public class HashMapGetKey {
public static void main(String args[]) {
// create hash map
HashMap map = new HashMap();
// populate hash map
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
map.put(4, "four");
// get keyset value from map
Set keyset=map.keySet();
// check key set values
System.out.println("Key set values are: " + keyset);
}
}
I think the OP's problem was that he wants to do BOTH of the following:
As several posters have mentioned, to pass a parameter containing spaces, you must surround the actual parameter value with double quotes.
To test whether a parameter is missing, the method I always learned was:
if "%1" == ""
However, if the actual parameter is quoted (as it must be if the value contains spaces), this becomes
if ""actual parameter value"" == ""
which causes the "unexpected" error. If you instead use
if %1 == ""
then the error no longer occurs for quoted values. But in that case, the test no longer works when the value is missing -- it becomes
if == ""
To fix this, use any other characters (except ones with special meaning to DOS) instead of quotes in the test:
if [%1] == []
if .%1. == ..
if abc%1xyz == abcxyz
I was in the same situation and found this one,
You can add the src
folder to build path by:
src
folder.And you are done. Hope this help.
EDIT: Refer to the Eclipse documentation
If there is no Server context (i.e your running offline), you can use HttpUtility.HtmlDecode.
I would do
StartDate1.IsBetween(StartDate2, EndDate2) || EndDate1.IsBetween(StartDate2, EndDate2)
Where IsBetween
is something like
public static bool IsBetween(this DateTime value, DateTime left, DateTime right) {
return (value > left && value < right) || (value < left && value > right);
}
I've created a little Powershell function to emulate MSDOS pause
. This handles whether running Powershell ISE or non ISE. (ReadKey
does not work in powershell ISE). When running Powershell ISE, this function opens a Windows MessageBox
. This can sometimes be confusing, because the MessageBox
does not always come to the forefront. Anyway, here it goes:
Usage:
pause "Press any key to continue"
Function definition:
Function pause ($message)
{
# Check if running Powershell ISE
if ($psISE)
{
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.MessageBox]::Show("$message")
}
else
{
Write-Host "$message" -ForegroundColor Yellow
$x = $host.ui.RawUI.ReadKey("NoEcho,IncludeKeyDown")
}
}
disclaimer: this is not a just to the point answer, it's more like a piece of advice, even if the answer can be found on the references
IMHO: object oriented programming in Python sucks quite a lot.
The method dispatching is not very straightforward, you need to know about bound/unbound instance/class (and static!) methods; you can have multiple inheritance and need to deal with legacy and new style classes (yours was old style) and know how the MRO works, properties...
In brief: too complex, with lots of things happening under the hood. Let me even say, it is unpythonic, as there are many different ways to achieve the same things.
My advice: use OOP only when it's really useful. Usually this means writing classes that implement well known protocols and integrate seamlessly with the rest of the system. Do not create lots of classes just for the sake of writing object oriented code.
Take a good read to this pages:
you'll find them quite useful.
If you really want to learn OOP, I'd suggest starting with a more conventional language, like Java. It's not half as fun as Python, but it's more predictable.
Just to show how you can combine itertools
recipes, I'm extending the pairwise
recipe as directly as possible back into the window
recipe using the consume
recipe:
def consume(iterator, n):
"Advance the iterator n-steps ahead. If n is none, consume entirely."
# Use functions that consume iterators at C speed.
if n is None:
# feed the entire iterator into a zero-length deque
collections.deque(iterator, maxlen=0)
else:
# advance to the empty slice starting at position n
next(islice(iterator, n, n), None)
def window(iterable, n=2):
"s -> (s0, ...,s(n-1)), (s1, ...,sn), (s2, ..., s(n+1)), ..."
iters = tee(iterable, n)
# Could use enumerate(islice(iters, 1, None), 1) to avoid consume(it, 0), but that's
# slower for larger window sizes, while saving only small fixed "noop" cost
for i, it in enumerate(iters):
consume(it, i)
return zip(*iters)
The window
recipe is the same as for pairwise
, it just replaces the single element "consume" on the second tee
-ed iterator with progressively increasing consumes on n - 1
iterators. Using consume
instead of wrapping each iterator in islice
is marginally faster (for sufficiently large iterables) since you only pay the islice
wrapping overhead during the consume
phase, not during the process of extracting each window-ed value (so it's bounded by n
, not the number of items in iterable
).
Performance-wise, compared to some other solutions, this is pretty good (and better than any of the other solutions I tested as it scales). Tested on Python 3.5.0, Linux x86-64, using ipython
%timeit
magic.
kindall's the deque
solution, tweaked for performance/correctness by using islice
instead of a home-rolled generator expression and testing the resulting length so it doesn't yield results when the iterable is shorter than the window, as well as passing the maxlen
of the deque
positionally instead of by keyword (makes a surprising difference for smaller inputs):
>>> %timeit -r5 deque(windowkindall(range(10), 3), 0)
100000 loops, best of 5: 1.87 µs per loop
>>> %timeit -r5 deque(windowkindall(range(1000), 3), 0)
10000 loops, best of 5: 72.6 µs per loop
>>> %timeit -r5 deque(windowkindall(range(1000), 30), 0)
1000 loops, best of 5: 71.6 µs per loop
Same as previous adapted kindall solution, but with each yield win
changed to yield tuple(win)
so storing results from the generator works without all stored results really being a view of the most recent result (all other reasonable solutions are safe in this scenario), and adding tuple=tuple
to the function definition to move use of tuple
from the B
in LEGB
to the L
:
>>> %timeit -r5 deque(windowkindalltupled(range(10), 3), 0)
100000 loops, best of 5: 3.05 µs per loop
>>> %timeit -r5 deque(windowkindalltupled(range(1000), 3), 0)
10000 loops, best of 5: 207 µs per loop
>>> %timeit -r5 deque(windowkindalltupled(range(1000), 30), 0)
1000 loops, best of 5: 348 µs per loop
consume
-based solution shown above:
>>> %timeit -r5 deque(windowconsume(range(10), 3), 0)
100000 loops, best of 5: 3.92 µs per loop
>>> %timeit -r5 deque(windowconsume(range(1000), 3), 0)
10000 loops, best of 5: 42.8 µs per loop
>>> %timeit -r5 deque(windowconsume(range(1000), 30), 0)
1000 loops, best of 5: 232 µs per loop
Same as consume
, but inlining else
case of consume
to avoid function call and n is None
test to reduce runtime, particularly for small inputs where the setup overhead is a meaningful part of the work:
>>> %timeit -r5 deque(windowinlineconsume(range(10), 3), 0)
100000 loops, best of 5: 3.57 µs per loop
>>> %timeit -r5 deque(windowinlineconsume(range(1000), 3), 0)
10000 loops, best of 5: 40.9 µs per loop
>>> %timeit -r5 deque(windowinlineconsume(range(1000), 30), 0)
1000 loops, best of 5: 211 µs per loop
(Side-note: A variant on pairwise
that uses tee
with the default argument of 2 repeatedly to make nested tee
objects, so any given iterator is only advanced once, not independently consumed an increasing number of times, similar to MrDrFenner's answer is similar to non-inlined consume
and slower than the inlined consume
on all tests, so I've omitted it those results for brevity).
As you can see, if you don't care about the possibility of the caller needing to store results, my optimized version of kindall's solution wins most of the time, except in the "large iterable, small window size case" (where inlined consume
wins); it degrades quickly as the iterable size increases, while not degrading at all as the window size increases (every other solution degrades more slowly for iterable size increases, but also degrades for window size increases). It can even be adapted for the "need tuples" case by wrapping in map(tuple, ...)
, which runs ever so slightly slower than putting the tupling in the function, but it's trivial (takes 1-5% longer) and lets you keep the flexibility of running faster when you can tolerate repeatedly returning the same value.
If you need safety against returns being stored, inlined consume
wins on all but the smallest input sizes (with non-inlined consume
being slightly slower but scaling similarly). The deque
& tupling based solution wins only for the smallest inputs, due to smaller setup costs, and the gain is small; it degrades badly as the iterable gets longer.
For the record, the adapted version of kindall's solution that yield
s tuple
s I used was:
def windowkindalltupled(iterable, n=2, tuple=tuple):
it = iter(iterable)
win = deque(islice(it, n), n)
if len(win) < n:
return
append = win.append
yield tuple(win)
for e in it:
append(e)
yield tuple(win)
Drop the caching of tuple
in the function definition line and the use of tuple
in each yield
to get the faster but less safe version.
run cmd
Enter wmic baseboard get product,version,serialnumber
Press the enter key. The result you see under serial number column is your motherboard serial number
Way to unlock the user :
$ sqlplus /nolog
SQL > conn sys as sysdba
SQL > ALTER USER USER_NAME ACCOUNT UNLOCK;
and open new terminal
SQL > sqlplus / as sysdba
connected
SQL > conn username/password //which username u gave before unlock
password:password
password:password
Make sure you have the proper emulator and Android version installed. That solved the problem for me.
Following is the way to do it;
.control select {
border-radius: 0px;
appearance: none;
-webkit-appearance: none;
-moz-appearance: none;
background-image: url("<your image>");
background-repeat: no-repeat;
background-position: 100%;
background-size: 20px;
}
The easiest method is really good but you don't get a standard Java project, i.e., the .java and .class files separated in different folders.
To get this very easily:
<Enter>
and that's it.For iPhone 5,
@media screen and (device-aspect-ratio: 40/71)
for iPhone 6,7,8
@media only screen and (min-device-width: 375px) and (max-device-width: 667px) and (orientation : portrait)
for iPhone 6+,7+,8+
@media screen and (-webkit-device-pixel-ratio: 3) and (min-device-width: 414px)
Working fine for me as of now.
You can also try this:
for %%a in (*) do echo %%a
Using a for
loop, you can echo
out all the file names of the current directory.
To print them directly from the console:
for %a in (*) do @echo %a
E-mail addresses are very difficult to verify correctly with a mere regex. Here is a pretty scary regex that supposedly implements RFC822, chapter 6, the specification of valid e-mail addresses.
Not really an answer, but maybe related to what you're trying to accomplish.
Instead of creating a new route for that, you could just redirect to your controller/action and pass the information via querystring. For instance:
protected void Application_Error(object sender, EventArgs e) {
Exception exception = Server.GetLastError();
Response.Clear();
HttpException httpException = exception as HttpException;
if (httpException != null) {
string action;
switch (httpException.GetHttpCode()) {
case 404:
// page not found
action = "HttpError404";
break;
case 500:
// server error
action = "HttpError500";
break;
default:
action = "General";
break;
}
// clear error on server
Server.ClearError();
Response.Redirect(String.Format("~/Error/{0}/?message={1}", action, exception.Message));
}
Then your controller will receive whatever you want:
// GET: /Error/HttpError404
public ActionResult HttpError404(string message) {
return View("SomeView", message);
}
There are some tradeoffs with your approach. Be very very careful with looping in this kind of error handling. Other thing is that since you are going through the asp.net pipeline to handle a 404, you will create a session object for all those hits. This can be an issue (performance) for heavily used systems.
If you have access to the Java 8 Comparable API, Comparable.comparingToInt()
may be of use. (See Java 8 Comparable Documentation).
For example, a Comparator<Dog>
to sort Dog
instances descending by age could be created with the following:
Comparable.comparingToInt(Dog::getDogAge).reversed();
The function take a lambda mapping T
to Integer
, and creates an ascending comparator. The chained function .reversed()
turns the ascending comparator into a descending comparator.
Note: while this may not be useful for most versions of Android out there, I came across this question while searching for similar information for a non-Android Java application. I thought it might be useful to others in the same spot to see what I ended up settling on.
After a lot of digging around I finally ended up downloading the source code of the recovery section of Android. Turns out you can actually send commands to the recovery.
* The arguments which may be supplied in the recovery.command file:
* --send_intent=anystring - write the text out to recovery.intent
* --update_package=path - verify install an OTA package file
* --wipe_data - erase user data (and cache), then reboot
* --wipe_cache - wipe cache (but not user data), then reboot
* --set_encrypted_filesystem=on|off - enables / diasables encrypted fs
Those are the commands you can use according to the one I found but that might be different for modded files. So using adb you can do this:
adb shell
recovery --wipe_data
Using --wipe_data seemed to do what I was looking for which was handy although I have not fully tested this as of yet.
EDIT:
For anyone still using this topic, these commands may change based on which recovery you are using. If you are using Clockword recovery, these commands should still work. You can find other commands in /cache/recovery/command
For more information please see here: https://github.com/CyanogenMod/android_bootable_recovery/blob/cm-10.2/recovery.c
This will reset the time in the docker server:
docker run --rm --privileged alpine hwclock -s
Next time you create a container the clock should be correct.
Source: https://github.com/docker/for-mac/issues/2076#issuecomment-353749995
Yep. Cloudflare uses it for its DNS instructions homepage: https://1.1.1.1
Uri.EscapeDataString
or HttpUtility.UrlEncode
is the correct way to escape a string meant to be part of a URL.
Take for example the string "Stack Overflow"
:
HttpUtility.UrlEncode("Stack Overflow")
--> "Stack+Overflow"
Uri.EscapeUriString("Stack Overflow")
--> "Stack%20Overflow"
Uri.EscapeDataString("Stack + Overflow")
--> Also encodes "+" to "%2b"
---->Stack%20%2B%20%20Overflow
Only the last is correct when used as an actual part of the URL (as opposed to the value of one of the query string parameters)
I am surprised these have not been mentioned: but instead of using bare-bones rather manual process with json.org's little package, GSon and Jackson are much more convenient to use. So:
So you can actually bind to your own POJOs, not some half-assed tree nodes or Lists and Maps. (and at least Jackson allows binding to such things too (perhaps GSON as well, not sure), JsonNode, Map, List, if you really want these instead of 'real' objects)
EDIT 19-MAR-2014:
Another new contender is Jackson jr library: it uses same fast Streaming parser/generator as Jackson (jackson-core
), but data-binding part is tiny (50kB). Functionality is more limited (no annotations, just regular Java Beans), but performance-wise should be fast, and initialization (first-call) overhead very low as well.
So it just might be good choice, especially for smaller apps.
You could use inputType="phone"
, however in that case you would have to deal with multiple ,
or .
being present, so additional validation would be necessary.
Compare and contrast the differences between a sql/rdbms solution and nosql solution. You can't claim to be an expert in any technology without knowing its strengths and weaknesses as compared to its competitors.
Many answers using external programs, which is not really using Bash
.
If you know you will have Bash4 available you should really just use the ${VAR,,}
notation (it is easy and cool). For Bash before 4 (My Mac still uses Bash 3.2 for example). I used the corrected version of @ghostdog74 's answer to create a more portable version.
One you can call lowercase 'my STRING'
and get a lowercase version. I read comments about setting the result to a var, but that is not really portable in Bash
, since we can't return strings. Printing it is the best solution. Easy to capture with something like var="$(lowercase $str)"
.
How this works
The way this works is by getting the ASCII integer representation of each char with printf
and then adding 32
if upper-to->lower
, or subtracting 32
if lower-to->upper
. Then use printf
again to convert the number back to a char. From 'A' -to-> 'a'
we have a difference of 32 chars.
Using printf
to explain:
$ printf "%d\n" "'a"
97
$ printf "%d\n" "'A"
65
97 - 65 = 32
And this is the working version with examples.
Please note the comments in the code, as they explain a lot of stuff:
#!/bin/bash
# lowerupper.sh
# Prints the lowercase version of a char
lowercaseChar(){
case "$1" in
[A-Z])
n=$(printf "%d" "'$1")
n=$((n+32))
printf \\$(printf "%o" "$n")
;;
*)
printf "%s" "$1"
;;
esac
}
# Prints the lowercase version of a sequence of strings
lowercase() {
word="$@"
for((i=0;i<${#word};i++)); do
ch="${word:$i:1}"
lowercaseChar "$ch"
done
}
# Prints the uppercase version of a char
uppercaseChar(){
case "$1" in
[a-z])
n=$(printf "%d" "'$1")
n=$((n-32))
printf \\$(printf "%o" "$n")
;;
*)
printf "%s" "$1"
;;
esac
}
# Prints the uppercase version of a sequence of strings
uppercase() {
word="$@"
for((i=0;i<${#word};i++)); do
ch="${word:$i:1}"
uppercaseChar "$ch"
done
}
# The functions will not add a new line, so use echo or
# append it if you want a new line after printing
# Printing stuff directly
lowercase "I AM the Walrus!"$'\n'
uppercase "I AM the Walrus!"$'\n'
echo "----------"
# Printing a var
str="A StRing WITH mixed sTUFF!"
lowercase "$str"$'\n'
uppercase "$str"$'\n'
echo "----------"
# Not quoting the var should also work,
# since we use "$@" inside the functions
lowercase $str$'\n'
uppercase $str$'\n'
echo "----------"
# Assigning to a var
myLowerVar="$(lowercase $str)"
myUpperVar="$(uppercase $str)"
echo "myLowerVar: $myLowerVar"
echo "myUpperVar: $myUpperVar"
echo "----------"
# You can even do stuff like
if [[ 'option 2' = "$(lowercase 'OPTION 2')" ]]; then
echo "Fine! All the same!"
else
echo "Ops! Not the same!"
fi
exit 0
And the results after running this:
$ ./lowerupper.sh
i am the walrus!
I AM THE WALRUS!
----------
a string with mixed stuff!
A STRING WITH MIXED STUFF!
----------
a string with mixed stuff!
A STRING WITH MIXED STUFF!
----------
myLowerVar: a string with mixed stuff!
myUpperVar: A STRING WITH MIXED STUFF!
----------
Fine! All the same!
This should only work for ASCII characters though.
For me it is fine, since I know I will only pass ASCII chars to it.
I am using this for some case-insensitive CLI options, for example.
For Kotling here is what I used lately:
// src/main/com.blabla/ShellApplication.kt
/**
* Main entry point for the shell application.
*/
@SpringBootApplication
public class ShellApplication : CommandLineRunner {
companion object {
@JvmStatic
fun main(args: Array<String>) {
val application = SpringApplication(ShellApplication::class.java)
application.webApplicationType = WebApplicationType.NONE
application.run(*args);
}
}
override fun run(vararg args: String?) {}
}
// src/main/com.blabla/command/CustomCommand.kt
@ShellComponent
public class CustomCommand {
private val logger = KotlinLogging.logger {}
@ShellMethod("Import, create and update data from CSV")
public fun importCsv(@ShellOption() file: String) {
logger.info("Hi")
}
}
And everything boot normally ending up with a shell with my custom command available.
You have not defined a method around your code.
import java.io.*;
public class details
{
public static void main( String[] args )
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("What is your name?");
String name = in.readLine(); ;
System.out.println("Hello " + name);
}
}
In this case, I have assumed that you want your code to be executed in the main
method of the class. It is, of course, possible that this code goes in any other method.
To soluction it you should configure a xml binding before to compile with wsimport, setting generateElementProperty as false.
<jaxws:bindings wsdlLocation="LOCATION_OF_WSDL"
xmlns:jaxws="http://java.sun.com/xml/ns/jaxws"
xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:jxb="http://java.sun.com/xml/ns/jaxb"
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">
<jaxws:enableWrapperStyle>false</jaxws:enableWrapperStyle>
<jaxws:bindings node="wsdl:definitions/wsdl:types/xs:schema[@targetNamespace='NAMESPACE_OF_WSDL']">
<jxb:globalBindings xmlns:jxb="http://java.sun.com/xml/ns/jaxb" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xjc:generateElementProperty>false</xjc:generateElementProperty>
</jxb:globalBindings>
</jaxws:bindings>
</jaxws:bindings>
First, I try without a space, rtrim($arraynama, ",");
and get an error result.
Then I add a space and get a good result:
$newarraynama = rtrim($arraynama, ", ");
Although this post seems to be old, I'd like to add the following two to inform about the recent development in this area for Android:
android-binding - Providing a framework that enabes the binding of android view widgets to data model. It helps to implement MVC or MVVM patterns in android applications.
roboguice - RoboGuice takes the guesswork out of development. Inject your View, Resource, System Service, or any other object, and let RoboGuice take care of the details.
You have to add the reference of the namespace : System.Windows.Forms to your project, because for some reason it is not already added, so you can add New Reference from Visual Studio menu.
Right click on "Reference" ? "Add New Reference" ? "System.Windows.Forms"
Implemented this way without using Jquery:
<button class="emailReplyButton" onClick="sendEmail(message)">Reply</button>
sendEmail(message) {
var email = message.emailId;
var subject = message.subject;
var emailBody = 'Hi '+message.from;
document.location = "mailto:"+email+"?subject="+subject+"&body="+emailBody;
}
I refactored the solution that Narek had to create (according to me) a slightly more efficient and easy to understand code. I used embedded Automatic Resource Management, a recent feature in Java and used a Scanner class which according to me is more easier to understand and use.
Here is the code with edited Comments:
public class RemoveLineInFile {
private static File file;
public static void main(String[] args) {
//create a new File
file = new File("hello.txt");
//takes in String that you want to get rid off
removeLineFromFile("Hello");
}
public static void removeLineFromFile(String lineToRemove) {
//if file does not exist, a file is created
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
System.out.println("File "+file.getName()+" not created successfully");
}
}
// Construct the new temporary file that will later be renamed to the original
// filename.
File tempFile = new File(file.getAbsolutePath() + ".tmp");
//Two Embedded Automatic Resource Managers used
// to effectivey handle IO Responses
try(Scanner scanner = new Scanner(file)) {
try (PrintWriter pw = new PrintWriter(new FileWriter(tempFile))) {
//a declaration of a String Line Which Will Be assigned Later
String line;
// Read from the original file and write to the new
// unless content matches data to be removed.
while (scanner.hasNextLine()) {
line = scanner.nextLine();
if (!line.trim().equals(lineToRemove)) {
pw.println(line);
pw.flush();
}
}
// Delete the original file
if (!file.delete()) {
System.out.println("Could not delete file");
return;
}
// Rename the new file to the filename the original file had.
if (!tempFile.renameTo(file))
System.out.println("Could not rename file");
}
}
catch (IOException e)
{
System.out.println("IO Exception Occurred");
}
}
}
Just want to add this for the future programmer.
This code limits the date min and max. The year is fully controlled by getting the current year as max year.
Hope this could help to anyone.
Here's the code.
var dateToday = new Date();
var yrRange = '2014' + ":" + (dateToday.getFullYear());
$(function () {
$("[id$=txtDate]").datepicker({
showOn: 'button',
changeMonth: true,
changeYear: true,
showButtonPanel: true,
buttonImageOnly: true,
yearRange: yrRange,
buttonImage: 'calendar3.png',
buttonImageOnly: true,
minDate: new Date(2014,1-1,1),
maxDate: '+50Y',
inline:true
});
});
If you're doing the check inside the View, put the value in the ViewBag
.
In your controller:
ViewBag["parameterName"] = Request["parameterName"];
It's worth noting that the Request
and Response
properties are exposed by the Controller
class. They have the same semantics as HttpRequest
and HttpResponse
.
This code will work perfectly in WPF. You can use it in either page load or in button click.
string screenWidth =System.Windows.SystemParameters.PrimaryScreenWidth.ToString();
string screenHeight = System.Windows.SystemParameters.PrimaryScreenHeight.ToString();
txtResolution.Text ="Resolution : "+screenWidth + " X " + screenHeight;
sed -i 's/[^[:print:]]//' FILENAME
Also, this acts like dos2unix
hmmmm i think there is much efficient way to make it specially for people want to target all browser and not only FormData supported browser
the idea to have hidden IFRAME on page and making normal submit for the From inside IFrame example
<FORM action='save_upload.php' method=post
enctype='multipart/form-data' target=hidden_upload>
<DIV><input
type=file name='upload_scn' class=file_upload></DIV>
<INPUT
type=submit name=submit value=Upload /> <IFRAME id=hidden_upload
name=hidden_upload src='' onLoad='uploadDone("hidden_upload")'
style='width:0;height:0;border:0px solid #fff'></IFRAME>
</FORM>
most important to make a target of form the hidden iframe ID or name and enctype multipart/form-data to allow accepting photos
javascript side
function getFrameByName(name) {
for (var i = 0; i < frames.length; i++)
if (frames[i].name == name)
return frames[i];
return null;
}
function uploadDone(name) {
var frame = getFrameByName(name);
if (frame) {
ret = frame.document.getElementsByTagName("body")[0].innerHTML;
if (ret.length) {
var json = JSON.parse(ret);
// do what ever you want
}
}
}
server Side Example PHP
<?php
$target_filepath = "/tmp/" . basename($_FILES['upload_scn']['name']);
if (move_uploaded_file($_FILES['upload_scn']['tmp_name'], $target_filepath)) {
$result = ....
}
echo json_encode($result);
?>
<html>_x000D_
<style>_x000D_
#myProgress {_x000D_
width: 100%;_x000D_
background-color: #ddd;_x000D_
}_x000D_
_x000D_
#myBar {_x000D_
width: 10%;_x000D_
height: 15px;_x000D_
background-color: #4CAF50;_x000D_
text-align: center;_x000D_
line-height: 15px;_x000D_
color: white;_x000D_
}_x000D_
</style>_x000D_
<body onload="move()">_x000D_
_x000D_
<div id="myProgress">_x000D_
<div id="myBar">10%</div>_x000D_
</div>_x000D_
_x000D_
<script>_x000D_
var i = 0;_x000D_
function move() {_x000D_
if (i == 0) {_x000D_
i = 1;_x000D_
var elem = document.getElementById("myBar");_x000D_
var width = 10;_x000D_
var id = setInterval(frame, 10);_x000D_
function frame() {_x000D_
if (width >= 100) {_x000D_
clearInterval(id);_x000D_
i = 0;_x000D_
} else {_x000D_
width++;_x000D_
elem.style.width = width + "%";_x000D_
elem.innerHTML = width + "%";_x000D_
}_x000D_
}_x000D_
}_x000D_
}_x000D_
</script>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
first ensure that your table storage engine type should be innoDB (you can set it using Table operations Tab)
if you are using new phpmyadmin then use new "Relation view" tab to make foreign key relation
if you are using old version of phpmyadmin then the "relation view" button will show on the bottom of the table columns
If the question is docker related... the official nginx docker images do this by making softlinks towards stdout/stderr
RUN ln -sf /dev/stdout /var/log/nginx/access.log && ln -sf /dev/stderr /var/log/nginx/error.log
def concatFiles():
path = 'input/'
files = os.listdir(path)
for idx, infile in enumerate(files):
print ("File #" + str(idx) + " " + infile)
concat = ''.join([open(path + f).read() for f in files])
with open("output_concatFile.txt", "w") as fo:
fo.write(path + concat)
if __name__ == "__main__":
concatFiles()
So, I was having the same issue, but trying to import Android code via the "Import..." menu. When neither of the above two solutions worked on Eclipse Juno:
Eclipse -> File -> Import -> General -> Existing Project Into Workspace (NOTE: NOT 'EXISTING ANDROID PROJECT')
(Projects should import correctly, but should have errors. We must now attach the SDK to the project)
Right-Click on the project, Properties->Android->Project Build Target Choose the appropriate build target (in doubt, use 4.0.3 in the project is newish, and use 2.2 if the project is oldish)
Click OK
Once the project rebuilds, everything should be back in order.
(This was written when Eclipse Indigo was in vogue, and there may be changes as Google updates their tools to cover corner cases.)
I found the prior answers and comments to be needlessly incomplete and/or confusing. The minimum that I needed to do was:
~/.config/fish/config.fish
. This file can optionally be a softlink.alias myalias echo foo bar
.fish
. To confirm the definition, try type myalias
. Try the alias.If any doubt in this code, please ask your questions(Here for gmail Port number is 587)
// code to Send Mail
// Add following Lines in your web.config file
// <system.net>
// <mailSettings>
// <smtp>
// <network host="smtp.gmail.com" port="587" userName="[email protected]" password="yyy" defaultCredentials="false"/>
// </smtp>
// </mailSettings>
// </system.net>
// Add below lines in your config file inside appsetting tag <appsetting></appsetting>
// <add key="emailFromAddress" value="[email protected]"/>
// <add key="emailToAddress" value="[email protected]"/>
// <add key="EmailSsl" value="true"/>
// Namespace Used
using System.Net.Mail;
public static bool SendingMail(string subject, string content)
{
// getting the values from config file through c#
string fromEmail = ConfigurationSettings.AppSettings["emailFromAddress"];
string mailid = ConfigurationSettings.AppSettings["emailToAddress"];
bool useSSL;
if (ConfigurationSettings.AppSettings["EmailSsl"] == "true")
{
useSSL = true;
}
else
{
useSSL = false;
}
SmtpClient emailClient;
MailMessage message;
message = new MailMessage();
message.From = new MailAddress(fromEmail);
message.ReplyTo = new MailAddress(fromEmail);
if (SetMailAddressCollection(message.To, mailid))
{
message.Subject = subject;
message.Body = content;
message.IsBodyHtml = true;
emailClient = new SmtpClient();
emailClient.EnableSsl = useSSL;
emailClient.Send(message);
}
return true;
}
// if you are sending mail in group
private static bool SetMailAddressCollection(MailAddressCollection toAddresses, string mailId)
{
bool successfulAddressCreation = true;
toAddresses.Add(new MailAddress(mailId));
return successfulAddressCreation;
}
Angular introduced $watchGroup
in version 1.3 using which we can watch multiple variables, with a single $watchGroup
block
$watchGroup
takes array as first parameter in which we can include all of our variables to watch.
$scope.$watchGroup(['var1','var2'],function(newVals,oldVals){
console.log("new value of var1 = " newVals[0]);
console.log("new value of var2 = " newVals[1]);
console.log("old value of var1 = " oldVals[0]);
console.log("old value of var2 = " oldVals[1]);
});
Easy and simple:
public static bool DirIsEmpty(string path) {
int num = Directory.GetFiles(path).Length + Directory.GetDirectories(path).Length;
return num == 0;
}
In Swift3, To set the Back button to red
.
self.navigationController?.navigationBar.tintColor = UIColor.red
Recently, I have seen this problem too. Below, you have my solution:
Or it can be a genuine network issue. Restart your network-manager using sudo service network-manager restart
or fix it up
I have just received this error after switching from HTTPS to SSH (for my origin remote). To fix, I simply ran the following command (for each repo):
ssh -T [email protected]
Upon receiving a successful response, I could fetch/push to the repo with ssh.
I took that command from Git's Testing your SSH connection guide, which is part of the greater Connecting to GitHub with with SSH guide.
use two line of code to convert array to list if you use it in integer value you must use autoboxing type for primitive data type
Integer [] arr={1,2};
Arrays.asList(arr);
What I ended up doing is create a new KeyContainer name based off of the current DateTime (DateTime.Now.Ticks.ToString()) whenever I need to create a new key and save the container name and public key to the database. Also, whenever I create a new key I would do the following:
public static string ConvertToNewKey(string oldPrivateKey)
{
// get the current container name from the database...
rsa.PersistKeyInCsp = false;
rsa.Clear();
rsa = null;
string privateKey = AssignNewKey(true); // create the new public key and container name and write them to the database...
// re-encrypt existing data to use the new keys and write to database...
return privateKey;
}
public static string AssignNewKey(bool ReturnPrivateKey){
string containerName = DateTime.Now.Ticks.ToString();
// create the new key...
// saves container name and public key to database...
// and returns Private Key XML.
}
before creating the new key.
If you're just interested in increasing the font size of just the first paragraph of any document, an effect used by online publications, then you can use the first-child pseudo-class to achieve the desired effect.
p:first-child
{
font-size: 115%; // Will set the font size to be 115% of the original font-size for the p element.
}
However, this will change the font size of every p element that is the first-child of any other element. If you're interested in setting the size of the first p element of the body element, then use the following:
body > p:first-child
{
font-size: 115%;
}
The above code will only work with the p element that is a child of the body element.
float : 23 bits of significand, 8 bits of exponent, and 1 sign bit.
double : 52 bits of significand, 11 bits of exponent, and 1 sign bit.
You may find these questions helpful:
To set/remove multiple query params at once I've ended up with the methods below as part of my global mixins (this
points to vue component):
setQuery(query){
let obj = Object.assign({}, this.$route.query);
Object.keys(query).forEach(key => {
let value = query[key];
if(value){
obj[key] = value
} else {
delete obj[key]
}
})
this.$router.replace({
...this.$router.currentRoute,
query: obj
})
},
removeQuery(queryNameArray){
let obj = {}
queryNameArray.forEach(key => {
obj[key] = null
})
this.setQuery(obj)
},
Implement both deprecated and non-deprecated methods like below. First one is to handle API level 21 and higher, second one is handle lower than API level 21
webViewClient = object : WebViewClient() {
.
.
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
parseUri(request?.url)
return true
}
@SuppressWarnings("deprecation")
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
parseUri(Uri.parse(url))
return true
}
}