With the advent of Django 1.7, there is now a new update_or_create
QuerySet method, which should do exactly what you want. Just be careful of potential race conditions if uniqueness is not enforced at the database level.
Example from the documentation:
obj, created = Person.objects.update_or_create(
first_name='John', last_name='Lennon',
defaults={'first_name': 'Bob'},
)
The
update_or_create
method tries to fetch an object from database based on the given kwargs. If a match is found, it updates the fields passed in thedefaults
dictionary.
Pre-Django 1.7:
Change the model field values as appropriate, then call .save()
to persist the changes:
try:
obj = Model.objects.get(field=value)
obj.field = new_value
obj.save()
except Model.DoesNotExist:
obj = Model.objects.create(field=new_value)
# do something else with obj if need be
For classed based views use self.request.user.id
The problem here are PHP namespaces. You need to learn how to use them. As your controller are in App\Http\Controllers
namespace, if you refer any other class, you need to add leading backslash (or proper namespace) or add use
statement at the beginning of file (before class definition).
So in your case you could use:
$headquote = \DB::table('quotation_texts')->find(176);
$headquote = \App\Quotation::find(176);
or add in your controller class use
statement so the beginning of your controller class could look like this:
<?php
namespace App\Http\Controllers;
use DB;
use App\Quotation;
For more information about namespaces you could look at How to use objects from other namespaces and how to import namespaces in PHP or namespaces in PHP manual
use MM
(months) instead of mm
(minutes) :
DateTime.Now.ToString("dd/MM/yyyy");
check here for more format options.
There are three options, that you can use. -I
is to exclude binary files in grep. Other are for line numbers and file names.
grep -I -n -H
-I -- process a binary file as if it did not contain matching data;
-n -- prefix each line of output with the 1-based line number within its input file
-H -- print the file name for each match
So this might be a way to run grep:
grep -InH your-word *
Starting Service using Powershell script. You can link this to task scheduler and trigger it at intervals or as needed. Create this as a PS1 file i.e. file with extension PS1 and then let this file be triggered from task scheduler.
To start stop service
in task scheduler if you are using it on server use this in arguments
-noprofile -executionpolicy bypass -file "C:\Service Restart Scripts\StopService.PS1"
verify by running the same on cmd if it works it should work on task scheduler also
$Password = "Enter_Your_Password"
$UserAccount = "Enter_Your_AccountInfor"
$MachineName = "Enter_Your_Machine_Name"
$ServiceList = @("test.SocketService","test.WcfServices","testDesktopService","testService")
$PasswordSecure = $Password | ConvertTo-SecureString -AsPlainText -Force
$Credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $UserAccount, $PasswordSecure
$LogStartTime = Get-Date -Format "MM-dd-yyyy hh:mm:ss tt"
$FileDateTimeStamp = Get-Date -Format "MM-dd-yyyy_hh"
$LogFileName = "C:\Users\krakhil\Desktop\Powershell\Logs\StartService_$FileDateTimeStamp.txt"
#code to start the service
"`n####################################################################" > $LogFileName
"####################################################################" >> $LogFileName
"###################### STARTING SERVICE ##########################" >> $LogFileName
for($i=0;$i -le 3; $i++)
{
"`n`n" >> $LogFileName
$ServiceName = $ServiceList[$i]
"$LogStartTime => Service Name: $ServiceName" >> $LogFileName
Write-Output "`n####################################"
Write-Output "Starting Service - " $ServiceList[$i]
"$LogStartTime => Starting Service: $ServiceName" >> $LogFileName
Start-Service $ServiceList[$i]
$ServiceState = Get-Service | Where-Object {$_.Name -eq $ServiceList[$i]}
if($ServiceState.Status -eq "Running")
{
"$LogStartTime => Started Service Successfully: $ServiceName" >> $LogFileName
Write-Host "`n Service " $ServiceList[$i] " Started Successfully"
}
else
{
"$LogStartTime => Unable to Stop Service: $ServiceName" >> $LogFileName
Write-Output "`n Service didn't Start. Current State is - "
Write-Host $ServiceState.Status
}
}
#code to stop the service
"`n####################################################################" > $LogFileName
"####################################################################" >> $LogFileName
"###################### STOPPING SERVICE ##########################" >> $LogFileName
for($i=0;$i -le 3; $i++)
{
"`n`n" >> $LogFileName
$ServiceName = $ServiceList[$i]
"$LogStartTime => Service Name: $ServiceName" >> $LogFileName
Write-Output "`n####################################"
Write-Output "Stopping Service - " $ServiceList[$i]
"$LogStartTime => Stopping Service: $ServiceName" >> $LogFileName
Stop-Service $ServiceList[$i]
$ServiceState = Get-Service | Where-Object {$_.Name -eq $ServiceList[$i]}
if($ServiceState.Status -eq "Stopped")
{
"$LogStartTime => Stopped Service Successfully: $ServiceName" >> $LogFileName
Write-Host "`n Service " $ServiceList[$i] " Stopped Successfully"
}
else
{
"$LogStartTime => Unable to Stop Service: $ServiceName" >> $LogFileName
Write-Output "`nService didn't Stop. Current State is - "
Write-Host $ServiceState.Status
}
}
It's a bit of an open door, but in the end both are about equally important.
What's worse?
software that does what it needs to do, but internally has problems?
software that is supposed to work if you look at the sources, but doesn't?
My answer: Neither is totally acceptable, but software cannot be proven to be 100% bugfree. So you're going to have to make some trade-offs. Option two is more directly noticable to clients, so you're going to get problems with that sooner. On the long run, option one is going to be problematic.
edit/update:
Xcode 8 or later • Swift 3 or later
var secondsFromGMT: Int { return TimeZone.current.secondsFromGMT() }
secondsFromGMT // -7200
if you need the abbreviation:
var localTimeZoneAbbreviation: String { return TimeZone.current.abbreviation() ?? "" }
localTimeZoneAbbreviation // "GMT-2"
if you need the timezone identifier:
var localTimeZoneIdentifier: String { return TimeZone.current.identifier }
localTimeZoneIdentifier // "America/Sao_Paulo"
To know all timezones abbreviations available:
var timeZoneAbbreviations: [String:String] { return TimeZone.abbreviationDictionary }
timeZoneAbbreviations // ["CEST": "Europe/Paris", "WEST": "Europe/Lisbon", "CDT": "America/Chicago", "EET": "Europe/Istanbul", "BRST": "America/Sao_Paulo", "EEST": "Europe/Istanbul", "CET": "Europe/Paris", "MSD": "Europe/Moscow", "MST": "America/Denver", "KST": "Asia/Seoul", "PET": "America/Lima", "NZDT": "Pacific/Auckland", "CLT": "America/Santiago", "HST": "Pacific/Honolulu", "MDT": "America/Denver", "NZST": "Pacific/Auckland", "COT": "America/Bogota", "CST": "America/Chicago", "SGT": "Asia/Singapore", "CAT": "Africa/Harare", "BRT": "America/Sao_Paulo", "WET": "Europe/Lisbon", "IST": "Asia/Calcutta", "HKT": "Asia/Hong_Kong", "GST": "Asia/Dubai", "EDT": "America/New_York", "WIT": "Asia/Jakarta", "UTC": "UTC", "JST": "Asia/Tokyo", "IRST": "Asia/Tehran", "PHT": "Asia/Manila", "AKDT": "America/Juneau", "BST": "Europe/London", "PST": "America/Los_Angeles", "ART": "America/Argentina/Buenos_Aires", "PDT": "America/Los_Angeles", "WAT": "Africa/Lagos", "EST": "America/New_York", "BDT": "Asia/Dhaka", "CLST": "America/Santiago", "AKST": "America/Juneau", "ADT": "America/Halifax", "AST": "America/Halifax", "PKT": "Asia/Karachi", "GMT": "GMT", "ICT": "Asia/Bangkok", "MSK": "Europe/Moscow", "EAT": "Africa/Addis_Ababa"]
To know all timezones names (identifiers) available:
var timeZoneIdentifiers: [String] { return TimeZone.knownTimeZoneIdentifiers }
timeZoneIdentifiers // ["Africa/Abidjan", "Africa/Accra", "Africa/Addis_Ababa", "Africa/Algiers", "Africa/Asmara", "Africa/Bamako", "Africa/Bangui", "Africa/Banjul", "Africa/Bissau", "Africa/Blantyre", "Africa/Brazzaville", "Africa/Bujumbura", "Africa/Cairo", "Africa/Casablanca", "Africa/Ceuta", "Africa/Conakry", "Africa/Dakar", "Africa/Dar_es_Salaam", "Africa/Djibouti", "Africa/Douala", "Africa/El_Aaiun", "Africa/Freetown", "Africa/Gaborone", "Africa/Harare", "Africa/Johannesburg", "Africa/Juba", "Africa/Kampala", "Africa/Khartoum", "Africa/Kigali", "Africa/Kinshasa", "Africa/Lagos", "Africa/Libreville", "Africa/Lome", "Africa/Luanda", "Africa/Lubumbashi", "Africa/Lusaka", "Africa/Malabo", "Africa/Maputo", "Africa/Maseru", "Africa/Mbabane", "Africa/Mogadishu", "Africa/Monrovia", "Africa/Nairobi", "Africa/Ndjamena", "Africa/Niamey", "Africa/Nouakchott", "Africa/Ouagadougou", "Africa/Porto-Novo", "Africa/Sao_Tome", "Africa/Tripoli", "Africa/Tunis", "Africa/Windhoek", "America/Adak", "America/Anchorage", "America/Anguilla", "America/Antigua", "America/Araguaina", "America/Argentina/Buenos_Aires", "America/Argentina/Catamarca", "America/Argentina/Cordoba", "America/Argentina/Jujuy", "America/Argentina/La_Rioja", "America/Argentina/Mendoza", "America/Argentina/Rio_Gallegos", "America/Argentina/Salta", "America/Argentina/San_Juan", "America/Argentina/San_Luis", "America/Argentina/Tucuman", "America/Argentina/Ushuaia", "America/Aruba", "America/Asuncion", "America/Atikokan", "America/Bahia", "America/Bahia_Banderas", "America/Barbados", "America/Belem", "America/Belize", "America/Blanc-Sablon", "America/Boa_Vista", "America/Bogota", …, "Pacific/Marquesas", "Pacific/Midway", "Pacific/Nauru", "Pacific/Niue", "Pacific/Norfolk", "Pacific/Noumea", "Pacific/Pago_Pago", "Pacific/Palau", "Pacific/Pitcairn", "Pacific/Pohnpei", "Pacific/Ponape", "Pacific/Port_Moresby", "Pacific/Rarotonga", "Pacific/Saipan", "Pacific/Tahiti", "Pacific/Tarawa", "Pacific/Tongatapu", "Pacific/Truk", "Pacific/Wake", "Pacific/Wallis"]
There is a few other info you may need:
var isDaylightSavingTime: Bool { return TimeZone.current.isDaylightSavingTime(for: Date()) }
print(isDaylightSavingTime) // true (in effect)
var daylightSavingTimeOffset: TimeInterval { return TimeZone.current.daylightSavingTimeOffset() }
print(daylightSavingTimeOffset) // 3600 seconds (1 hour - daylight savings time)
var nextDaylightSavingTimeTransition: Date? { return TimeZone.current.nextDaylightSavingTimeTransition } // "Feb 18, 2017, 11:00 PM"
print(nextDaylightSavingTimeTransition?.description(with: .current) ?? "none")
nextDaylightSavingTimeTransition // "Saturday, February 18, 2017 at 11:00:00 PM Brasilia Standard Time\n"
var nextDaylightSavingTimeTransitionAfterNext: Date? {
guard
let nextDaylightSavingTimeTransition = nextDaylightSavingTimeTransition
else { return nil }
return TimeZone.current.nextDaylightSavingTimeTransition(after: nextDaylightSavingTimeTransition)
}
nextDaylightSavingTimeTransitionAfterNext // "Oct 15, 2017, 1:00 AM"
From my understanding of the question,this can use a fairly straight forward solution.Anyway below is the method i propose ,this method takes in a data table and then using SQL statements to insert into a table in the database.Please mind that my solution is using MySQLConnection and MySqlCommand replace it with SqlConnection and SqlCommand.
public void InsertTableIntoDB_CreditLimitSimple(System.Data.DataTable tblFormat)
{
for (int i = 0; i < tblFormat.Rows.Count; i++)
{
String InsertQuery = string.Empty;
InsertQuery = "INSERT INTO customercredit " +
"(ACCOUNT_CODE,NAME,CURRENCY,CREDIT_LIMIT) " +
"VALUES ('" + tblFormat.Rows[i]["AccountCode"].ToString() + "','" + tblFormat.Rows[i]["Name"].ToString() + "','" + tblFormat.Rows[i]["Currency"].ToString() + "','" + tblFormat.Rows[i]["CreditLimit"].ToString() + "')";
using (MySqlConnection destinationConnection = new MySqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
using (var dbcm = new MySqlCommand(InsertQuery, destinationConnection))
{
destinationConnection.Open();
dbcm.ExecuteNonQuery();
}
}
}//CreditLimit
A transaction isn't needed here, this should suffice:
function add_post($post_data) {
$this->db->insert('posts',$post_data);
return $this->db->insert_id();
}
Others coming around here might do well to read http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx which talks about limitations of XDomainRequest
It's because Arrays.asList(array)
return List<int[]>
. array
argument is treated as one value you want to wrap (you get list of arrays of ints), not as vararg.
Note that it does work with object types (not primitives):
public boolean contains(final String[] array, final String key) {
return Arrays.asList(array).contains(key);
}
or even:
public <T> boolean contains(final T[] array, final T key) {
return Arrays.asList(array).contains(key);
}
But you cannot have List<int>
and autoboxing is not working here.
This method will use the LocationManager service.
Source Link
//Check GPS Status true/false
public static boolean checkGPSStatus(Context context){
LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE );
boolean statusOfGPS = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
return statusOfGPS;
};
Aside from the clear: both
hack, you can skip the extra element and use overflow: hidden
on the wrapping div
:
<div style="overflow: hidden;">
<div style="float: left;"></div>
<div style="float: left;"></div>
</div>
Note that you can only read a stream once, so in some cases, you may need to clone the response in order to repeatedly read it:
fetch('example.json')
.then(res=>res.clone().json())
.then( json => console.log(json))
fetch('url_that_returns_text')
.then(res=>res.clone().text())
.then( text => console.log(text))
I can't find a way to create a table with icons in SO, so I am uploading 2 images.
IMO, froadie's simple concatenation is fine for a simple case like you presented. If you want to put together several strings, the string join method seems to be preferred:
the_text = ''.join(['the ', 'quick ', 'brown ', 'fox ', 'jumped ', 'over ', 'the ', 'lazy ', 'dog.'])
Edit: Note that join wants an iterable (e.g. a list) as its single argument.
On server-side it will be not as accurate as with JavaScript. Meanwhile, sometimes it is required to solve such task. Just to share the possible solution in this case I write this answer.
If you need to determine user's time zone it could be done via Geo-IP services. Some of them providing timezone. For example, this one (http://smart-ip.net/geoip-api) could help:
<?php
$ip = $_SERVER['REMOTE_ADDR']; // means we got user's IP address
$json = file_get_contents( 'http://smart-ip.net/geoip-json/' . $ip); // this one service we gonna use to obtain timezone by IP
// maybe it's good to add some checks (if/else you've got an answer and if json could be decoded, etc.)
$ipData = json_decode( $json, true);
if ($ipData['timezone']) {
$tz = new DateTimeZone( $ipData['timezone']);
$now = new DateTime( 'now', $tz); // DateTime object corellated to user's timezone
} else {
// we can't determine a timezone - do something else...
}
I was using .NET Framework 4.5 but my new library had .NET Framework 4.5.2 and I got the same issue when I tried to build. I solved it by updating my project from 4.5 to 4.5.2 (same as my library).
find the file pg_hba.conf
- it may be located, for example in /etc/postgresql-9.1/pg_hba.conf
.
cd /etc/postgresql-9.1/
Back it up
cp pg_hba.conf pg_hba.conf-backup
place the following line (as either the first uncommented line, or as the only one):
For all occurrence of below (local and host) , exepct replication section if you don't have any it has to be changed as follow ,no MD5 or Peer autehication should be present.
local all all trust
restart your PostgreSQL server (e.g., on Linux:)
sudo /etc/init.d/postgresql restart
If the service (daemon) doesn't start reporting in log file:
local connections are not supported by this build
you should change
local all all trust
to
host all all 127.0.0.1/32 trust
you can now connect as any user. Connect as the superuser postgres
(note, the superuser name may be different in your installation. In some systems it is called pgsql
, for example.)
psql -U postgres
or
psql -h 127.0.0.1 -U postgres
(note that with the first command you will not always be connected with local host)
Reset password ('replace my_user_name with postgres since you are resetting postgres user)
ALTER USER my_user_name with password 'my_secure_password';
Restore the old pg_hba.conf
as it is very dangerous to keep around
cp pg_hba.conf-backup pg_hba.conf
restart the server, in order to run with the safe pg_hba.conf
sudo /etc/init.d/postgresql restart
Further Reading about that pg_hba file: http://www.postgresql.org/docs/9.1/static/auth-pg-hba-conf.html
It worked for me
ssh -i [your id_rsa path] -T [email protected]
null
is a value assigned to a reference type. null
is a reserved value, indicating that a reference does not resemble an instance of an object.
A boolean
is not an instance of an Object. It is a primitive type, like int
and float
. In the same way that: int x
has a value of 0
, boolean x
has a value of false
.
In 12c, here's the new way:
select bla
from bla
where bla
order by finaldate desc
fetch first 1 rows only;
How nice is that!
The default limit for the length of the request line is 8190 bytes (see LimitRequestLine
directive). And if we subtract three bytes for the request method (i.e. GET
), eight bytes for the version information (i.e. HTTP/1.0
/HTTP/1.1
) and two bytes for the separating space, we end up with 8177 bytes for the URI path plus query.
We can include and exclude data types as per the requirement as below:
train.select_dtypes(include=None, exclude=None)
train.select_dtypes(include='number') #will include all the numeric types
Referred from Jupyter Notebook.
To select all numeric types, use np.number
or 'number'
To select strings you must use the object
dtype but note that
this will return all object dtype columns
See the NumPy dtype hierarchy <http://docs.scipy.org/doc/numpy/reference/arrays.scalars.html>
__
To select datetimes, use np.datetime64
, 'datetime'
or
'datetime64'
To select timedeltas, use np.timedelta64
, 'timedelta'
or
'timedelta64'
To select Pandas categorical dtypes, use 'category'
To select Pandas datetimetz dtypes, use 'datetimetz'
(new in
0.20.0) or ``'datetime64[ns, tz]'
Mozilla's MDN suggests something like the following [source]:
p {
width: intrinsic; /* Safari/WebKit uses a non-standard name */
width: -moz-max-content; /* Firefox/Gecko */
width: -webkit-max-content; /* Chrome */
}
#many .more.selectors h4 + p { ... }
This is called the adjacent sibling selector.
Every things seems correct. You might want to use the following css selector instead of what you used.
ul > li:not(:last-child):after
if you are using extracted tomcat then,
startup.sh
and shutdown.sh
are two script located in TOMCAT/bin/ to start and shutdown tomcat, You could use that
if tomcat is installed then
/etc/init.d/tomcat5.5 start
/etc/init.d/tomcat5.5 stop
/etc/init.d/tomcat5.5 restart
Just add them:
['it'] + ['was'] + ['annoying']
You should read the Python tutorial to learn basic info like this.
you can use
state.name for state in states track by state.code
Where states in the JSON array, state is the variable name for each object in the array.
Hope this helps
I would use GCJ (GNU Compiler for Java) in your situation. It's an AOT (ahead of time) compiler for Java, much like GCC is for C. Instead of interpreting code, or generating intermediate java code to be run at a later time by the Java VM, it generates machine code.
GCJ is available on almost any Linux system through its respective package manager (if available). After installation, the GCJ compiler should be added to the path so that it can be invoked through the terminal. If you're using Windows, you can download and install GCJ through Cygwin or MinGW.
I would strongly recommend, however, that you rewrite your source for another language that is meant to be compiled, such as C++. Java is meant to be a portable, interpreted language. Compiling it to machine code is completely against what the language was developed for.
The answer by @akrun certainly does the trick. For future googlers who want to understand why, here is an explanation...
The new variable needs to be created first.
The variable "valueBin" needs to be already in the df in order for the conditional assignment to work. Essentially, the syntax of the code is correct. Just add one line in front of the code chuck to create this name --
df$newVariableName <- NA
Then you continue with whatever conditional assignment rules you have, like
df$newVariableName[which(df$oldVariableName<=250)] <- "<=250"
I blame whoever wrote that package's error message... The debugging was made especially confusing by that error message. It is irrelevant information that you have two arrays in the df with different lengths. No. Simply create the new column first. For more details, consult this post https://www.r-bloggers.com/translating-weird-r-errors/
Not a perfect solution, but this CSS might help. The zoom is what makes this code work, and the factor should theoretically be infinite to work ideally for small images - but 2, 4, or 8 works fine in most cases.
#myImage {
zoom: 2; //increase if you have very small images
display: block;
margin: auto;
height: auto;
max-height: 100%;
width: auto;
max-width: 100%;
}
Certainly not the only way - you could prototype a method (against Object here but I certainly wouldn't suggest using Object for live code) to replicate C#/Java style comparison methods.
Edit, since a general example seems to be expected:
Object.prototype.equals = function(x)
{
for(p in this)
{
switch(typeof(this[p]))
{
case 'object':
if (!this[p].equals(x[p])) { return false }; break;
case 'function':
if (typeof(x[p])=='undefined' || (p != 'equals' && this[p].toString() != x[p].toString())) { return false; }; break;
default:
if (this[p] != x[p]) { return false; }
}
}
for(p in x)
{
if(typeof(this[p])=='undefined') {return false;}
}
return true;
}
Note that testing methods with toString() is absolutely not good enough but a method which would be acceptable is very hard because of the problem of whitespace having meaning or not, never mind synonym methods and methods producing the same result with different implementations. And the problems of prototyping against Object in general.
kernel.json
file:My solution is useful if you need the same environment variables every time you start a jupyter kernel, especially if you have multiple sets of environment variables for different tasks.
To create a new ipython kernel with your environment variables, do the following:
jupyter kernelspec list
to see a list with installed kernels and where the files are stored.python2
) to a new directory (e.g. python2_myENV
).display_name
in the new kernel.json
file.env
dictionary defining the environment variables.Your kernel json could look like this (I did not modify anything from the installed kernel.json except display_name
and env
):
{
"display_name": "Python 2 with environment",
"language": "python",
"argv": [
"/usr/bin/python2",
"-m",
"ipykernel_launcher",
"-f",
"{connection_file}"
],
"env": {"LD_LIBRARY_PATH":""}
}
LD_LIBRARY_PATH
which effects how compiled modules (e.g. written in C) are loaded. Setting this variable using %set_env
did not work.You can just use:
<ng-template [ngIf]="index == 1">First</ng-template>
<ng-template [ngIf]="index == 2">Second</ng-template>
<ng-template [ngIf]="index == 3">Third</ng-template>
unless the ng-container part is important to your design I suppose.
Here's a Plunker
A few line of java code.
public static void main(String args[]) throws Exception{
String str="test string";
MessageDigest messageDigest=MessageDigest.getInstance("MD5");
messageDigest.update(str.getBytes(),0,str.length());
System.out.println("MD5: "+new BigInteger(1,messageDigest.digest()).toString(16));
}
It's simple. Just change the port. Use 3268 instead of 389. If your domain name DOMAIN.LOCAL, in search put DC=DOMAIN,DC=LOCAL
Port 3268: This port is used for queries that are specifically targeted for the global catalog. LDAP requests sent to port 3268 can be used to search objects in the entire forest. However, only the attributes marked for replication to the global catalog can be returned.
Port 389: This port is used for requesting information from the Domain Controller. LDAP requests sent to port 389 can be used to search objects only within the global catalog’s home domain. However, the application can possible to obtain all of the attributes searched objects.
In Support Library 27.1.0 and later, Google has introduced new methods requireContext()
and requireActivity()
methods.
Eg:ContextCompat.getColor(requireContext(), R.color.soft_gray)
More info here
Instead of using @Controller and @ResponseBody, @RestController let's you expose Rest APIs in Spring 4.0 and above.
I solve the problem. So simple. Syntax error.
But I also want to know how to pass a function with parameters to view....
how about:
scope.$watch(function() {
return {
a: thing-one,
b: thing-two,
c: red-fish,
d: blue-fish
};
}, listener...);
Easiest way to do it would be this
std::string myWord = "myWord";
char myArray[myWord.size()+1];//as 1 char space for null is also required
strcpy(myArray, myWord.c_str());
Firstly a quick recap on RSA key generation.
The public key consists of the modulus and the public exponent.
A minimal private key would consist of the modulus and the private exponent. There is no computationally feasible surefire way to go from a known modulus and private exponent to the corresponding public exponent.
However:
So in most practical RSA implementations you can get the public key from the private key. It would be possible to build a RSA based cryptosystem where this was not possible, but it is not the done thing.
$("#element").removeAttr("class").addClass("yourClass");
May or may not be accurate, but according to this site: http://www.htmlite.com/mysql003.php.
BLOB A string with a maximum length of 65535 characters.
The MySQL manual says:
The maximum size of a BLOB or TEXT object is determined by its type, but the largest value you actually can transmit between the client and server is determined by the amount of available memory and the size of the communications buffers
I think the first site gets their answers from interpreting the MySQL manual, per http://dev.mysql.com/doc/refman/5.0/en/storage-requirements.html
To complement the previous stated solution, use:
str = str.replace("%", "%%");
just give
a{
color:blue
}
even if its is visited it will always be blue
SQL Server has no setting to control query timeout in the connection string, and as far as I know this is the same for other major databases. But, this doesn't look like the problem you're seeing: I'd expect to see an exception raised
Error: System.Data.SqlClient.SqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
if there genuinely was a timeout executing the query.
If this does turn out to be a problem, you can change the default timeout for a SQL Server database as a property of the database itself; use SQL Server Manager for this.
Be sure that the query is exactly the same from your Web application as the one you're running directly. Use a profiler to verify this.
Explanation of shutdown and close: Graceful shutdown (msdn)
Shutdown (in your case) indicates to the other end of the connection there is no further intention to read from or write to the socket. Then close frees up any memory associated with the socket.
Omitting shutdown may cause the socket to linger in the OSs stack until the connection has been closed gracefully.
IMO the names 'shutdown' and 'close' are misleading, 'close' and 'destroy' would emphasise their differences.
To add to the (really good) existing answer
open_basedir
is one that can stump you because it can be specified in a web server configuration. While this is easily remedied if you run your own dedicated server, there are some shared hosting software packages out there (like Plesk, cPanel, etc) that will configure a configuration directive on a per-domain basis. Because the software builds the configuration file (i.e. httpd.conf
) you cannot change that file directly because the hosting software will just overwrite it when it restarts.
With Plesk, they provide a place to override the provided httpd.conf
called vhost.conf
. Only the server admin can write this file. The configuration for Apache looks something like this
<Directory /var/www/vhosts/domain.com>
<IfModule mod_php5.c>
php_admin_flag engine on
php_admin_flag safe_mode off
php_admin_value open_basedir "/var/www/vhosts/domain.com:/tmp:/usr/share/pear:/local/PEAR"
</IfModule>
</Directory>
Have your server admin consult the manual for the hosting and web server software they use.
It's important to note that executing a file through your web server is very different from a command line or cron job execution. The big difference is that your web server has its own user and permissions. For security reasons that user is pretty restricted. Apache, for instance, is often apache
, www-data
or httpd
(depending on your server). A cron job or CLI execution has whatever permissions that the user running it has (i.e. running a PHP script as root will execute with permissions of root).
A lot of times people will solve a permissions problem by doing the following (Linux example)
chmod 777 /path/to/file
This is not a smart idea, because the file or directory is now world writable. If you own the server and are the only user then this isn't such a big deal, but if you're on a shared hosting environment you've just given everyone on your server access.
What you need to do is determine the user(s) that need access and give only those them access. Once you know which users need access you'll want to make sure that
That user owns the file and possibly the parent directory (especially the parent directory if you want to write files). In most shared hosting environments this won't be an issue, because your user should own all the files underneath your root. A Linux example is shown below
chown apache:apache /path/to/file
The user, and only that user, has access. In Linux, a good practice would be chmod 600
(only owner can read and write) or chmod 644
(owner can write but everyone can read)
You can read a more extended discussion of Linux/Unix permissions and users here
Each iteration of the forEach()
will call the function that you have supplied. To stop further processing within any given iteration (and continue with the next item) you just have to return
from the function at the appropriate point:
elementsCollection.forEach(function(element){
if (!element.shouldBeProcessed)
return; // stop processing this iteration
// This part will be avoided if not neccessary
doSomeLengthyOperation();
});
The "no frills" options are as follows:
ActiveSheet.Name = "New Name"
and
Sheets("Sheet2").Name = "New Name"
You can also check out recording macros and seeing what code it gives you, it's a great way to start learning some of the more vanilla functions.
its totall wrong. INSERT QUERY does not have a WHERE clause, Only UPDATE QUERY has it. If you want to add data Where id = 1 then your Query will be
UPDATE Users SET weight=160, desiredWeight= 145 WHERE id = 1;
You can use sub query way of codeigniter to do this for this purpose you will have to hack codeigniter. like this
Go to system/database/DB_active_rec.php
Remove public or protected keyword from these functions
public function _compile_select($select_override = FALSE)
public function _reset_select()
Now subquery writing in available And now here is your query with active record
$this->db->select('trans_id');
$this->db->from('myTable');
$this->db->where('code','B');
$subQuery = $this->db->_compile_select();
$this->db->_reset_select();
// And now your main query
$this->db->select("*");
$this->db->where_in("$subQuery");
$this->db->where('code !=', 'B');
$this->db->get('myTable');
And the thing is done. Cheers!!!
Note : While using sub queries you must use
$this->db->from('myTable')
instead of
$this->db->get('myTable')
which runs the query.
Watch this too
How can I rewrite this SQL into CodeIgniter's Active Records?
Note : In Codeigntier 3 these functions are already public so you do not need to hack them.
using this worked for me
git rm -f --cached <filename>
Simply pass the sorted items from the dictionary to the plot()
function. concentration.items()
returns a list of tuples where each tuple contains a key from the dictionary and its corresponding value.
You can take advantage of list unpacking (with *
) to pass the sorted data directly to zip, and then again to pass it into plot()
:
import matplotlib.pyplot as plt
concentration = {
0: 0.19849878712984576,
5000: 0.093917341754771386,
10000: 0.075060643507712022,
20000: 0.06673074282575861,
30000: 0.057119318961966224,
50000: 0.046134834546203485,
100000: 0.032495766396631424,
200000: 0.018536317451599615,
500000: 0.0059499290585381479}
plt.plot(*zip(*sorted(concentration.items())))
plt.show()
sorted()
sorts tuples in the order of the tuple's items so you don't need to specify a key
function because the tuples returned by dict.item()
already begin with the key value.
This code block solve my problem,
<script type="text/javascript">_x000D_
$(window).bind("load", function () {_x000D_
// Code here_x000D_
});_x000D_
</script>
_x000D_
For posterity, also check server logs to see if the resource being requested is returning a 200.
I ran into a similar issue, where all of the proper headers were being returned in the pre-flight ajax request, but the browser reported the actual request was blocked due to bad CORS headers.
Turns out, the page being requested was returning a 500 error due to bad code, but only when it was fetched via CORS. The browser (both Chrome and Firefox) mistakenly reported that the Access-Control-Allow-Origin header was missing instead of saying the page returned a 500.
Similar to other answers, this error can be experienced when there are no sites configured to use SSL.
I had the error when I upgraded from Debian Wheezy to Debian Jessie. The new version of Apache requires a site configuration file ending in .conf
. Because my configuration file didn't, it was being ignored, and there were no others configured to serve SSL connections.
NanoHttpd works like a charm on Android -- we have code in production, in users hands, that's built on it.
The license absolutely allows commercial use of NanoHttpd, without any "viral" implications.
Just because @MartinCapodici 's comment is awesome I write here as an answer to give visibility.
All clockwise:
A good example of the 307 Internal Redirect
in action is when Google Chrome encounters a HTTP call to a domain it knows as requiring Strict Transport Security.
The browser redirects seamlessly, using the same method as the original call.
It's not a standard lib of python 2.7. So in order for these to work properly and if you're using Python 2.7 you should download the PIL library first: Direct download link: http://effbot.org/downloads/PIL-1.1.7.win32-py2.7.exe After installing it, follow these steps:
Edit your script.py
from Tkinter import *
from PIL import ImageTk, Image
app_root = Tk()
#Setting it up
img = ImageTk.PhotoImage(Image.open("app.png"))
#Displaying it
imglabel = Label(app_root, image=img).grid(row=1, column=1)
app_root.mainloop()
Hope that helps!
The problem is with line
imageWidth = 1 * Convert.ToInt32(Label1.Text);
Label1.Text
may or may not be int. Check.
Use Int32.TryParse(value, out number)
instead. That will solve your problem.
int imageWidth;
if(Int32.TryParse(Label1.Text, out imageWidth))
{
Image1.Width= imageWidth;
}
Using this,
String s = "03/24/2013 21:54";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm");
try
{
Date date = simpleDateFormat.parse(s);
System.out.println("date : "+simpleDateFormat.format(date));
}
catch (ParseException ex)
{
System.out.println("Exception "+ex);
}
Actually I just found out that there is even one more way of getting a country code, using the getSimCountryIso() method of TelephoneManager
:
TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String countryCode = tm.getSimCountryIso();
Since it is the sim code it also should not change when traveling to other countries.
In [56]: df = pd.DataFrame(np.abs(randn(3, 4)), index=[1,2,3], columns=['A','B','C','D'])
In [57]: df.divide(df.sum(axis=1), axis=0)
Out[57]:
A B C D
1 0.319124 0.296653 0.138206 0.246017
2 0.376994 0.326481 0.230464 0.066062
3 0.036134 0.192954 0.430341 0.340571
You could use following code:
<style>
.svgwrapper {
position: relative;
}
.svgwrapper {
position: absolute;
z-index: -1;
}
</style>
<div class="svgwrapper" onClick="function();">
<object src="blah" />
</div>
b3ng0 wrote similar code but it does not work. z-index of parent must be auto.
#!/bin/sh
# http://www.tldp.org/LDP/abs/html/io-redirection.html
echo "Hello World"
exec > script.log 2>&1
echo "Start logging out from here to a file"
bad command
echo "End logging out from here to a file"
exec > /dev/tty 2>&1 #redirects out to controlling terminal
echo "Logged in the terminal"
Output:
> ./above_script.sh
Hello World
Not logged in the file
> cat script.log
Start logging out from here to a file
./logging_sample.sh: line 6: bad: command not found
End logging out from here to a file
Read more here: http://www.tldp.org/LDP/abs/html/io-redirection.html
Other solution:
var dateAv = new Date();
var endTime = new Date(dateAv.getFullYear(), dateAv.getMonth(), dateAv.getDate(), dateAv.getHours(), dateAv.getMinutes() + 30);
The long rest in between is due to your keyframe settings. Your current keyframe rules mean that the actual bounce happens only between 40% - 60% of the animation duration (that is, between 1s - 1.5s mark of the animation). Remove those rules and maybe even reduce the animation-duration
to suit your needs.
.animated {_x000D_
-webkit-animation-duration: .5s;_x000D_
animation-duration: .5s;_x000D_
-webkit-animation-fill-mode: both;_x000D_
animation-fill-mode: both;_x000D_
-webkit-animation-timing-function: linear;_x000D_
animation-timing-function: linear;_x000D_
animation-iteration-count: infinite;_x000D_
-webkit-animation-iteration-count: infinite;_x000D_
}_x000D_
@-webkit-keyframes bounce {_x000D_
0%, 100% {_x000D_
-webkit-transform: translateY(0);_x000D_
}_x000D_
50% {_x000D_
-webkit-transform: translateY(-5px);_x000D_
}_x000D_
}_x000D_
@keyframes bounce {_x000D_
0%, 100% {_x000D_
transform: translateY(0);_x000D_
}_x000D_
50% {_x000D_
transform: translateY(-5px);_x000D_
}_x000D_
}_x000D_
.bounce {_x000D_
-webkit-animation-name: bounce;_x000D_
animation-name: bounce;_x000D_
}_x000D_
#animated-example {_x000D_
width: 20px;_x000D_
height: 20px;_x000D_
background-color: red;_x000D_
position: relative;_x000D_
top: 100px;_x000D_
left: 100px;_x000D_
border-radius: 50%;_x000D_
}_x000D_
hr {_x000D_
position: relative;_x000D_
top: 92px;_x000D_
left: -300px;_x000D_
width: 200px;_x000D_
}
_x000D_
<div id="animated-example" class="animated bounce"></div>_x000D_
<hr>
_x000D_
Here is how your original keyframe
settings would be interpreted by the browser:
translate
by 0px in Y axis.translate
by 0px in Y axis.translate
by 0px in Y axis.translate
by 5px in Y axis. This results in a gradual upward movement.translate
by 0px in Y axis. This results in a gradual downward movement.translate
by 0px in Y axis.translate
by 0px in Y axis.Normally Python throws NameError
if the variable is not defined:
>>> d[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined
However, you've managed to stumble upon a name that already exists in Python.
Because dict
is the name of a built-in type in Python you are seeing what appears to be a strange error message, but in reality it is not.
The type of dict
is a type
. All types are objects in Python. Thus you are actually trying to index into the type
object. This is why the error message says that the "'type' object is not subscriptable."
>>> type(dict)
<type 'type'>
>>> dict[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'type' object is not subscriptable
Note that you can blindly assign to the dict
name, but you really don't want to do that. It's just going to cause you problems later.
>>> dict = {1:'a'}
>>> type(dict)
<class 'dict'>
>>> dict[1]
'a'
The true source of the problem is that you must assign variables prior to trying to use them. If you simply reorder the statements of your question, it will almost certainly work:
d = {1: "walk1.png", 2: "walk2.png", 3: "walk3.png"}
m1 = pygame.image.load(d[1])
m2 = pygame.image.load(d[2])
m3 = pygame.image.load(d[3])
playerxy = (375,130)
window.blit(m1, (playerxy))
Since I wanted to compare two arrays for a unit Test and I arrived on this answer I thought I could share.
You can also do it with:
@Test
public void testTwoArrays() {
byte[] array = new BigInteger("1111000011110001", 2).toByteArray();
byte[] secondArray = new BigInteger("1111000011110001", 2).toByteArray();
Assert.assertArrayEquals(array, secondArray);
}
And you could check on Comparing arrays in JUnit assertions for more infos.
I have found a solution by myself. I use the PDANet tool to find the driver automatically.
Just for the sake of completeness, here is a solution with lambda and method reference:
Description: The following method
String
with the pattern yyyy-MM-dd
into a Timestamp
, if a valid input is given,null
, if a null
value is given,DateTimeParseException
, if an invalid input is givenCode:
static Timestamp convertStringToTimestamp(String strDate) {
return Optional.ofNullable(strDate) // wrap the String into an Optional
.map(str -> LocalDate.parse(str).atStartOfDay()) // convert into a LocalDate and fix the hour:minute:sec to 00:00:00
.map(Timestamp::valueOf) // convert to Timestamp
.orElse(null); // if no value is present, return null
}
Validation:
This method can be tested with those unit tests:
(with Junit5 and Hamcrest)
@Test
void convertStringToTimestamp_shouldReturnTimestamp_whenValidInput() {
// given
String strDate = "2020-01-30";
// when
final Timestamp result = convertStringToTimestamp(strDate);
// then
final LocalDateTime dateTime = LocalDateTime.ofInstant(result.toInstant(), ZoneId.systemDefault());
assertThat(dateTime.getYear(), is(2020));
assertThat(dateTime.getMonthValue(), is(1));
assertThat(dateTime.getDayOfMonth(), is(30));
}
@Test
void convertStringToTimestamp_shouldReturnTimestamp_whenInvalidInput() {
// given
String strDate = "7770-91-30";
// when, then
assertThrows(DateTimeParseException.class, () -> convertStringToTimestamp(strDate));
}
@Test
void convertStringToTimestamp_shouldReturnTimestamp_whenNullInput() {
// when
final Timestamp result = convertStringToTimestamp(null);
// then
assertThat(result, is(nullValue()));
}
Usually, the string to parse comes with another format. A way to deal with it is to use a formatter to convert it to another format. Here is an example:
Input: 20200130 11:30
Pattern: yyyyMMdd HH:mm
Output: Timestamp of this input
Code:
static Timestamp convertStringToTimestamp(String strDate) {
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm");
return Optional.ofNullable(strDate) //
.map(str -> LocalDateTime.parse(str, formatter))
.map(Timestamp::valueOf) //
.orElse(null);
}
Test:
@Test
void convertStringToTimestamp_shouldReturnTimestamp_whenValidInput() {
// given
String strDate = "20200130 11:30";
// when
final Timestamp result = convertStringToTimestamp(strDate);
// then
final LocalDateTime dateTime = LocalDateTime.ofInstant(result.toInstant(), ZoneId.systemDefault());
assertThat(dateTime.getYear(), is(2020));
assertThat(dateTime.getMonthValue(), is(1));
assertThat(dateTime.getDayOfMonth(), is(30));
assertThat(dateTime.getHour(), is(11));
assertThat(dateTime.getMinute(), is(30));
}
The general format, from the @link section of the javadoc documentation, is:
Method in the same class:
/** See also {@link #myMethod(String)}. */
void foo() { ... }
Method in a different class, either in the same package or imported:
/** See also {@link MyOtherClass#myMethod(String)}. */
void foo() { ... }
Method in a different package and not imported:
/** See also {@link com.mypackage.YetAnotherClass#myMethod(String)}. */
void foo() { ... }
Label linked to method, in plain text rather than code font:
/** See also this {@linkplain #myMethod(String) implementation}. */
void foo() { ... }
A chain of method calls, as in your question. We have to specify labels for the links to methods outside this class, or we get getFoo().Foo.getBar().Bar.getBaz()
. But these labels can be fragile during refactoring -- see "Labels" below.
/**
* A convenience method, equivalent to
* {@link #getFoo()}.{@link Foo#getBar() getBar()}.{@link Bar#getBaz() getBaz()}.
* @return baz
*/
public Baz fooBarBaz()
Automated refactoring may not affect labels. This includes renaming the method, class or package; and changing the method signature.
Therefore, provide a label only if you want different text than the default.
For example, you might link from human language to code:
/** You can also {@linkplain #getFoo() get the current foo}. */
void setFoo( Foo foo ) { ... }
Or you might link from a code sample with text different than the default, as shown above under "A chain of method calls." However, this can be fragile while APIs are evolving.
If the method signature includes parameterized types, use the erasure of those types in the javadoc @link. For example:
int bar( Collection<Integer> receiver ) { ... }
/** See also {@link #bar(Collection)}. */
void foo() { ... }
This is not something you can do in a foolproof way. One possibility would be to examine every character in the file to ensure that it doesn't contain any characters in the ranges 0x00 - 0x1f
or 0x7f -0x9f
but, as I said, this may be true for any number of files, including at least one other variant of ISO8859.
Another possibility is to look for specific words in the file in all of the languages supported and see if you can find them.
So, for example, find the equivalent of the English "and", "but", "to", "of" and so on in all the supported languages of 8859-1 and see if they have a large number of occurrences within the file.
I'm not talking about literal translation such as:
English French
------- ------
of de, du
and et
the le, la, les
although that's possible. I'm talking about common words in the target language (for all I know, Icelandic has no word for "and" - you'd probably have to use their word for "fish" [sorry that's a little stereotypical, I didn't mean any offense, just illustrating a point]).
//How decodeURIComponent Works
function proURIDecoder(val)
{
val=val.replace(/\+/g, '%20');
var str=val.split("%");
var cval=str[0];
for (var i=1;i<str.length;i++)
{
cval+=String.fromCharCode(parseInt(str[i].substring(0,2),16))+str[i].substring(2);
}
return cval;
}
document.write(proURIDecoder(window.location.href));
THE CORRECT WAY IS :
UPDATE test1
INNER JOIN test2 ON (test1.id = test2.id)
SET test1.data = test2.data
Directly from the GitHub project homepage:
Dapper allow you to pass in IEnumerable and will automatically parameterize your query.
connection.Query<int>(
@"select *
from (select 1 as Id union all select 2 union all select 3) as X
where Id in @Ids",
new { Ids = new int[] { 1, 2, 3 });
Will be translated to:
select *
from (select 1 as Id union all select 2 union all select 3) as X
where Id in (@Ids1, @Ids2, @Ids3)
// @Ids1 = 1 , @Ids2 = 2 , @Ids2 = 3
Please check Michael answer and vote for it. It is the right way to check open ports. Netstat and other tools are not any use if you are developing services or daemons. For instance, I am crating modbus TCP server and client services for an industrial network. The services can listen to any port, but the question is whether that port is open? The program is going to be used in different places, and I cannot check them all manually, so this is what I did:
from contextlib import closing
import socket
class example:
def __init__():
self.machine_ip = socket.gethostbyname(socket.gethostname())
self.ready:bool = self.check_socket()
def check_socket(self)->bool:
result:bool = True
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
modbus_tcp_port:int = 502
if not sock.connect_ex((self.machine_ip, modbus_tcp_port)) == 0:
result = False
return result
$ docker-compose up -d --no-deps --build <service_name>
--no-deps - Don't start linked services.
--build - Build images before starting containers.
Depending on the issue, whether it's JAVA home path not correctly set or missing msvcr100.dll file, follow the below methods to rectify the problem:
1. Issue with JAVA home path not correctly set:
Follow these steps:
/bin
directory.sqldeveloper.conf
in any editor to edit.SetJavaHome
"java.exe
on prompt.2. Issue with missing msvcr100.dll file:
OP stated the following in his comments below:
If I first install the jdk and then sql developer without Java, it tells me Unable to launch the Java Virtual Machine Located at path: C:/Program Files/Java/jdk1.8.0_45/bin/msvcr100.dll
So, the error message is clear:
Unable to launch the Java Virtual Machine Located at path:
C:/Program Files/Java/jdk1.8.0_45/bin/msvcr100.dll
Follow these steps:
copy:
MSVCR100.dll
from:
sqldeveloper\jdk\jre\bin
to:
sqldeveloper\sqldeveloper\bin
And relaunch SQL Developer again.
What is msvcr100.dll file?:
msvcr100.dll
is a part of Microsoft Visual C++ and is required to run programs developed with Visual C++. Some applications like SQL Developer in the question, needs the file in the SQL Developer installation folder.
What options are available to fix the issue?:
Copying it from Windows systemfolder to the installation folder of application should fix the problem. Also, you could add the PATH to the msvcr100.dll file based on 32/64 bit requirements. If the local file itself is deleted or corrupt by any chance, then it could be downloaded online or could also be reinstalled via Microsoft visual C++ 2010 Redistributable package. It is important to use the correct version based on the software. Use the 32bit dll file for 32bit software, and 64bit dll file for 64bit software.
The center of rectangle is the midpoint of the diagonal end points of rectangle.
Here the midpoint is ( (x1 + x2) / 2, (y1 + y2) / 2 )
.
That means:
xCenter = (x1 + x2) / 2
yCenter = (y1 + y2) / 2
Let me know your code.
Note: This is an answer useful for Python's ElementTree standard library without using hardcoded namespaces.
To extract namespace's prefixes and URI from XML data you can use ElementTree.iterparse
function, parsing only namespace start events (start-ns):
>>> from io import StringIO
>>> from xml.etree import ElementTree
>>> my_schema = u'''<rdf:RDF xml:base="http://dbpedia.org/ontology/"
... xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
... xmlns:owl="http://www.w3.org/2002/07/owl#"
... xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
... xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
... xmlns="http://dbpedia.org/ontology/">
...
... <owl:Class rdf:about="http://dbpedia.org/ontology/BasketballLeague">
... <rdfs:label xml:lang="en">basketball league</rdfs:label>
... <rdfs:comment xml:lang="en">
... a group of sports teams that compete against each other
... in Basketball
... </rdfs:comment>
... </owl:Class>
...
... </rdf:RDF>'''
>>> my_namespaces = dict([
... node for _, node in ElementTree.iterparse(
... StringIO(my_schema), events=['start-ns']
... )
... ])
>>> from pprint import pprint
>>> pprint(my_namespaces)
{'': 'http://dbpedia.org/ontology/',
'owl': 'http://www.w3.org/2002/07/owl#',
'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
'rdfs': 'http://www.w3.org/2000/01/rdf-schema#',
'xsd': 'http://www.w3.org/2001/XMLSchema#'}
Then the dictionary can be passed as argument to the search functions:
root.findall('owl:Class', my_namespaces)
Try this: (For Preview)
<script type="text/javascript">
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
</script>
<body>
<form id="form1" runat="server">
<input type="file" onchange="readURL(this);" />
<img id="blah" src="#" alt="your image" />
</form>
</body>
Working Demo here>
A call to your parent class's empty constructor super()
is done automatically when you don't do it yourself. That's the reason you've never had to do it in your code. It was done for you.
When your superclass doesn't have a no-arg constructor, the compiler will require you to call super
with the appropriate arguments. The compiler will make sure that you instantiate the class correctly. So this is not something you have to worry about too much.
Whether you call super()
in your constructor or not, it doesn't affect your ability to call the methods of your parent class.
As a side note, some say that it's generally best to make that call manually for reasons of clarity.
Do you have multiple mongodb nodes in a replica set?
I found (I am using via Robomongo gui mongo shell, I guess same applies in other cases) that the correct remove syntax, i.e.
db.test_users.remove({"_id": ObjectId("4d512b45cc9374271b02ec4f")})
...does not work unless you are connected to the primary node of the replica set.
Maybe we should help you with a big misunderstanding on your side first: PHP is (like ASP.NET or whatever you used to far) a server side language while javascript is client side.
This means that PHP will run on your webserver and create a HTML page dynamically which is then sent to the browser. Javascript in turn is embedded (either directly or as a referenced file) into this HTML page and runs in the browser.
Maybe you can now understand why your approach so far could never work out.
Another oneliner using basic command line functions handling multiple occurences per line.
cat * |sed s/string/\\\nstring\ /g |grep string |wc -l
data.rename(columns={'gdp':'log(gdp)'}, inplace=True)
The rename
show that it accepts a dict as a param for columns
so you just pass a dict with a single entry.
Also see related
Docker caches the entire filesystem state after each successful RUN
line.
Knowing that:
RUN
command, comment it out in the Dockerfile (as well as any and all subsequent RUN
commands), then run docker build
and docker run
again.RUN
command, simply add || true
to it to force it to succeed; then proceed like above (keep any and all subsequent RUN
commands commented out, run docker build
and docker run
)Tada, no need to mess with Docker internals or layer IDs, and as a bonus Docker automatically minimizes the amount of work that needs to be re-done.
Integer[] arrayInteger = {1,2,3,4,3,2,4,6,7,8,9,9,10};
Set set = new HashSet();
for(Integer i:arrayInteger)
set.add(i);
System.out.println(set);
<script type = “text/template”> … </script>
is obsolete. Use <template>
tag instead.
The tail
program can do this:
ls -lart | tail -n +2
The -n +2
means “start passing through on the second line of output”.
Check the charset encoding of the file. Make sure that it is in ASCII.
Use the od
command to see if there is a UTF-8 BOM at the beginning, for example.
None of the workarounds suggested here (chmod/chgrp/setfacl/windows perms) worked for me with msys64 on a Windows 7 corporate VM. In the end I worked around the problem by using an ssh agent with the key provided on stdin. Adding this to my .bash_profile
makes it the default for my login:
eval $(ssh-agent -s)
cat ~/.ssh/id_rsa | ssh-add -k -
Now I can do git push and pull with ssh remotes.
That's because in C - integer on 32 bit machine doesn't mean that 32 bits are used for storing it, it may be 16 bits as well. It depends on the machine (implementation-dependent).
In my case I had to add a .NET Authorization Rule for the web site in IIS.
I added a rule to allow anonymous users.
Thanks to Alex Mckay I had a resolve for dynamic setting a props:
for(let prop in filter)
(state.filter as Record<string, any>)[prop] = filter[prop];
background-image: url(/images/poster.png);
background-position: center;
background-position-y: 50px;
background-repeat: no-repeat;
64 bit version will allow a single process to use more RAM than 32 bit, however you may find that the memory footprint doubles depending on what you are storing in RAM (Integers in particular).
For example if your app requires > 2GB of RAM, so you switch from 32bit to 64bit you may find that your app is now requiring > 4GB of RAM.
Check whether all of your 3rd party modules are available in 64 bit, otherwise it may be easier to stick to 32bit in the meantime
Try this:
SELECT tab2.column_name
FROM [DB1.mdf].[dbo].[table_name_1] tab1 INNER JOIN [DB2.mdf].[dbo].[table_name_2] tab2
ON tab1.col_name = tab2.col_name
<input type="number" />
<input type="tel" />
Both of these present the numeric keypad when the input gains focus.
<input type="search" />
shows a normal keyboard with an extra search button
Everything else seems to bring up the standard keyboard.
Rather than Runtime.exec(String command)
, you need to use the exec(String command, String[] envp, File dir)
method signature:
Process p = Runtime.getRuntime().exec("cmd /c upsert.bat", null, new File("C:\\Program Files\\salesforce.com\\Data Loader\\cliq_process\\upsert"));
But personally, I'd use ProcessBuilder
instead, which is a little more verbose but much easier to use and debug than Runtime.exec()
.
ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "upsert.bat");
File dir = new File("C:/Program Files/salesforce.com/Data Loader/cliq_process/upsert");
pb.directory(dir);
Process p = pb.start();
Your error is posted in the official documentation. You can read this article.
I have copied the reason for you (and hyperlinked the URLs) from that article:
This will happen if the administrator has not created a PostgreSQL user account for you. (PostgreSQL user accounts are distinct from operating system user accounts.) If you are the administrator, see Chapter 20 for help creating accounts. You will need to become the operating system user under which PostgreSQL was installed (usually postgres) to create the first user account. It could also be that you were assigned a PostgreSQL user name that is different from your operating system user name; in that case you need to use the -U switch or set the PGUSER environment variable to specify your PostgreSQL user name
For your purposes, you can do:
1) Create a PostgreSQL user account:
sudo -u postgres createuser tom -d -P
(the -P
option to set a password; the -d
option for allowing the creation of database for your username 'tom'. Note that 'tom' is your operating system username. That way, you can execute PostgreSQL commands without sudo
ing.)
2) Now you should be able to execute createdb
and other PostgreSQL commands.
NOTICE
This answer is old (January 2014) many new debugging solutions are available since then.
I finally got it working! using weinre and cordova (no Phonegap build) and to save hassle for future devs, who may face the same problem, I made a YouTube tutorial ;)
I was a bit puzzled that norm.fit
apparently only worked with the expanded list of sampled values. I tried giving it two lists of numbers, or lists of tuples, but it only appeared to flatten everything and threat the input as individual samples. Since I already have a histogram based on millions of samples, I didn't want to expand this if I didn't have to. Thankfully, the normal distribution is trivial to calculate, so...
# histogram is [(val,count)]
from math import sqrt
def normfit(hist):
n,s,ss = univar(hist)
mu = s/n
var = ss/n-mu*mu
return (mu, sqrt(var))
def univar(hist):
n = 0
s = 0
ss = 0
for v,c in hist:
n += c
s += c*v
ss += c*v*v
return n, s, ss
I'm sure this must be provided by the libraries, but as I couldn't find it anywhere, I'm posting this here instead. Feel free to point to the correct way to do it and downvote me :-)
try
window.frameElement.ownerDocument.domain
if any(t < 0 for t in x):
# do something
Also, if you're going to use "True in ...", make it a generator expression so it doesn't take O(n) memory:
if True in (t < 0 for t in x):
you can use either the ADD command https://docs.docker.com/engine/reference/builder/#/add or the COPY command https://docs.docker.com/engine/reference/builder/#/copy
Here is the ng repeat with ng click function and to append with slider
<script>
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope) {
$scope.employees = [
{ 'id': '001', 'name': 'Alpha', 'joinDate': '05/17/2015', 'age': 37 },
{ 'id': '002', 'name': 'Bravo', 'joinDate': '03/25/2016', 'age': 27 },
{ 'id': '003', 'name': 'Charlie', 'joinDate': '09/11/2015', 'age': 29 },
{ 'id': '004', 'name': 'Delta', 'joinDate': '09/11/2015', 'age': 19 },
{ 'id': '005', 'name': 'Echo', 'joinDate': '03/09/2014', 'age': 32 }
]
//This will hide the DIV by default.
$scope.IsVisible = false;
$scope.ShowHide = function () {
//If DIV is visible it will be hidden and vice versa.
$scope.IsVisible = $scope.IsVisible ? false : true;
}
});
</script>
</head>
<body>
<div class="container" ng-app="MyApp" ng-controller="MyController">
<input type="checkbox" value="checkbox1" ng-click="ShowHide()" /> checkbox1
<div id="mixedSlider">
<div class="MS-content">
<div class="item" ng-repeat="emps in employees" ng-show = "IsVisible">
<div class="subitem">
<p>{{emps.id}}</p>
<p>{{emps.name}}</p>
<p>{{emps.age}}</p>
</div>
</div>
</div>
<div class="MS-controls">
<button class="MS-left"><i class="fa fa-angle-left" aria-hidden="true"></i></button>
<button class="MS-right"><i class="fa fa-angle-right" aria-hidden="true"></i></button>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="js/multislider.js"></script>
<script>
$('#mixedSlider').multislider({
duration: 750,
interval: false
});
</script>
First off it's important to understand that there are two kinds of "event listeners":
Scope event listeners registered via $on
:
$scope.$on('anEvent', function (event, data) {
...
});
Event handlers attached to elements via for example on
or bind
:
element.on('click', function (event) {
...
});
When $scope.$destroy()
is executed it will remove all listeners registered via $on
on that $scope.
It will not remove DOM elements or any attached event handlers of the second kind.
This means that calling $scope.$destroy()
manually from example within a directive's link function will not remove a handler attached via for example element.on
, nor the DOM element itself.
Note that remove
is a jqLite method (or a jQuery method if jQuery is loaded before AngularjS) and is not available on a standard DOM Element Object.
When element.remove()
is executed that element and all of its children will be removed from the DOM together will all event handlers attached via for example element.on
.
It will not destroy the $scope associated with the element.
To make it more confusing there is also a jQuery event called $destroy
. Sometimes when working with third-party jQuery libraries that remove elements, or if you remove them manually, you might need to perform clean up when that happens:
element.on('$destroy', function () {
scope.$destroy();
});
This depends on how the directive is "destroyed".
A normal case is that a directive is destroyed because ng-view
changes the current view. When this happens the ng-view
directive will destroy the associated $scope, sever all the references to its parent scope and call remove()
on the element.
This means that if that view contains a directive with this in its link function when it's destroyed by ng-view
:
scope.$on('anEvent', function () {
...
});
element.on('click', function () {
...
});
Both event listeners will be removed automatically.
However, it's important to note that the code inside these listeners can still cause memory leaks, for example if you have achieved the common JS memory leak pattern circular references
.
Even in this normal case of a directive getting destroyed due to a view changing there are things you might need to manually clean up.
For example if you have registered a listener on $rootScope
:
var unregisterFn = $rootScope.$on('anEvent', function () {});
scope.$on('$destroy', unregisterFn);
This is needed since $rootScope
is never destroyed during the lifetime of the application.
The same goes if you are using another pub/sub implementation that doesn't automatically perform the necessary cleanup when the $scope is destroyed, or if your directive passes callbacks to services.
Another situation would be to cancel $interval
/$timeout
:
var promise = $interval(function () {}, 1000);
scope.$on('$destroy', function () {
$interval.cancel(promise);
});
If your directive attaches event handlers to elements for example outside the current view, you need to manually clean those up as well:
var windowClick = function () {
...
};
angular.element(window).on('click', windowClick);
scope.$on('$destroy', function () {
angular.element(window).off('click', windowClick);
});
These were some examples of what to do when directives are "destroyed" by Angular, for example by ng-view
or ng-if
.
If you have custom directives that manage the lifecycle of DOM elements etc. it will of course get more complex.
In stead of replacing text branding, I divided into two rows like in the code below and gave img-responsive
class to the image......
<div class="collapse navbar-collapse navbar-ex1-collapse" style="background: #efefef; height:auto;">
<div class="container" style="margin-bottom:-1px;">
<div class="row">
<div class="col-md-3">
<div id="menubar-logo">
<a href="index.html"><img src="img/tl_logo.png" class="img-responsive" alt="Triple Luck IT Service Logo"></a>
</div>
</div>
<div class=" col-md-offset-3 col-md-6">
<ul class="nav navbar-nav">
<li><a href="index.php" class="active">Home</a></li>
<li><a href="about_us.php">About Us</a></li>
<li><a href="contact_us.php">Contact Us</a></li>
</ul>
</div>
</div>
<!-- end of "row" -->
</div>
<!-- end of "container" -->
</div>
<!-- end of "collapse" -->
and in addition,I added the following css codes.......
#menubar-logo img {
margin-top: 10px;
margin-bottom: 20px;
margin-right: 10px;
}
If my code solves your problem, it's my pleasure.....
This should do the trick for you: put include tag inside of a block section.
page1.html:
{% extends "base1.html" %}
{% block foo %}
{% include "commondata.html" %}
{% endblock %}
page2.html:
{% extends "base2.html" %}
{% block bar %}
{% include "commondata.html" %}
{% endblock %}
You've been shown PadLeft
and PadRight
. This will fill in the missing PadCenter
.
public static class StringUtils
{
public static string PadCenter(this string s, int width, char c)
{
if (s == null || width <= s.Length) return s;
int padding = width - s.Length;
return s.PadLeft(s.Length + padding / 2, c).PadRight(width, c);
}
}
Note to self: don't forget to update own CV: "One day, I even fixed Joel Coehoorn's code!" ;-D -Serge
Its a CORS issue, your api cannot be accessed directly from remote or different origin, In order to allow other ip address or other origins from accessing you api, you should add the 'Access-Control-Allow-Origin' on the api's header, you can set its value to '*' if you want it to be accessible to all, or you can set specific domain or ips like 'http://siteA.com' or 'http://192. ip address ';
Include this on your api's header, it may vary depending on how you are displaying json data,
if your using ajax, to retrieve and display data your header would look like this,
$.ajax({
url: '',
headers: { 'Access-Control-Allow-Origin': 'http://The web site allowed to access' },
data: data,
type: 'dataType',
/* etc */
success: function(jsondata){
}
})
I took klaus se's and aganders3's answer, and made a documented module that is more readable and holds in one file. You can just add it to your project. It even has an optional progress bar !
"""
The ``processes`` module provides some convenience functions
for using parallel processes in python.
Adapted from http://stackoverflow.com/a/16071616/287297
Example usage:
print prll_map(lambda i: i * 2, [1, 2, 3, 4, 6, 7, 8], 32, verbose=True)
Comments:
"It spawns a predefined amount of workers and only iterates through the input list
if there exists an idle worker. I also enabled the "daemon" mode for the workers so
that KeyboardInterupt works as expected."
Pitfalls: all the stdouts are sent back to the parent stdout, intertwined.
Alternatively, use this fork of multiprocessing:
https://github.com/uqfoundation/multiprocess
"""
# Modules #
import multiprocessing
from tqdm import tqdm
################################################################################
def apply_function(func_to_apply, queue_in, queue_out):
while not queue_in.empty():
num, obj = queue_in.get()
queue_out.put((num, func_to_apply(obj)))
################################################################################
def prll_map(func_to_apply, items, cpus=None, verbose=False):
# Number of processes to use #
if cpus is None: cpus = min(multiprocessing.cpu_count(), 32)
# Create queues #
q_in = multiprocessing.Queue()
q_out = multiprocessing.Queue()
# Process list #
new_proc = lambda t,a: multiprocessing.Process(target=t, args=a)
processes = [new_proc(apply_function, (func_to_apply, q_in, q_out)) for x in range(cpus)]
# Put all the items (objects) in the queue #
sent = [q_in.put((i, x)) for i, x in enumerate(items)]
# Start them all #
for proc in processes:
proc.daemon = True
proc.start()
# Display progress bar or not #
if verbose:
results = [q_out.get() for x in tqdm(range(len(sent)))]
else:
results = [q_out.get() for x in range(len(sent))]
# Wait for them to finish #
for proc in processes: proc.join()
# Return results #
return [x for i, x in sorted(results)]
################################################################################
def test():
def slow_square(x):
import time
time.sleep(2)
return x**2
objs = range(20)
squares = prll_map(slow_square, objs, 4, verbose=True)
print "Result: %s" % squares
EDIT: Added @alexander-mcfarlane suggestion and a test function
if your text doesn't spill over two rows then you can do line-height: ;
in your CSS, the more line-height you give, the lower on the container it will hold.
You can't follow the cursor with a DIV
, but you can draw a DIV
when moving the cursor!
$(document).on('mousemove', function(e){
$('#your_div_id').css({
left: e.pageX,
top: e.pageY
});
});
That div must be off the float, so position: absolute
should be set.
You need to code your html using absolute path for images. By Absolute path means you have to upload the images in a server and in the src
attribute of images you have to give the direct path like this <img src="http://yourdomain.com/images/example.jpg">
.
Below is the PHP code for your refference :- Its taken from http://www.php.net/manual/en/function.mail.php
<?php
// multiple recipients
$to = '[email protected]' . ', '; // note the comma
$to .= '[email protected]';
// subject
$subject = 'Birthday Reminders for August';
// message
$message = '
<p>Here are the birthdays upcoming in August!</p>
';
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";
// Additional headers
$headers .= 'To: Mary <[email protected]>, Kelly <[email protected]>' . "\r\n";
$headers .= 'From: Birthday Reminder <[email protected]>' . "\r\n";
// Mail it
mail($to, $subject, $message, $headers);
?>
There's a 'cheap and dirty' trick that I have used... shhhh don't tell anyone. If you output tab delimited text and make the file name *.xls then Excel opens it without objection, question or warning. So just crank the data out into a text file with tab delimitation and you can open it with Excel or Open Office.
Show file and track error
systemctl status nginx.service
Remember that a single =
is always an assignment in C or C++.
Your test should be if ( match == 0 && k == M )
you made a typo on the k == M
test.
If you really mean k=M
(i.e. a side-effecting assignment inside a test) you should for readability reasons code if (match == 0 && (k=m) != 0)
but most coding rules advise not writing that.
BTW, your mistake suggests to ask for all warnings (e.g. -Wall
option to g++
), and to upgrade to recent compilers. The next GCC 4.8 will give you:
% g++-trunk -Wall -c ederman.cc
ederman.cc: In function ‘void foo()’:
ederman.cc:9:30: error: lvalue required as left operand of assignment
if ( match == 0 && k = M )
^
and Clang 3.1 also tells you ederman.cc:9:30: error: expression is not assignable
So use recent versions of free compilers and enable all the warnings when using them.
Type this .... SET foreign_key_checks = 0;
delete your table then type SET foreign_key_checks = 1;
MySQL – Temporarily disable Foreign Key Checks or Constraints
Quite simple with the latest version of Visual Studio Code, if you have installed the official Python extension for Visual Studio Code:
Shift + Command + P
Type: Python: Select Interpreter
Choose your virtual environment.
To differentiate the routes, try adding a constraint that id must be numeric:
RouteTable.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
constraints: new { id = @"\d+" }, // Only matches if "id" is one or more digits.
defaults: new { id = System.Web.Http.RouteParameter.Optional }
);
Swift 4, Xcode 9.4.1
The solution that worked for me: I had a label within a collection view cell, and the label text was getting trimmed. Set the attributes as below on Storyboard
Lines = 0
LineBreak = Word Wrap
Set yourlabel's leading and trailing constraint = 0 (using Autolayout)
If you use io.js, it has support for multi-line strings as they are in ECMAScript 6.
var a =
`this is
a multi-line
string`;
See "New String Methods" at http://davidwalsh.name/es6-io for details and "template strings" at http://kangax.github.io/compat-table/es6/ for tracking compatibility.
Despite Daniel Böhmer's working solution, Ohad Schneider offered a better solution in a comment:
If the file is usually ignored, and you force adding it - it can be accidentally ignored again in the future (like when the file is deleted, then a commit is made and the file is re-created.
You should just un-ignore it in the .gitignore file like that: Unignore subdirectories of ignored directories in Git
You are most likely not using the correct credentials for the MySQL server. You also need to ensure the user you are connecting as has the correct privileges to view databases/tables, and that you can connect from your current location in network topographic terms (localhost).
Turn on grep
's line buffering mode when using BSD grep (FreeBSD, Mac OS X etc.)
tail -f file | grep --line-buffered my_pattern
It looks like a while ago --line-buffered
didn't matter for GNU grep (used on pretty much any Linux) as it flushed by default (YMMV for other Unix-likes such as SmartOS, AIX or QNX). However, as of November 2020, --line-buffered
is needed (at least with GNU grep 3.5 in openSUSE, but it seems generally needed based on comments below).
<span>
will allow you to style text, but it adds no semantic content.
As you're emphasizing some text, it sounds like you'd be better served by wrapping the text in <em></em>
and using CSS to change the color of the <em>
element. For example:
.description {
color: #fff;
}
.description em {
color: #ffa500;
}
<p class="description">Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Sed hendrerit mollis varius. Etiam ornare placerat
massa, <em>eget vulputate tellus fermentum.</em></p>
In fact, I'd go to great pains to avoid the <span>
element, as it's completely meaningless to everything that doesn't render your style sheet (bots, screen readers, luddites who disable styles, parsers, etc.) or renders it in unexpected ways (personal style sheets). In many ways, it's no better than using the <font>
element.
.description {_x000D_
color: #000;_x000D_
}_x000D_
_x000D_
.description em {_x000D_
color: #ffa500;_x000D_
}
_x000D_
<p class="description">Lorem ipsum dolor sit amet, consectetur _x000D_
adipiscing elit. Sed hendrerit mollis varius. Etiam ornare placerat _x000D_
massa, <em>eget vulputate tellus fermentum.</em></p>
_x000D_
No, they are not always.
It depends on whether you allow user input to be placed within the query itself. For example:
$dbh = new PDO("blahblah");
$tableToUse = $_GET['userTable'];
$stmt = $dbh->prepare('SELECT * FROM ' . $tableToUse . ' where username = :username');
$stmt->execute( array(':username' => $_REQUEST['username']) );
would be vulnerable to SQL injections and using prepared statements in this example won't work, because the user input is used as an identifier, not as data. The right answer here would be to use some sort of filtering/validation like:
$dbh = new PDO("blahblah");
$tableToUse = $_GET['userTable'];
$allowedTables = array('users','admins','moderators');
if (!in_array($tableToUse,$allowedTables))
$tableToUse = 'users';
$stmt = $dbh->prepare('SELECT * FROM ' . $tableToUse . ' where username = :username');
$stmt->execute( array(':username' => $_REQUEST['username']) );
Note: you can't use PDO to bind data that goes outside of DDL (Data Definition Language), i.e. this does not work:
$stmt = $dbh->prepare('SELECT * FROM foo ORDER BY :userSuppliedData');
The reason why the above does not work is because DESC
and ASC
are not data. PDO can only escape for data. Secondly, you can't even put '
quotes around it. The only way to allow user chosen sorting is to manually filter and check that it's either DESC
or ASC
.
When call add_subparsers
method save the first positional argument to dest=
and check value after argparse has been initialized, like this:
subparsers = parser.add_subparsers(dest='command')
And just check this this variable:
if not args.command:
parser.print_help()
parser.exit(1) # If exit() - exit code will be zero (no error)
Full example:
#!/usr/bin/env python
""" doc """
import argparse
import sys
parser = argparse.ArgumentParser(description=__doc__)
subparsers = parser.add_subparsers(dest='command',
help='List of commands')
list_parser = subparsers.add_parser('list',
help='List contents')
list_parser.add_argument('dir', action='store',
help='Directory to list')
create_parser = subparsers.add_parser('create',
help='Create a directory')
create_parser.add_argument('dirname', action='store',
help='New directory to create')
create_parser.add_argument('--read-only', default=False, action='store_true',
help='Set permissions to prevent writing to the directory')
args = parser.parse_args()
if not args.command:
parser.print_help()
parser.exit(1)
print(vars(args)) # For debug
(.//*[table-locator])[n]
where n
represents the specific line.
If you're using SQL Server 2005, you could use the FOR XML PATH command.
SELECT [VehicleID]
, [Name]
, (STUFF((SELECT CAST(', ' + [City] AS VARCHAR(MAX))
FROM [Location]
WHERE (VehicleID = Vehicle.VehicleID)
FOR XML PATH ('')), 1, 2, '')) AS Locations
FROM [Vehicle]
It's a lot easier than using a cursor, and seems to work fairly well.
Another approach to sort HTML table. (based on W3.JS HTML Sort)
/* Facility Name */_x000D_
$('#bioTable th:eq(0)').addClass("control-label pointer");_x000D_
/* Phone # */_x000D_
$('#bioTable th:eq(1)').addClass("not-allowed");_x000D_
/* City */_x000D_
$('#bioTable th:eq(2)').addClass("control-label pointer");_x000D_
/* Specialty */_x000D_
$('#bioTable th:eq(3)').addClass("not-allowed");_x000D_
_x000D_
_x000D_
var collection = [{_x000D_
"FacilityName": "MinION",_x000D_
"Phone": "999-8888",_x000D_
"City": "France",_x000D_
"Specialty": "Genetic Prediction"_x000D_
}, {_x000D_
"FacilityName": "GridION X5",_x000D_
"Phone": "999-8812",_x000D_
"City": "Singapore",_x000D_
"Specialty": "DNA Assembly"_x000D_
}, {_x000D_
"FacilityName": "PromethION",_x000D_
"Phone": "929-8888",_x000D_
"City": "San Francisco",_x000D_
"Specialty": "DNA Testing"_x000D_
}, {_x000D_
"FacilityName": "iSeq 100 System",_x000D_
"Phone": "999-8008",_x000D_
"City": "Christchurch",_x000D_
"Specialty": "gDNA-mRNA sequencing"_x000D_
}]_x000D_
_x000D_
$tbody = $("#bioTable").append('<tbody></tbody>');_x000D_
_x000D_
for (var i = 0; i < collection.length; i++) {_x000D_
$tbody = $tbody.append('<tr class="item"><td>' + collection[i]["FacilityName"] + '</td><td>' + collection[i]["Phone"] + '</td><td>' + collection[i]["City"] + '</td><td>' + collection[i]["Specialty"] + '</td></tr>');_x000D_
}
_x000D_
.control-label:after {_x000D_
content: "*";_x000D_
color: red;_x000D_
}_x000D_
_x000D_
.pointer {_x000D_
cursor: pointer;_x000D_
}_x000D_
_x000D_
.not-allowed {_x000D_
cursor: not-allowed;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://www.w3schools.com/lib/w3.js"></script>_x000D_
<link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet" />_x000D_
<p>Click the <strong>table headers</strong> to sort the table accordingly:</p>_x000D_
_x000D_
<table id="bioTable" class="w3-table-all">_x000D_
<thead>_x000D_
<tr>_x000D_
<th onclick="w3.sortHTML('#bioTable', '.item', 'td:nth-child(1)')">Facility Name</th>_x000D_
<th>Phone #</th>_x000D_
<th onclick="w3.sortHTML('#bioTable', '.item', 'td:nth-child(3)')">City</th>_x000D_
<th>Specialty</th>_x000D_
</tr>_x000D_
</thead>_x000D_
</table>
_x000D_
<h4>Order List</h4>
<ul>
<li ng-repeat="val in filter_option.order">
<span>
<input title="{{filter_option.order_name[$index]}}" type="radio" ng-model="filter_param.order_option" ng-value="'{{val}}'" />
{{filter_option.order_name[$index]}}
</span>
<select title="" ng-model="filter_param[val]">
<option value="asc">Asc</option>
<option value="desc">Desc</option>
</select>
</li>
</ul>
for inserting data into table you can write
insert into tablename values(column_name1,column_name2,column_name3);
but write the column_name
in the sequence as per sequence in table ...
I was getting this problem from my Dockerfile as I had:
RUN bash < <(curl -s -S -L https://raw.githubusercontent.com/moovweb/gvm/master/binscripts/gvm-installer)
However, according to this issue, it was solved:
The exec form makes it possible to avoid shell string munging, and to
RUN
commands using a base image that does not contain/bin/sh
.Note
To use a different shell, other than
/bin/sh
, use the exec form passing in the desired shell. For example,RUN ["/bin/bash", "-c", "echo hello"]
RUN ["/bin/bash", "-c", "bash < <(curl -s -S -L https://raw.githubusercontent.com/moovweb/gvm/master/binscripts/gvm-installer)"]
Notice the quotes around each parameter.
If you're wondering about functionality, then jQuery's .html()
performs the same intended functionality as .innerHTML
, but it also performs checks for cross-browser compatibility.
For this reason, you can always use jQuery's .html()
instead of .innerHTML
where possible.
Use:
a:visited {
text-decoration: none;
}
But it will only affect links that haven't been clicked on yet.
Some safer alternatives to eval()
and sympy.sympify().evalf()
*:
*SymPy sympify
is also unsafe according to the following warning from the documentation.
Warning: Note that this function uses
eval
, and thus shouldn’t be used on unsanitized input.
By default Windows defines the following prefix that is available to everyone: http://+:80/Temporary_Listen_Addresses/
So you can register your HttpListener
via:
Prefixes.Add("http://+:80/Temporary_Listen_Addresses/" + Guid.NewGuid().ToString("D") + "/";
This sometimes causes problems with software such as Skype which will try to utilise port 80 by default.
and, for completeness and with regards to this question asking about changing string columns only, there's mutate_if
:
data <- cbind(stringVar = sample(c("foo","bar"),10,replace=TRUE),
data.frame(matrix(sample(1:40), 10, 10, dimnames = list(1:10, LETTERS[1:10]))),stringsAsFactors=FALSE)
factoredData = data %>% mutate_if(is.character,funs(factor(.)))
Add your <script>
to the bottom of your <body>
, or add an event listener for DOMContentLoaded
following this StackOverflow question.
If that script executes in the <head>
section of the code, document.getElementsByClassName(...)
will return an empty array because the DOM is not loaded yet.
You're getting the Type Error
because you're referencing search_span[0]
, but search_span[0]
is undefined
.
This works when you execute it in Dev Tools because the DOM is already loaded.
It's just a syntax error. You just have to replace j+3
by j=j+3
or j+=3
.
I know this is a very old question, but I recently experienced the "cannot copy from obj to bin" error in VS 2012. Every single time I tried to rebuild a certain project, I got the message. The only solution was to do a clean before every rebuild.
After much investigating, it turns out I had an incomplete pragma warning statement in one of my files that did not prevent the compilation from succeeding, but was somehow confusing VS into keeping the file(s) locked.
In my case, I had the following at the top of the file:
#pragma warning(
That's it. I guess I was attempting to do something a while back and got distracted and never finished the process, but the VS warnings about that particular line were lost in the shuffle. Eventually I noticed the warning, removed the line, and rebuild works every time since then.
I've hacked up the following idiom:
echo "Generating from IDL..."
idlj -fclient -td java/src echo.idl
if [ $? -ne 0 ]; then { echo "Failed, aborting." ; exit 1; } fi
echo "Compiling classes..."
javac *java
if [ $? -ne 0 ]; then { echo "Failed, aborting." ; exit 1; } fi
echo "Done."
Precede each command with an informative echo, and follow each command with that same
if [ $? -ne 0 ];...
line. (Of course, you can edit that error message if you want to.)
You can call setBounds
on the "compound" drawables to modify the size of the image.
Try this code to autosize the drawable of your button:
DroidUtils.scaleButtonDrawables((Button) findViewById(R.id.ButtonTest), 1.0);
defined by this function:
public final class DroidUtils {
/** scale the Drawables of a button to "fit"
* For left and right drawables: height is scaled
* eg. with fitFactor 1 the image has max. the height of the button.
* For top and bottom drawables: width is scaled:
* With fitFactor 0.9 the image has max. 90% of the width of the button
* */
public static void scaleButtonDrawables(Button btn, double fitFactor) {
Drawable[] drawables = btn.getCompoundDrawables();
for (int i = 0; i < drawables.length; i++) {
if (drawables[i] != null) {
int imgWidth = drawables[i].getIntrinsicWidth();
int imgHeight = drawables[i].getIntrinsicHeight();
if ((imgHeight > 0) && (imgWidth > 0)) { //might be -1
float scale;
if ((i == 0) || (i == 2)) { //left or right -> scale height
scale = (float) (btn.getHeight() * fitFactor) / imgHeight;
} else { //top or bottom -> scale width
scale = (float) (btn.getWidth() * fitFactor) / imgWidth;
}
if (scale < 1.0) {
Rect rect = drawables[i].getBounds();
int newWidth = (int)(imgWidth * scale);
int newHeight = (int)(imgHeight * scale);
rect.left = rect.left + (int)(0.5 * (imgWidth - newWidth));
rect.top = rect.top + (int)(0.5 * (imgHeight - newHeight));
rect.right = rect.left + newWidth;
rect.bottom = rect.top + newHeight;
drawables[i].setBounds(rect);
}
}
}
}
}
}
Be aware, that this may not be called in onCreate()
of an activity, because button height and width are not (yet) available there. Call this in on onWindowFocusChanged()
or use this solution to call the function.
Edited:
The first incarnation of this function did not work correctly. It used userSeven7s code to scale the image, but returning ScaleDrawable.getDrawable()
does not seem to work (neither does returning ScaleDrawable
) for me.
The modified code uses setBounds
to provide the bounds for the image. Android fits the image into these bounds.
Moment.js can convert unix timestamps into any custom format
In this case : var time = moment(1382086394000).format("DD-MM-YYYY h:mm:ss");
will print 18-10-2013 11:53:14
;
Here's a plunker that demonstrates this.
This is a very simple adaptation of the modifyList function by Sarkar. Because it is recursive, it will handle more complex situations than mapply
would, and it will handle mismatched name situations by ignoring the items in 'second' that are not in 'first'.
appendList <- function (x, val)
{
stopifnot(is.list(x), is.list(val))
xnames <- names(x)
for (v in names(val)) {
x[[v]] <- if (v %in% xnames && is.list(x[[v]]) && is.list(val[[v]]))
appendList(x[[v]], val[[v]])
else c(x[[v]], val[[v]])
}
x
}
> appendList(first,second)
$a
[1] 1 2
$b
[1] 2 3
$c
[1] 3 4
on delete button click event
public void delete(View v){
ListView listview1;
ArrayList<E> datalist;
final int position = listview1.getPositionForView((View) v.getParent());
datalist.remove(position);
myAdapter.notifyDataSetChanged();
}
Here is the answer for those of you looking like I did all over the web trying to find out how to do this task. Uploading a photo to a server with the file name stored in a mysql database and other form data you want in your Database. Please let me know if it helped.
Firstly the form you need:
<form method="post" action="addMember.php" enctype="multipart/form-data">
<p>
Please Enter the Band Members Name.
</p>
<p>
Band Member or Affiliates Name:
</p>
<input type="text" name="nameMember"/>
<p>
Please Enter the Band Members Position. Example:Drums.
</p>
<p>
Band Position:
</p>
<input type="text" name="bandMember"/>
<p>
Please Upload a Photo of the Member in gif or jpeg format. The file name should be named after the Members name. If the same file name is uploaded twice it will be overwritten! Maxium size of File is 35kb.
</p>
<p>
Photo:
</p>
<input type="hidden" name="size" value="350000">
<input type="file" name="photo">
<p>
Please Enter any other information about the band member here.
</p>
<p>
Other Member Information:
</p>
<textarea rows="10" cols="35" name="aboutMember">
</textarea>
<p>
Please Enter any other Bands the Member has been in.
</p>
<p>
Other Bands:
</p>
<input type="text" name="otherBands" size=30 />
<br/>
<br/>
<input TYPE="submit" name="upload" title="Add data to the Database" value="Add Member"/>
</form>
Then this code processes you data from the form:
<?php
// This is the directory where images will be saved
$target = "your directory";
$target = $target . basename( $_FILES['photo']['name']);
// This gets all the other information from the form
$name=$_POST['nameMember'];
$bandMember=$_POST['bandMember'];
$pic=($_FILES['photo']['name']);
$about=$_POST['aboutMember'];
$bands=$_POST['otherBands'];
// Connects to your Database
mysqli_connect("yourhost", "username", "password") or die(mysqli_error()) ;
mysqli_select_db("dbName") or die(mysqli_error()) ;
// Writes the information to the database
mysqli_query("INSERT INTO tableName (nameMember,bandMember,photo,aboutMember,otherBands)
VALUES ('$name', '$bandMember', '$pic', '$about', '$bands')") ;
// Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
// Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}
else {
// Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
Code edited from www.about.com
Chances are that, if all the answers above didn't work for you, and you are using a request validation, you forgot to put the authorization to true.
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class EquipmentRequest extends FormRequest {
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize() {
/*******************************************************/
return true; /************ THIS VALUE NEEDS TO BE TRUE */
/*******************************************************/
}
/* ... */
}
I use a function to echo and run the command:
#!/bin/bash
# Function to display commands
exe() { echo "\$ $@" ; "$@" ; }
exe echo hello world
Which outputs
$ echo hello world
hello world
For more complicated commands pipes, etc., you can use eval:
#!/bin/bash
# Function to display commands
exe() { echo "\$ ${@/eval/}" ; "$@" ; }
exe eval "echo 'Hello, World!' | cut -d ' ' -f1"
Which outputs
$ echo 'Hello, World!' | cut -d ' ' -f1
Hello
You only need this link jspdf.min.js
It has everything in it.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js"></script>
Actually it depends on your use case.
1) You want to protect your route from unauthorized users
If that is the case you can use the component called <Redirect />
and can implement the following logic:
import React from 'react'
import { Redirect } from 'react-router-dom'
const ProtectedComponent = () => {
if (authFails)
return <Redirect to='/login' />
}
return <div> My Protected Component </div>
}
Keep in mind that if you want <Redirect />
to work the way you expect, you should place it inside of your component's render method so that it should eventually be considered as a DOM element, otherwise it won't work.
2) You want to redirect after a certain action (let's say after creating an item)
In that case you can use history:
myFunction() {
addSomeStuff(data).then(() => {
this.props.history.push('/path')
}).catch((error) => {
console.log(error)
})
or
myFunction() {
addSomeStuff()
this.props.history.push('/path')
}
In order to have access to history, you can wrap your component with an HOC called withRouter
. When you wrap your component with it, it passes match
location
and history
props. For more detail please have a look at the official documentation for withRouter.
If your component is a child of a <Route />
component, i.e. if it is something like <Route path='/path' component={myComponent} />
, you don't have to wrap your component with withRouter
, because <Route />
passes match
, location
, and history
to its child.
3) Redirect after clicking some element
There are two options here. You can use history.push()
by passing it to an onClick
event:
<div onClick={this.props.history.push('/path')}> some stuff </div>
or you can use a <Link />
component:
<Link to='/path' > some stuff </Link>
I think the rule of thumb with this case is to try to use <Link />
first, I suppose especially because of performance.
You can use the index of the array element to remove it from the array, the next time you use the $list
variable, you will see that the array is changed.
Try something like this
foreach($list as $itemIndex => &$item) {
if($item['status'] === false) {
unset($list[$itemIndex]);
}
}
Instead of nohup
, you should use screen
. It achieves the same result - your commands are running "detached". However, you can resume screen sessions and get back into their "hidden" terminal and see recent progress inside that terminal.
screen
has a lot of options. Most often I use these:
To start first screen session or to take over of most recent detached one:
screen -Rd
To detach from current session: Ctrl+ACtrl+D
You can also start multiple screens - read the docs.
FFMpeg can do this by seeking to the given timestamp and extracting exactly one frame as an image, see for instance:
ffmpeg -i input_file.mp4 -ss 01:23:45 -vframes 1 output.jpg
Let's explain the options:
-i input file the path to the input file
-ss 01:23:45 seek the position to the specified timestamp
-vframes 1 only handle one video frame
output.jpg output filename, should have a well-known extension
The -ss
parameter accepts a value in the form HH:MM:SS[.xxx]
or as a number in seconds. If you need a percentage, you need to compute the video duration beforehand.
You'll need to learn how to use sed http://unixhelp.ed.ac.uk/CGI/man-cgi?sed
And also to use for so you can loop through your file entries http://www.cyberciti.biz/faq/bash-for-loop/
Your command will look something like this, I don't have a term beside me so I can't check
for i in `dir` do mv $i `echo $i | sed '/orig/new/g'`
You probably need to use reflection to get the types of them to check. To get the type of the List: Get generic type of java.util.List
Mac (French-Canadian Keyboard):
Line Comment hold both: Cmd + É
Block Comment hold all three: Cmd + Alt + É
"É" is on the same position as "?/" in english one.
For Multiple Instance of the same activity , use the following snippet,
Note : This snippet, I am using outside of my Activity
. Make sure your AndroidManifest
file doesn't contain android:launchMode="singleTop|singleInstance"
. if needed, you can change it to android:launchMode="standard"
.
Intent i = new Intent().setClass(mActivity.getApplication(), TestUserProfileScreenActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
// Launch the new activity and add the additional flags to the intent
mActivity.getApplication().startActivity(i);
This works fine for me. Hope, this saves times for someone. If anybody finds a better way, please share with us.
You should always consider what the browser will see by the end. In this case, it will see this:
<img src='something' onmouseover='change(' ex1')' />
In other words, the "onmouseover" attribute is just change(
, and there's another "attribute" called ex1')'
with no value.
The truth is, HTML does not use \
for an escape character. But it does recognise "
and '
as escaped quote and apostrophe, respectively.
Armed with this knowledge, use this:
document.getElementById("something").innerHTML = "<img src='something' onmouseover='change("ex1")' />";
... That being said, you could just use JavaScript quotes:
document.getElementById("something").innerHTML = "<img src='something' onmouseover='change(\"ex1\")' />";
A few compilers (usually the ones for microcontrollers) has a special feature implemented within recognizing literal binary numbers by prefix "0b..." preceding the number, although most compilers (C/C++ standards) don't have such feature and if it is the case, here it is my alternative solution:
#define B_0000 0
#define B_0001 1
#define B_0010 2
#define B_0011 3
#define B_0100 4
#define B_0101 5
#define B_0110 6
#define B_0111 7
#define B_1000 8
#define B_1001 9
#define B_1010 a
#define B_1011 b
#define B_1100 c
#define B_1101 d
#define B_1110 e
#define B_1111 f
#define _B2H(bits) B_##bits
#define B2H(bits) _B2H(bits)
#define _HEX(n) 0x##n
#define HEX(n) _HEX(n)
#define _CCAT(a,b) a##b
#define CCAT(a,b) _CCAT(a,b)
#define BYTE(a,b) HEX( CCAT(B2H(a),B2H(b)) )
#define WORD(a,b,c,d) HEX( CCAT(CCAT(B2H(a),B2H(b)),CCAT(B2H(c),B2H(d))) )
#define DWORD(a,b,c,d,e,f,g,h) HEX( CCAT(CCAT(CCAT(B2H(a),B2H(b)),CCAT(B2H(c),B2H(d))),CCAT(CCAT(B2H(e),B2H(f)),CCAT(B2H(g),B2H(h)))) )
// Using example
char b = BYTE(0100,0001); // Equivalent to b = 65; or b = 'A'; or b = 0x41;
unsigned int w = WORD(1101,1111,0100,0011); // Equivalent to w = 57155; or w = 0xdf43;
unsigned long int dw = DWORD(1101,1111,0100,0011,1111,1101,0010,1000); //Equivalent to dw = 3745774888; or dw = 0xdf43fd28;
Disadvantages (it's not such a big ones):
Advantages:
spending processor time
in pointless operations (like "?.. :..", "<<", "+"
) to the executable program (it may be performed hundred of times in the final application);"mainly in C"
compilers and C++ as well (template+enum solution works only in C++ compilers
);"enum solution" (usually 255 = reach enum definition limit)
, differently, "literal constant" limitations, in the compiler allows greater numbers;several header files
(in most cases not easily readable and understandable, and make the project become unnecessarily confused and extended, like that using "BOOST_BINARY()"
);Unfortunately, Dictionary has problems with Model Binding in MVC. Read the full story here. Instead, create a custom model binder to get the Dictionary as a parameter for the controller action.
To solve your requirement, here is the working solution -
First create your ViewModels in following way. PersonModel can have list of RoleModels.
public class PersonModel
{
public List<RoleModel> Roles { get; set; }
public string Name { get; set; }
}
public class RoleModel
{
public string RoleName { get; set;}
public string Description { get; set;}
}
Then have a index action which will be serving basic index view -
public ActionResult Index()
{
return View();
}
Index view will be having following JQuery AJAX POST operation -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$(function () {
$('#click1').click(function (e) {
var jsonObject = {
"Name" : "Rami",
"Roles": [{ "RoleName": "Admin", "Description" : "Admin Role"}, { "RoleName": "User", "Description" : "User Role"}]
};
$.ajax({
url: "@Url.Action("AddUser")",
type: "POST",
data: JSON.stringify(jsonObject),
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (response) {
alert(response.responseText);
},
success: function (response) {
alert(response);
}
});
});
});
</script>
<input type="button" value="click1" id="click1" />
Index action posts to AddUser action -
[HttpPost]
public ActionResult AddUser(PersonModel model)
{
if (model != null)
{
return Json("Success");
}
else
{
return Json("An Error Has occoured");
}
}
So now when the post happens you can get all the posted data in the model parameter of action.
Update:
For asp.net core, to get JSON data as your action parameter you should add the [FromBody]
attribute before your param name in your controller action. Note: if you're using ASP.NET Core 2.1, you can also use the [ApiController]
attribute to automatically infer the [FromBody] binding source for your complex action method parameters. (Doc)
There's always a lowercase "v". But seriously, aside from Unicode, all I can find would be &darr
, which looks like ↓.
Maybe it is time to start revising this answer? Personally I would vote for setActive()
and unsetActive()
(alternatives can be setUnActive()
, notActive()
, disable()
, etc. depending on context) since "setActive" implies you activate it at all times, which you don't. It's kind of counter intuitive to say "setActive" but actually remove the active state.
Another problem is, you can can not listen to specifically a SetActive event in a CQRS way, you would need to listen to a 'setActiveEvent' and determine inside that listener wether is was actually set active or not. Or of course determine which event to call when calling setActive()
but that then goes against the Separation of Concerns principle.
A good read on this is the FlagArgument article by Martin Fowler: http://martinfowler.com/bliki/FlagArgument.html
However, I come from a PHP background and see this trend being adopted more and more. Not sure how much this lives with Java development.
I saying that the case statement is wrong but this can be a good solution instead.
If you choose to use the CASE
statement, you have to make sure that at least one of the CASE
condition is matched. Otherwise, you need to define an error handler to catch the error. Recall that you don’t have to do this with the IF
statement.
SELECT if(hide = 0,FALSE,TRUE) col FROM tbl; #for BOOLEAN Value return
or
SELECT if(hide = 0,'FALSE','TRUE') col FROM tbl; #for string Value return
You should be able to declare a cursor to be a bind variable (called parameters in other DBMS')
like Vincent wrote, you can do something like this:
begin
open :yourCursor
for 'SELECT "'|| :someField ||'" from yourTable where x = :y'
using :someFilterValue;
end;
You'd have to bind 3 vars to that script. An input string for "someField", a value for "someFilterValue" and an cursor for "yourCursor" which has to be declared as output var.
Unfortunately, I have no idea how you'd do that from C++. (One could say fortunately for me, though. ;-) )
Depending on which access library you use, it might be a royal pain or straight forward.
As for how to represent a single apostrophe as a string in Python, you can simply surround it with double quotes ("'"
) or you can escape it inside single quotes ('\''
).
To remove apostrophes from a string, a simple approach is to just replace the apostrophe character with an empty string:
>>> "didn't".replace("'", "")
'didnt'
There is a simple solution.
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"> </script>
<script type="text/javascript" src="../js/jquery.min.js"></script>
<script type="text/javascript" src="../js/flexcroll.js"></script>
<script type="text/javascript" src="../js/jquery-ui-1.8.18.custom.min.js"></script>
<script type="text/javascript" src="../js/JScript.js"></script>
<title>calendar</title>
<script type="text/javascript">
$(function(){$('.dateTxt').datepicker(); });
</script>
</head>
<body>
<p>Date 1: <input id="one" class="dateTxt" type="text" ></p>
<p>Date 2: <input id="two" class="dateTxt" type="text" ></p>
<p>Date 3: <input id="three" class="dateTxt" type="text" ></p>
</body>
</html>
Improving on Ocelot20's answer, if you have a table you're left outer joining with where you just want 0 or 1 rows out of it, but it could have multiple, you need to Order your joined table:
var qry = Foos.GroupJoin(
Bars.OrderByDescending(b => b.Id),
foo => foo.Foo_Id,
bar => bar.Foo_Id,
(f, bs) => new { Foo = f, Bar = bs.FirstOrDefault() });
Otherwise which row you get in the join is going to be random (or more specifically, whichever the db happens to find first).
This error is shown when your XCode is old and the related device you are using is updated to latest version. First of all, install the latest Xcode version.
We can solve this issue by following the below steps:-
If everything worked properly, your XCode has a new developer disk image. Close the finder now, and quit your XCode. Open your Xcode and the error will be gone. Now you can connect your latest device to old Xcode versions.
Thanks
Try this first:
git checkout master
(If you're on a different branch than master
, use the branch name there instead.)
If that doesn't work, try...
For a single file:
git checkout HEAD /path/to/file
For the entire repository working copy:
git reset --hard HEAD
And if that doesn't work, then you can look in the reflog to find your old head SHA and reset to that:
git reflog
git reset --hard <sha from reflog>
HEAD
is a name that always points to the latest commit in your current branch.
Implemented in JavaScript (ES6):
/**
* Calculate x and y in circle's circumference
* @param {Object} input - The input parameters
* @param {number} input.radius - The circle's radius
* @param {number} input.angle - The angle in degrees
* @param {number} input.cx - The circle's origin x
* @param {number} input.cy - The circle's origin y
* @returns {Array[number,number]} The calculated x and y
*/
function pointsOnCircle({ radius, angle, cx, cy }){
angle = angle * ( Math.PI / 180 ); // Convert from Degrees to Radians
const x = cx + radius * Math.sin(angle);
const y = cy + radius * Math.cos(angle);
return [ x, y ];
}
Usage:
const [ x, y ] = pointsOnCircle({ radius: 100, angle: 180, cx: 150, cy: 150 });
console.log( x, y );
/**
* Calculate x and y in circle's circumference
* @param {Object} input - The input parameters
* @param {number} input.radius - The circle's radius
* @param {number} input.angle - The angle in degrees
* @param {number} input.cx - The circle's origin x
* @param {number} input.cy - The circle's origin y
* @returns {Array[number,number]} The calculated x and y
*/
function pointsOnCircle({ radius, angle, cx, cy }){
angle = angle * ( Math.PI / 180 ); // Convert from Degrees to Radians
const x = cx + radius * Math.sin(angle);
const y = cy + radius * Math.cos(angle);
return [ x, y ];
}
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
function draw( x, y ){
ctx.clearRect( 0, 0, canvas.width, canvas.height );
ctx.beginPath();
ctx.strokeStyle = "orange";
ctx.arc( 100, 100, 80, 0, 2 * Math.PI);
ctx.lineWidth = 3;
ctx.stroke();
ctx.closePath();
ctx.beginPath();
ctx.fillStyle = "indigo";
ctx.arc( x, y, 6, 0, 2 * Math.PI);
ctx.fill();
ctx.closePath();
}
let angle = 0; // In degrees
setInterval(function(){
const [ x, y ] = pointsOnCircle({ radius: 80, angle: angle++, cx: 100, cy: 100 });
console.log( x, y );
draw( x, y );
document.querySelector("#degrees").innerHTML = angle + "°";
document.querySelector("#points").textContent = x.toFixed() + "," + y.toFixed();
}, 100 );
_x000D_
<p>Degrees: <span id="degrees">0</span></p>
<p>Points on Circle (x,y): <span id="points">0,0</span></p>
<canvas width="200" height="200" style="border: 1px solid"></canvas>
_x000D_
Google Drive folders can be embedded and displayed in list
and grid
views:
<iframe src="https://drive.google.com/embeddedfolderview?id=FOLDER-ID#list" style="width:100%; height:600px; border:0;"></iframe>
<iframe src="https://drive.google.com/embeddedfolderview?id=FOLDER-ID#grid" style="width:100%; height:600px; border:0;"></iframe>
Q: What is a folder ID (FOLDER-ID) and how can I get it?
A: Go to Google Drive >> open the folder >> look at its URL in the address bar of your browser. For example:
Folder URL: https://drive.google.com/drive/folders/0B1iqp0kGPjWsNDg5NWFlZjEtN2IwZC00NmZiLWE3MjktYTE2ZjZjNTZiMDY2
Folder ID:
0B1iqp0kGPjWsNDg5NWFlZjEtN2IwZC00NmZiLWE3MjktYTE2ZjZjNTZiMDY2
This technique works best for folders with public access. Folders that are shared only with certain Google accounts will cause trouble when you embed them this way. At the time of this edit, a message "You need permission" appears, with some buttons to help you "Request access" or "Switch accounts" (or possibly sign-in to a Google account). The Javascript in these buttons doesn't work properly inside an IFRAME
in Chrome.
Read more at https://productforums.google.com/forum/#!msg/drive/GpVgCobPL2Y/_Xt7sMc1WzoJ
I just tested a couple paths using Excel 2013 on on Windows 7. I found the overall pathname limit to be 213 and the basename length to be 186. At least the error dialog for exceeding basename length is clear:
And trying to move a not-too-long basename to a too-long-pathname is also very clear:
The pathname error is deceptive, though. Quite unhelpful:
This is a lazy Microsoft restriction. There's no good reason for these arbitrary length limits, but in the end, it’s a real bug in the error dialog.
YES, PUT, DELETE, HEAD etc HTTP methods are available in all modern browsers.
To be compliant with XMLHttpRequest Level 2 browsers must support these methods. To check which browsers support XMLHttpRequest Level 2 I recommend CanIUse:
Only Opera Mini is lacking support atm (juli '15), but Opera Mini lacks support for everything. :)
Just call getArguments()
in your Frag2
's onCreateView()
method:
public class Frag2 extends Fragment {
public View onCreateView(LayoutInflater inflater,
ViewGroup containerObject,
Bundle savedInstanceState){
//here is your arguments
Bundle bundle=getArguments();
//here is your list array
String[] myStrings=bundle.getStringArray("elist");
}
}
Generally the practice would be to pass data as a DateTime with a "timezone" of UTC and then pass a TimeZoneInfo object and when you are ready to display the data, you use the TimeZoneInfo object to convert the UTC DateTime.
The other option is to set the DateTime with the current timezone, and then make sure the "timezone" is unknown for the DateTime object, then make sure the DateTime is again passed with a TimeZoneInfo that indicates the TimeZone of the DateTime passed.
As others have indicated here, it would be nice if Microsoft got on top of this and created one nice object to do it all, but for now you have to deal with two objects.
Python's csv module handles data row-wise, which is the usual way of looking at such data. You seem to want a column-wise approach. Here's one way of doing it.
Assuming your file is named myclone.csv
and contains
workers,constant,age
w0,7.334,-1.406
w1,5.235,-4.936
w2,3.2225,-1.478
w3,0,0
this code should give you an idea or two:
>>> import csv
>>> f = open('myclone.csv', 'rb')
>>> reader = csv.reader(f)
>>> headers = next(reader, None)
>>> headers
['workers', 'constant', 'age']
>>> column = {}
>>> for h in headers:
... column[h] = []
...
>>> column
{'workers': [], 'constant': [], 'age': []}
>>> for row in reader:
... for h, v in zip(headers, row):
... column[h].append(v)
...
>>> column
{'workers': ['w0', 'w1', 'w2', 'w3'], 'constant': ['7.334', '5.235', '3.2225', '0'], 'age': ['-1.406', '-4.936', '-1.478', '0']}
>>> column['workers']
['w0', 'w1', 'w2', 'w3']
>>> column['constant']
['7.334', '5.235', '3.2225', '0']
>>> column['age']
['-1.406', '-4.936', '-1.478', '0']
>>>
To get your numeric values into floats, add this
converters = [str.strip] + [float] * (len(headers) - 1)
up front, and do this
for h, v, conv in zip(headers, row, converters):
column[h].append(conv(v))
for each row instead of the similar two lines above.
If you are using Scene Builder, you will see at the right an accordion panel which normally has got three options ("Properties", "Layout" and "Code"). In the second one ("Layout"), you will see an option called "[parent layout] Constraints" (in your case "AnchorPane Constrainsts").
You should put "0" in the four sides of the element wich represents the parent layout.
You can also not specify the type parameter which seems a bit cleaner and what Spring intended when looking at the docs:
@RequestMapping(method = RequestMethod.HEAD, value = Constants.KEY )
public ResponseEntity taxonomyPackageExists( @PathVariable final String key ){
// ...
return new ResponseEntity(HttpStatus.NO_CONTENT);
}
Is there an issue using the Date.toString().indexOf('Daylight Time') > -1
"" + new Date()
Sat Jan 01 100050 00:00:00 GMT-0500 (Eastern Standard Time)
"" + new Date(...)
Sun May 01 100033 00:00:00 GMT-0400 (Eastern Daylight Time)
This seems compatible with all browsers.
You can try this also to replace existing object
toDoTaskList = [
{id:'abcd', name:'test'},
{id:'abcdc', name:'test'},
{id:'abcdtr', name:'test'}
];
newRecordToUpdate = {id:'abcdc', name:'xyz'};
this.toDoTaskList.map((todo, i) => {
if (todo.id == newRecordToUpdate .id){
this.toDoTaskList[i] = updatedVal;
}
});
In Xcode > 4.3:
You click on the scheme drop down bar -> edit scheme -> arguments tab and then add NSZombieEnabled in the Environment Variables column and YES in the value column.
Good Luck !!!
replace this
printf("%c",word[i]);
by
printf("%02X",word[i]);
A very simple work-around for this issue is to create a Streamable<T>
interface extending Iterable<T>
that holds a default <T> stream()
method.
interface Streamable<T> extends Iterable<T> {
default Stream<T> stream() {
return StreamSupport.stream(spliterator(), false);
}
}
Now any of your Iterable<T>
s can be trivially made streamable just by declaring them implements Streamable<T>
instead of Iterable<T>
.
File Permissions
File size
.Sometimes an inaccessible or corrupted file would be the problem, as was in my case
I found dfsq's answer its comments extremely useful. I made some minor modifications applicable to me (and I'm posting it here, in case it is of some use to others).
class
as hooks, instead of table elements tr
class
while showing/hiding parent$rows
text elements into an array only once (and avoiding $rows.length
times computation)var $rows = $('.wrapper');
var rowsTextArray = [];
var i = 0;
$.each($rows, function () {
rowsTextArray[i] = ($(this).find('.number').text() + $(this).find('.fruit').text())
.replace(/\s+/g, '')
.toLowerCase();
i++;
});
$('#search').keyup(function() {
var val = $.trim($(this).val()).replace(/\s+/g, '').toLowerCase();
$rows.show().filter(function(index) {
return (rowsTextArray[index].indexOf(val) === -1);
}).hide();
});
_x000D_
span {
margin-right: 0.2em;
}
_x000D_
<input type="text" id="search" placeholder="type to search" />
<div class="wrapper"><span class="number">one</span><span class="fruit">apple</span></div>
<div class="wrapper"><span class="number">two</span><span class="fruit">banana</span></div>
<div class="wrapper"><span class="number">three</span><span class="fruit">cherry</span></div>
<div class="wrapper"><span class="number">four</span><span class="fruit">date</span></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
This seems to be answered - #include <fstream>
.
The message means :-
incomplete type
- the class has not been defined with a full class. The compiler has seen statements such as class ifstream;
which allow it to understand that a class exists, but does not know how much memory the class takes up.
The forward declaration allows the compiler to make more sense of :-
void BindInput( ifstream & inputChannel );
It understands the class exists, and can send pointers and references through code without being able to create the class, see any data within the class, or call any methods of the class.
The has initializer
seems a bit extraneous, but is saying that the incomplete object is being created.
or use the AdjustToUniversal DateTimeStyle in a call to
DateTime.ParseExact(String, String[], IFormatProvider, DateTimeStyles)
In .NET Core, I managed to get a System.Net.Http.HttpClient
with UseDefaultCredentials = true
to pass through the authenticated user's Windows credentials to a back end service by using WindowsIdentity.RunImpersonated
.
HttpClient client = new HttpClient(new HttpClientHandler { UseDefaultCredentials = true } );
HttpResponseMessage response = null;
if (identity is WindowsIdentity windowsIdentity)
{
await WindowsIdentity.RunImpersonated(windowsIdentity.AccessToken, async () =>
{
var request = new HttpRequestMessage(HttpMethod.Get, url)
response = await client.SendAsync(request);
});
}
var span_Text = document.getElementById("span_Id").innerText;_x000D_
_x000D_
console.log(span_Text)
_x000D_
<span id="span_Id">I am the Text </span>
_x000D_