User
.Add a property to the Response class 'user' with the type of the new class for the user values User
.
public class Response {
public string id { get; set; }
public string text { get; set; }
public string url { get; set; }
public string width { get; set; }
public string height { get; set; }
public string size { get; set; }
public string type { get; set; }
public string timestamp { get; set; }
public User user { get; set; }
}
public class User {
public int id { get; set; }
public string screen_name { get; set; }
}
In general you should make sure the property types of the json and your CLR classes match up. It seems that the structure that you're trying to deserialize contains multiple number values (most likely int
). I'm not sure if the JavaScriptSerializer
is able to deserialize numbers into string fields automatically, but you should try to match your CLR type as close to the actual data as possible anyway.
I'd use RestSharp - https://github.com/restsharp/RestSharp
Create class to deserialize to:
public class MyObject {
public string Id { get; set; }
public string Text { get; set; }
...
}
And the code to get that object:
RestClient client = new RestClient("http://whatever.com");
RestRequest request = new RestRequest("path/to/object");
request.AddParameter("id", "123");
// The above code will make a request URL of
// "http://whatever.com/path/to/object?id=123"
// You can pick and choose what you need
var response = client.Execute<MyObject>(request);
MyObject obj = response.Data;
Check out http://restsharp.org/ to get started.
To avoid any ambiguity, use the utilities methods from SwingUtilities :
SwingUtilities.isLeftMouseButton(MouseEvent anEvent)
SwingUtilities.isRightMouseButton(MouseEvent anEvent)
SwingUtilities.isMiddleMouseButton(MouseEvent anEvent)
You need to pass in a sequence, but you forgot the comma to make your parameters a tuple:
cursor.execute('INSERT INTO images VALUES(?)', (img,))
Without the comma, (img)
is just a grouped expression, not a tuple, and thus the img
string is treated as the input sequence. If that string is 74 characters long, then Python sees that as 74 separate bind values, each one character long.
>>> len(img)
74
>>> len((img,))
1
If you find it easier to read, you can also use a list literal:
cursor.execute('INSERT INTO images VALUES(?)', [img])
If you have PHP 5.5 or later, the best way is to use the built in function array_column()
:
$idCats = array_column($cats, 'id');
But the son has to be an array or converted to an array
try this using hooks:
const [dynamicClasses, setDynamicClasses] = React.useState([
"dynamicClass1", "dynamicClass2"
]);
and add this in className attribute :
<div className=`wrapper searchDiv ${[...dynamicClasses]}`>
...
</div>
to add class :
const addClass = newClass => {
setDynamicClasses([...dynamicClasses, newClass])
}
to delete class :
const deleteClass= classToDelete => {
setDynamicClasses(dynamicClasses.filter(class = > {
class !== classToDelete
}));
}
Many good answers here already, although you also need to keep in mind that if you are doing long-running processing on the UI thread (generally a bad idea), then you won't see the marquee moving either.
I think you may be getting tripped up on the sheet protection. I streamlined your code a little and am explicitly setting references to the workbook and worksheet objects. In your example, you explicitly refer to the workbook and sheet when you're setting the TxtRng object, but not when you unprotect the sheet.
Try this:
Sub varchanger()
Dim wb As Workbook
Dim ws As Worksheet
Dim TxtRng As Range
Set wb = ActiveWorkbook
Set ws = wb.Sheets("Sheet1")
'or ws.Unprotect Password:="yourpass"
ws.Unprotect
Set TxtRng = ws.Range("A1")
TxtRng.Value = "SubTotal"
'http://stackoverflow.com/questions/8253776/worksheet-protection-set-using-ws-protect-but-doesnt-unprotect-using-the-menu
' or ws.Protect Password:="yourpass"
ws.Protect
End Sub
If I run the sub with ws.Unprotect
commented out, I get a run-time error 1004. (Assuming I've protected the sheet and have the range locked.) Uncommenting the line allows the code to run fine.
NOTES:
Cells(1, 1)
notation can cause a huge amount of grief. Be careful using it. Range("A1")
is a lot easier for humans to parse and tends to prevent forehead-slapping mistakes.I was wondering why I was getting that big warning message on Ubuntu 16.04 (which comes with Git 2.7.4), but not on Arch Linux. The reason is that the warning was removed in Git 2.8 (March 2016):
Across the transition at around Git version 2.0, the user used to get a pretty loud warning when running "git push" without setting push.default configuration variable. We no longer warn because the transition was completed a long time ago.
So you won't see the warning if you have Git 2.8 and later and don't need to set push.default
unless you want to change the default 'simple'
behavior.
You need to access a geocoding service (i.e. from Google), there is no simple formula to transfer addresses to geo coordinates.
EDITED TO ADD: The following code is outdated and won't work in PHP 7. See the note towards the bottom of the answer for more details.
Assuming a table structure of an integer ID and a blob DATA column, and assuming MySQL functions are being used to interface with the database, you could probably do something like this:
$result = mysql_query 'INSERT INTO table (
data
) VALUES (
\'' . mysql_real_escape_string (file_get_contents ('/path/to/the/file/to/store.pdf')) . '\'
);';
A word of warning though, storing blobs in databases is generally not considered to be the best idea as it can cause table bloat and has a number of other problems associated with it. A better approach would be to move the file somewhere in the filesystem where it can be retrieved, and store the path to the file in the database instead of the file itself.
Also, using mysql_* function calls is discouraged as those methods are effectively deprecated and aren't really built with versions of MySQL newer than 4.x in mind. You should switch to mysqli or PDO instead.
UPDATE: mysql_* functions are deprecated in PHP 5.x and are REMOVED COMPLETELY IN PHP 7! You now have no choice but to switch to a more modern Database Abstraction (MySQLI, PDO). I've decided to leave the original answer above intact for historical reasons but don't actually use it
Here's how to do it with mysqli in procedural mode:
$result = mysqli_query ($db, 'INSERT INTO table (
data
) VALUES (
\'' . mysqli_real_escape_string (file_get_contents ('/path/to/the/file/to/store.pdf'), $db) . '\'
);');
The ideal way of doing it is with MySQLI/PDO prepared statements.
You have a potential race condition in your code--what happens if the user has permissions to write to the folder when you check, but before the user actually writes to the folder this permission is withdrawn? The write will throw an exception which you will need to catch and handle. So the initial check is pointless. You might as well just do the write and handle any exceptions. This is the standard pattern for your situation.
A Popen
object has a .wait()
method exactly defined for this: to wait for the completion of a given subprocess (and, besides, for retuning its exit status).
If you use this method, you'll prevent that the process zombies are lying around for too long.
(Alternatively, you can use subprocess.call()
or subprocess.check_call()
for calling and waiting. If you don't need IO with the process, that might be enough. But probably this is not an option, because your if the two subprocesses seem to be supposed to run in parallel, which they won't with (check_
)call()
.)
If you have several subprocesses to wait for, you can do
exit_codes = [p.wait() for p in p1, p2]
which returns as soon as all subprocesses have finished. You then have a list of return codes which you maybe can evaluate.
Only way that work for me was with an Iterator.
Iterator iterator= query.list().iterator();
Destination dest;
ArrayList<Destination> destinations= new ArrayList<>();
Iterator iterator= query.list().iterator();
while(iterator.hasNext()){
Object[] tuple= (Object[]) iterator.next();
dest= new Destination();
dest.setId((String)tuple[0]);
dest.setName((String)tuple[1]);
dest.setLat((String)tuple[2]);
dest.setLng((String)tuple[3]);
destinations.add(dest);
}
With other methods that I found, I had cast problems
(for those who are looking for php-curl answer)
$service_url = 'https://example.com/something/something.json';
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "username:password"); //Your credentials goes here
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //IMP if the url has https and you don't want to verify source certificate
$curl_response = curl_exec($curl);
$response = json_decode($curl_response);
curl_close($curl);
var_dump($response);
Here's how I check if the current network is using cellular or not on the latest Android versions:
val isCellular: Boolean get() {
val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
cm.getNetworkCapabilities(cm.activeNetwork).hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
} else {
cm.activeNetworkInfo?.type == ConnectivityManager.TYPE_MOBILE
}
}
LENGTH()
does return the string length (just verified). I suppose that your data is padded with blanks - try
SELECT typ, LENGTH(TRIM(t1.typ))
FROM AUTA_VIEW t1;
instead.
As OraNob
mentioned, another cause could be that CHAR
is used in which case LENGTH()
would also return the column width, not the string length. However, the TRIM()
approach also works in this case.
Your first CSS selector—social.h2
—is looking for the "social" element in the "h2", class, e.g.:
<social class="h2">
Class selectors are proceeded with a dot (.
). Also, use a space () to indicate that one element is inside of another. To find an
<h2>
descendant of an element in the social
class, try something like:
.social h2 {
color: pink;
font-size: 14px;
}
To get a better understanding of CSS selectors and how they are used to reference your HTML, I suggest going through the interactive HTML and CSS tutorials from CodeAcademy. I hope that this helps point you in the right direction.
This is very much implementation specific, but the general idea is to allow providers to issue short term access tokens with long term refresh tokens. Why?
You can also turn on WCF logging for more information about the original error. This helped me solve this problem.
Add the following to your web.config, it saves the log to C:\log\Traces.svclog
<system.diagnostics>
<sources>
<source name="System.ServiceModel"
switchValue="Information, ActivityTracing"
propagateActivity="true">
<listeners>
<add name="traceListener"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData= "c:\log\Traces.svclog" />
</listeners>
</source>
</sources>
</system.diagnostics>
Create a fake update to enforce the rowlock.
UPDATE <tablename> (ROWLOCK) SET <somecolumn> = <somecolumn> WHERE id=1
If that's not locking your row, god knows what will.
After this "UPDATE
" you can do your SELECT (ROWLOCK)
and subsequent updates.
Say your model is 'Shop'
class Shop(models.Model):
street = models.CharField(max_length=150)
city = models.CharField(max_length=150)
# some of your models may have explicit ordering
class Meta:
ordering = ('city')
Since you may have the Meta
class ordering
attribute set, you can use order_by()
without parameters to clear any ordering when using distinct()
. See the documentation under order_by
()
If you don’t want any ordering to be applied to a query, not even the default ordering, call order_by() with no parameters.
and distinct()
in the note where it discusses issues with using distinct()
with ordering.
To query your DB, you just have to call:
models.Shop.objects.order_by().values('city').distinct()
It returns a dictionnary
or
models.Shop.objects.order_by().values_list('city').distinct()
This one returns a ValuesListQuerySet
which you can cast to a list
.
You can also add flat=True
to values_list
to flatten the results.
See also: Get distinct values of Queryset by field
According to the LanguageManual, you can use unix_timestamp()
to get the "current time stamp using the default time zone." If you need to convert that to something more human-readable, you can use from_unixtime(unix_timestamp())
.
Hope that helps.
The recommended way in Python 3.5 and above is to use subprocess.run()
:
from subprocess import run
output = run("pwd", capture_output=True).stdout
I had a similar problem and solved it this way.
My working directory is a general script folder and serveral particular script folder in same root, i need to call particular script folder (which call general script with the parameter of the particular problem). So working directory is like this
\Nico\Scripts\Script1.ps1
\Script2.ps1
\Problem1\Solution1.ps1
\ParameterForSolution1.config
\Problem2\Solution2.ps1
\ParameterForSolution2.config
Solutions1 and Solutions2 call the PS1 in Scripts folder loading the parameter stored in ParameterForSolution. So in powershell ISE i run this command
.\Nico\Problem1\Solution1.PS1
And the code inside Solution1.PS1 is:
# This is the path where my script is running
$path = split-path -parent $MyInvocation.MyCommand.Definition
# Change to root dir
cd "$path\..\.."
$script = ".\Script\Script1.PS1"
$parametro = "Problem1\ParameterForSolution1.config"
# Another set of parameter Script1.PS1 can receive for debuggin porpuose
$parametro +=' -verbose'
Invoke-Expression "$script $parametro"
To people using Codeigniter (i'm on C3):
The index.php file overwrite php.ini configuration, so on index.php file, line 68:
case 'development':
error_reporting(-1);
ini_set('display_errors', 1);
break;
You can change this option to set what you need. Here's the complete list:
1 E_ERROR
2 E_WARNING
4 E_PARSE
8 E_NOTICE
16 E_CORE_ERROR
32 E_CORE_WARNING
64 E_COMPILE_ERROR
128 E_COMPILE_WARNING
256 E_USER_ERROR
512 E_USER_WARNING
1024 E_USER_NOTICE
6143 E_ALL
2048 E_STRICT
4096 E_RECOVERABLE_ERROR
Hope it helps.
After researching for almost 1 month i found the below code which is working very beautifully and 100% perfectly on my website. To check the preview how it is working you can check from the link. https://www.jobsedit.in/state-government-jobs/
CSS CODE-----
@media only screen and (max-width: 500px) {
.resp table {
display: block ;
}
.resp th {
position: absolute;
top: -9999px;
left: -9999px;
display:block ;
}
.resp tr {
border: 1px solid #ccc;
display:block;
}
.resp td {
/* Behave like a "row" */
border: none;
border-bottom: 1px solid #eee;
position: relative;
width:100%;
background-color:White;
text-indent: 50%;
text-align:left;
padding-left: 0px;
display:block;
}
.resp td:nth-child(1) {
border: none;
border-bottom: 1px solid #eee;
position: relative;
font-size:20px;
text-indent: 0%;
text-align:center;
}
.resp td:before {
/* Now like a table header */
position: absolute;
/* Top/left values mimic padding */
top: 6px;
left: 6px;
width: 45%;
text-indent: 0%;
text-align:left;
white-space: nowrap;
background-color:White;
font-weight:bold;
}
/*
Label the data
*/
.resp td:nth-of-type(2):before { content: attr(data-th) }
.resp td:nth-of-type(3):before { content: attr(data-th) }
.resp td:nth-of-type(4):before { content: attr(data-th) }
.resp td:nth-of-type(5):before { content: attr(data-th) }
.resp td:nth-of-type(6):before { content: attr(data-th) }
.resp td:nth-of-type(7):before { content: attr(data-th) }
.resp td:nth-of-type(8):before { content: attr(data-th) }
.resp td:nth-of-type(9):before { content: attr(data-th) }
.resp td:nth-of-type(10):before { content: attr(data-th) }
}
HTML CODE --
<table>
<tr>
<td data-th="Heading 1"></td>
<td data-th="Heading 2"></td>
<td data-th="Heading 3"></td>
<td data-th="Heading 4"></td>
<td data-th="Heading 5"></td>
</tr>
</table>
This is no longer an active API for google, you can try Xignite, although they charge: http://www.xignite.com
Another option is:
for i in *001.jpg
do
echo "mv $i yourstring${i#*001.jpg}"
done
remove echo
after you have it right.
Parameter substitution with #
will keep only the last part, so you can change its name.
Basically: If you're doing a transaction just do a rollback. Otherwise, you can't "undo" a MySQL query.
This was my stupidity, but a stupidity that was not easy to identify :).
Problem:
If you are deploying manually into your server, ensure your JAVA_HOME, JDK_HOME points to the correct JDK which you used to compile the project and build the war.
If you do not like to change JAVA_HOME, JDK_HOME, you can always change the JAVA_HOME and JDK_HOME in catalina.bat(for tomcat server) and that'll enable your life to be easy!
I guess that this code should answer your question:
use strict;
use warnings;
my @keys = qw/one two three two/;
my %hash;
for my $key (@keys)
{
$hash{$key}++;
}
for my $key (keys %hash)
{
print "$key: ", $hash{$key}, "\n";
}
Output:
three: 1
one: 1
two: 2
The iteration can be simplified to:
$hash{$_}++ for (@keys);
(See $_
in perlvar.) And you can even write something like this:
$hash{$_}++ or print "Found new value: $_.\n" for (@keys);
Which reports each key the first time it’s found.
You need to have favicon.ico
in the same folder or dictionary as your script because python only searches in the current dictionary or you could put in the full pathname. For example, this works:
from tkinter import *
root = Tk()
root.iconbitmap(r'c:\Python32\DLLs\py.ico')
root.mainloop()
But this blows up with your same error:
from tkinter import *
root = Tk()
root.iconbitmap('py.ico')
root.mainloop()
You can't inject content from another site (domain) using AJAX. The reason an iFrame is suited for these kinds of things is that you can specify the source to be from another domain.
brilliant example Jonathan Leffler, to make your code work on SLES, I needed to add an additional header to allow the pid_t object :)
#include <sys/types.h>
In Java8:
LongSummaryStatistics movingAverage = new LongSummaryStatistics();
movingAverage.accept(new data);
...
average = movingAverage.getAverage();
you have also IntSummaryStatistics
, DoubleSummaryStatistics
...
This is Just because you have made changes on your remote repository which was not pulled on your local repository.
To resolve simply 1. Pull from remote repository to local repository. It will not undo any changes locally. It will just update local repository. 2. Now push the changes to remote repository. It will work
See this. Your code would be something like the following:
from django.db.models import Max
# Generates a "SELECT MAX..." query
Argument.objects.aggregate(Max('rating')) # {'rating__max': 5}
You can also use this on existing querysets:
from django.db.models import Max
args = Argument.objects.filter(name='foo') # or whatever arbitrary queryset
args.aggregate(Max('rating')) # {'rating__max': 5}
If you need the model instance that contains this max value, then the code you posted is probably the best way to do it:
arg = args.order_by('-rating')[0]
Note that this will error if the queryset is empty, i.e. if no arguments match the query (because the [0]
part will raise an IndexError
). If you want to avoid that behavior and instead simply return None
in that case, use .first()
:
arg = args.order_by('-rating').first() # may return None
I don't know how to delete all at once, but you can use ipcs
to list resources, and then use loop and delete with ipcrm
. This should work, but it needs a little work. I remember that I made it work once in class.
Shortest working options:
// if you need to do something with the user
if ($user = User::whereEmail(Input::get('email'))->first()) {
// ...
}
// otherwise
$userExists = User::whereEmail(Input::get('email'))->exists();
How do you express binary literals in Python?
They're not "binary" literals, but rather, "integer literals". You can express integer literals with a binary format with a 0
followed by a B
or b
followed by a series of zeros and ones, for example:
>>> 0b0010101010
170
>>> 0B010101
21
From the Python 3 docs, these are the ways of providing integer literals in Python:
Integer literals are described by the following lexical definitions:
integer ::= decinteger | bininteger | octinteger | hexinteger decinteger ::= nonzerodigit (["_"] digit)* | "0"+ (["_"] "0")* bininteger ::= "0" ("b" | "B") (["_"] bindigit)+ octinteger ::= "0" ("o" | "O") (["_"] octdigit)+ hexinteger ::= "0" ("x" | "X") (["_"] hexdigit)+ nonzerodigit ::= "1"..."9" digit ::= "0"..."9" bindigit ::= "0" | "1" octdigit ::= "0"..."7" hexdigit ::= digit | "a"..."f" | "A"..."F"
There is no limit for the length of integer literals apart from what can be stored in available memory.
Note that leading zeros in a non-zero decimal number are not allowed. This is for disambiguation with C-style octal literals, which Python used before version 3.0.
Some examples of integer literals:
7 2147483647 0o177 0b100110111 3 79228162514264337593543950336 0o377 0xdeadbeef 100_000_000_000 0b_1110_0101
Changed in version 3.6: Underscores are now allowed for grouping purposes in literals.
You can have the zeros and ones in a string object which can be manipulated (although you should probably just do bitwise operations on the integer in most cases) - just pass int the string of zeros and ones and the base you are converting from (2):
>>> int('010101', 2)
21
You can optionally have the 0b
or 0B
prefix:
>>> int('0b0010101010', 2)
170
If you pass it 0
as the base, it will assume base 10 if the string doesn't specify with a prefix:
>>> int('10101', 0)
10101
>>> int('0b10101', 0)
21
You can pass an integer to bin to see the string representation of a binary literal:
>>> bin(21)
'0b10101'
And you can combine bin
and int
to go back and forth:
>>> bin(int('010101', 2))
'0b10101'
You can use a format specification as well, if you want to have minimum width with preceding zeros:
>>> format(int('010101', 2), '{fill}{width}b'.format(width=10, fill=0))
'0000010101'
>>> format(int('010101', 2), '010b')
'0000010101'
in IntelliJ, I get this error when trying to add the lib folder from the main project folder to an artifact.
Placing and using the lib folder in the src folder works.
For me, I managed to make it work that way. I deployed the automatic click in 5000 milliseconds and then closed the loop after 1000 milliseconds. Then there was only 1 automatic click.
<script> var myVar = setInterval(function ({document.getElementById("test").click();}, 500)); setInterval(function () {clearInterval(myVar)}, 1000));</script>
do you work with a 3d tool such as maya? for maya you can look at http://www.inka3d.com
I'm coming from a SQL Server background also and spent the past 2 weeks figuring out how to run scripts like this in IBM Data Studio. Hope it helps.
CREATE VARIABLE v_lookupid INTEGER DEFAULT (4815162342); --where 4815162342 is your variable data
SELECT * FROM DB1.PERSON WHERE PERSON_ID = v_lookupid;
SELECT * FROM DB1.PERSON_DATA WHERE PERSON_ID = v_lookupid;
SELECT * FROM DB1.PERSON_HIST WHERE PERSON_ID = v_lookupid;
DROP VARIABLE v_lookupid;
In Swift you would do it like this:
label.lineBreakMode = NSLineBreakMode.ByWordWrapping
label.numberOfLines = 0
(Note that the way the lineBreakMode constant works is different to in ObjC)
When running the command: cordova plugin remove <PLUGIN NAME>
, ensure that you do not add the version number to the plugin name. Just plain plugin name, for example:
cordova plugin remove cordova.plugin_name
and not:
cordova plugin remove cordova.plugin_name 0.01
or
cordova plugin remove "cordova.plugin_name 0.01"
In case there is a privilege issue, run with sudo if you are on a *nix system, for example:
sudo cordova plugin remove cordova.plugin_name
Then you may add --save to remove it from the config.xml file. For example:
cordova plugin remove cordova.plugin_name --save
import jquery within <script> tag in your vue file.
I think this is the easiest way.
For example,
<script>
import $ from "jquery";
export default {
name: 'welcome',
mounted: function() {
window.setTimeout(function() {
$('.logo').css('opacity', 0);
}, 1000);
}
}
</script>
A way to do this would be to set the color of the element to black, and then fade to the color of the background like this:
<style>
p {
animation-name: example;
animation-duration: 2s;
}
@keyframes example {
from {color:black;}
to {color:white;}
}
</style>
<p>I am FADING!</p>
I hope this is what you needed!
You can Simply extend user profile by creating a new entry each time when a user is created by using Django post save signals
from django.db.models.signals import *
from __future__ import unicode_literals
class UserProfile(models.Model):
user_name = models.OneToOneField(User, related_name='profile')
city = models.CharField(max_length=100, null=True)
def __unicode__(self): # __str__
return unicode(self.user_name)
def create_user_profile(sender, instance, created, **kwargs):
if created:
userProfile.objects.create(user_name=instance)
post_save.connect(create_user_profile, sender=User)
This will automatically create an employee instance when a new user is created.
If you wish to extend user model and want to add further information while creating a user you can use django-betterforms (http://django-betterforms.readthedocs.io/en/latest/multiform.html). This will create a user add form with all fields defined in the UserProfile model.
from django.db.models.signals import *
from __future__ import unicode_literals
class UserProfile(models.Model):
user_name = models.OneToOneField(User)
city = models.CharField(max_length=100)
def __unicode__(self): # __str__
return unicode(self.user_name)
from django import forms
from django.forms import ModelForm
from betterforms.multiform import MultiModelForm
from django.contrib.auth.forms import UserCreationForm
from .models import *
class ProfileForm(ModelForm):
class Meta:
model = Employee
exclude = ('user_name',)
class addUserMultiForm(MultiModelForm):
form_classes = {
'user':UserCreationForm,
'profile':ProfileForm,
}
from django.shortcuts import redirect
from .models import *
from .forms import *
from django.views.generic import CreateView
class AddUser(CreateView):
form_class = AddUserMultiForm
template_name = "add-user.html"
success_url = '/your-url-after-user-created'
def form_valid(self, form):
user = form['user'].save()
profile = form['profile'].save(commit=False)
profile.user_name = User.objects.get(username= user.username)
profile.save()
return redirect(self.success_url)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="." method="post">
{% csrf_token %}
{{ form }}
<button type="submit">Add</button>
</form>
</body>
</html>
from django.conf.urls import url, include
from appName.views import *
urlpatterns = [
url(r'^add-user/$', AddUser.as_view(), name='add-user'),
]
In Bootstrap 4 the correct answer is to use the text-xs-right
class.
This works because xs
denotes the smallest viewport size in BS. If you wanted to, you could apply the alignment only when the viewport is medium or larger by using text-md-right
.
In the latest alpha, text-xs-right
has been simplified to text-right
.
<div class="row">
<div class="col-md-6">Total cost</div>
<div class="col-md-6 text-right">$42</div>
</div>
The solution proposed by Jens is correct. However, it turns out that if you initialize your ModelForm with an instance (example below) django will not populate the data:
def your_view(request):
if request.method == 'POST':
form = UserDetailsForm(request.POST)
if form.is_valid():
# some code here
else:
form = UserDetailsForm(instance=request.user)
So, I made my own ModelForm base class that populates the initial data:
from django import forms
class BaseModelForm(forms.ModelForm):
"""
Subclass of `forms.ModelForm` that makes sure the initial values
are present in the form data, so you don't have to send all old values
for the form to actually validate.
"""
def merge_from_initial(self):
filt = lambda v: v not in self.data.keys()
for field in filter(filt, getattr(self.Meta, 'fields', ())):
self.data[field] = self.initial.get(field, None)
Then, the simple view example looks like this:
def your_view(request): if request.method == 'POST':
form = UserDetailsForm(request.POST)
if form.is_valid():
# some code here
else:
form = UserDetailsForm(instance=request.user)
form.merge_from_initial()
Fix doesn't work.
Exactly as in the example illustration, all these steps only provide access to "system" databases, and no option to select existing user databases that you want to access.
The solution to access a local (not Express Edition) Microsoft SQL server instance resides on the SQL Server side:
Done! Now you can select your local SQL Server from the Server Name list in Connection Properties.
If installed via apt-get
in Ubuntu 12.04, don't forget to chown -R mongodb:nogroup /path/to/new/directory
. Also, change the configuration at /etc/mongodb.conf
.
As a reminder, the mongodb-10gen
package is now started via upstart, so the config script is in /etc/init/mongodb.conf
I just went through this, hope googlers find it useful :)
Had issues using the code in the answer provided by @haynar above (wouldn't play on Chrome), and it seems that one of the more modern ways to ensure it plays is to use the video tag
Example:
<video controls="controls" width="800" height="600"
name="Video Name" src="http://www.myserver.com/myvideo.mov"></video>
This worked like a champ for my .mov file (generated from Keynote) in both Safari and Chrome, and is listed as supported in most modern browsers (The video tag is supported in Internet Explorer 9+, Firefox, Opera, Chrome, and Safari.)
Note: Will work in IE / etc.. if you use MP4 (Mov is not officially supported by those guys)
you need to configure this in web.xml as well.Please refer below code.
<taglib>
<taglib-uri>http://java.sun.com/jsp/jstl/core</taglib-uri>
<taglib-location>/WEB-INF/lib/c.tld</taglib-location>
</taglib>
Please let me know if you still face any issue.
function converToLocalTime(serverDate) {
var dt = new Date(Date.parse(serverDate));
var localDate = dt;
var gmt = localDate;
var min = gmt.getTime() / 1000 / 60; // convert gmt date to minutes
var localNow = new Date().getTimezoneOffset(); // get the timezone
// offset in minutes
var localTime = min - localNow; // get the local time
var dateStr = new Date(localTime * 1000 * 60);
// dateStr = dateStr.toISOString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); // this will return as just the server date format i.e., yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
dateStr = dateStr.toString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
return dateStr;
}
import sys
sys.path.append("path/to/Modules")
print sys.path
This won't persist over reboots or get translated to other files. It is however great if you don't want to make a permanent modification to your system.
The Differences in as easy as much possible: After having a basic understanding, the other comments posted above will be easier to catch.
Shell - "Shell" is a program, which facilitates the interaction between the user and the operating system (kernel). There are many shell implementation available, like sh, bash, csh, zsh...etc.
Using any of the Shell programs, we will be able to execute commands that are supported by that shell program.
Bash - It derived from Bourne-again Shell. Using this program, we will be able to execute all the commands specified by Shell. Also, we will be able to execute some commands that are specifically added to this program. Bash has backward compatibility with sh.
Sh - It derived from Bourne Shell. "sh" supports all the commands specified in the shell. Means, Using this program, we will be able to execute all the commands specified by Shell.
For more information, do: - https://man.cx/sh - https://man.cx/bash
>>> a = [0] * 10
>>> a
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
A solution that is viable for both Linux and Windows is to just get used to using console ffmpeg in your code. I stack up threads, write a simple thread controller class, then you can easily make use of what ever functionality of ffmpeg you want to use.
As an example, this contains sections use ffmpeg to create a thumbnail from a time that I specify.
In the thread controller you have something like
List<ThrdFfmpeg> threads = new List<ThrdFfmpeg>();
Which is the list of threads that you are running, I make use of a timer to Pole these threads, you can also set up an event if Pole'ing is not suitable for your application. In this case thw class Thrdffmpeg contains,
public class ThrdFfmpeg
{
public FfmpegStuff ffm { get; set; }
public Thread thrd { get; set; }
}
FFmpegStuff contains the various ffmpeg functionality, thrd is obviously the thread.
A property in FfmpegStuff is the class FilesToProcess, which is used to pass information to the called process, and receive information once the thread has stopped.
public class FileToProcess
{
public int videoID { get; set; }
public string fname { get; set; }
public int durationSeconds { get; set; }
public List<string> imgFiles { get; set; }
}
VideoID (I use a database) tells the threaded process which video to use taken from the database. fname is used in other parts of my functions that use FilesToProcess, but not used here. durationSeconds - is filled in by the threads that just collect video duration. imgFiles is used to return any thumbnails that were created.
I do not want to get bogged down in my code when the purpose of this is to encourage the use of ffmpeg in easily controlled threads.
Now we have our pieces we can add to our threads list, so in our controller we do something like,
AddThread()
{
ThrdFfmpeg thrd;
FileToProcess ftp;
foreach(FileToProcess ff in `dbhelper.GetFileNames(txtCategory.Text))`
{
//make a thread for each
ftp = new FileToProcess();
ftp = ff;
ftp.imgFiles = new List<string>();
thrd = new ThrdFfmpeg();
thrd.ffm = new FfmpegStuff();
thrd.ffm.filetoprocess = ftp;
thrd.thrd = new `System.Threading.Thread(thrd.ffm.CollectVideoLength);`
threads.Add(thrd);
}
if(timerNotStarted)
StartThreadTimer();
}
Now Pole'ing our threads becomes a simple task,
private void timerThreads_Tick(object sender, EventArgs e)
{
int runningCount = 0;
int finishedThreads = 0;
foreach(ThrdFfmpeg thrd in threads)
{
switch (thrd.thrd.ThreadState)
{
case System.Threading.ThreadState.Running:
++runningCount;
//Note that you can still view data progress here,
//but remember that you must use your safety checks
//here more than anywhere else in your code, make sure the data
//is readable and of the right sort, before you read it.
break;
case System.Threading.ThreadState.StopRequested:
break;
case System.Threading.ThreadState.SuspendRequested:
break;
case System.Threading.ThreadState.Background:
break;
case System.Threading.ThreadState.Unstarted:
//Any threads that have been added but not yet started, start now
thrd.thrd.Start();
++runningCount;
break;
case System.Threading.ThreadState.Stopped:
++finishedThreads;
//You can now safely read the results, in this case the
//data contained in FilesToProcess
//Such as
ThumbnailsReadyEvent( thrd.ffm );
break;
case System.Threading.ThreadState.WaitSleepJoin:
break;
case System.Threading.ThreadState.Suspended:
break;
case System.Threading.ThreadState.AbortRequested:
break;
case System.Threading.ThreadState.Aborted:
break;
default:
break;
}
}
if(flash)
{//just a simple indicator so that I can see
//that at least one thread is still running
lbThreadStatus.BackColor = Color.White;
flash = false;
}
else
{
lbThreadStatus.BackColor = this.BackColor;
flash = true;
}
if(finishedThreads >= threads.Count())
{
StopThreadTimer();
ShowSample();
MakeJoinedThumb();
}
}
Putting your own events onto into the controller class works well, but in video work, when my own code is not actually doing any of the video file processing, poling then invoking an event in the controlling class works just as well.
Using this method I have slowly built up just about every video and stills function I think I will ever use, all contained in the one class, and that class as a text file is useable on the Lunux and Windows version, with just a small number of pre-process directives.
Paste my contains
example here:
//table[contains(@class, "EC_result")]/tbody
Well I got this Issue too in my few websites and all i need to do is customize the content fetler for HTML entites. before that more i delete them more i got, so just change you html fiter or parsing function for the page and it worked. Its mainly due to HTML editors in most of CMSs. the way they store parse the data caused this issue (In My case). May this would Help in your case too
Provide the source image (img) size as the first rectangle:
ctx.drawImage(img, 0, 0, img.width, img.height, // source rectangle
0, 0, canvas.width, canvas.height); // destination rectangle
The second rectangle will be the destination size (what source rectangle will be scaled to).
Update 2016/6: For aspect ratio and positioning (ala CSS' "cover" method), check out:
Simulation background-size: cover in canvas
The most similar C# Select
analogue would be a map
function.
Just use:
var ids = selectedFruits.map(fruit => fruit.id);
to select all ids from selectedFruits
array.
It doesn't require any external dependencies, just pure JavaScript. You can find map
documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Rich Sutton's answer finally worked for me, after I realized that adding access_type=offline
is done on the front end client's request for an authorization code, not the back end request that exchanges that code for an access_token. I've added a comment to his answer and this link at Google for more info about refreshing tokens.
P.S. If you are using Satellizer, here is how to add that option to the $authProvider.google in AngularJS.
we also have had similar problems (we're behind a corporate proxy). changing to yarn at least on our jenkins builds made a huge difference.
there are some minor differences in the results between "npm install" and "yarn install" - but nothing that hurts us.
I had the same problem with my chromedriver using Python and options.add_argument("headless") did not work for me, but then I realized how to fix it so I bring it in the code below:
opt = webdriver.ChromeOptions()
opt.arguments.append("headless")
This happens because $cOTLdata
is not null but the index 'char_data'
does not exist. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.
To check whether the index exists or not you can use isset():
isset($cOTLdata['char_data'])
Which means the line should look something like this:
$len = isset($cOTLdata['char_data']) ? count($cOTLdata['char_data']) : 0;
Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).
This works for me
msg.BodyFormat = MailFormat.Html;
and then you can use html in your body
msg.Body = "<em>It's great to use HTML in mail!!</em>"
One option is to use a numbers/tally table to drive an iterative process via a pseudo-set based query.
The general idea of char replacement can be demonstrated with a simple character map table approach:
create table charMap (srcChar char(1), replaceChar char(1))
insert charMap values ('a', 'z')
insert charMap values ('b', 'y')
create table testChar(srcChar char(1))
insert testChar values ('1')
insert testChar values ('a')
insert testChar values ('2')
insert testChar values ('b')
select
coalesce(charMap.replaceChar, testChar.srcChar) as charData
from testChar left join charMap on testChar.srcChar = charMap.srcChar
Then you can bring in the tally table approach to do the lookup on each character position in the string.
create table tally (i int)
declare @i int
set @i = 1
while @i <= 256 begin
insert tally values (@i)
set @i = @i + 1
end
create table testData (testString char(10))
insert testData values ('123a456')
insert testData values ('123ab456')
insert testData values ('123b456')
select
i,
SUBSTRING(testString, i, 1) as srcChar,
coalesce(charMap.replaceChar, SUBSTRING(testString, i, 1)) as charData
from testData cross join tally
left join charMap on SUBSTRING(testString, i, 1) = charMap.srcChar
where i <= LEN(testString)
C# 8 allows you to solve this problem elegantly and compactly using an switch expression:
public string GetTypeName(object obj)
{
return obj switch
{
int i => "Int32",
string s => "String",
{ } => "Unknown",
_ => throw new ArgumentNullException(nameof(obj))
};
}
As a result, you get:
Console.WriteLine(GetTypeName(obj: 1)); // Int32
Console.WriteLine(GetTypeName(obj: "string")); // String
Console.WriteLine(GetTypeName(obj: 1.2)); // Unknown
Console.WriteLine(GetTypeName(obj: null)); // System.ArgumentNullException
You can read more about the new feature here.
Use the browser/chrome postman plugin to check the CORS/SOP like a website. Use desktop application instead to avoid these controls.
Detach
is unnecessary.
The answer (as of 2013) is simple:
$('#parentNode').append($('#childNode'));
According to http://api.jquery.com/append/
You can also select an element on the page and insert it into another:
$('.container').append($('h2'));
If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved into the target (not cloned).
HTML are markup languages, basically they are set of tags like <html>
, <body>
, which is used to present a website using css, and javascript as a whole. All these, happen in the clients system or the user you will be browsing the website.
Now, Connecting to a database, happens on whole another level. It happens on server, which is where the website is hosted.
So, in order to connect to the database and perform various data related actions, you have to use server-side scripts, like php, jsp, asp.net etc.
Now, lets see a snippet of connection using MYSQLi Extension of PHP
$db = mysqli_connect('hostname','username','password','databasename');
This single line code, is enough to get you started, you can mix such code, combined with HTML tags to create a HTML page, which is show data based pages. For example:
<?php
$db = mysqli_connect('hostname','username','password','databasename');
?>
<html>
<body>
<?php
$query = "SELECT * FROM `mytable`;";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_assoc($result)) {
// Display your datas on the page
}
?>
</body>
</html>
In order to insert new data into the database, you can use phpMyAdmin
or write a INSERT
query and execute them.
Here is another option that works well when ng-class can't be used (for example when styling SVG):
ng-attr-class="{{someBoolean && 'class-when-true' || 'class-when-false' }}"
(I think you need to be on latest unstable Angular to use ng-attr-, I'm currently on 1.1.4)
You must to add a needle headers:
Sample code :
$headers = "From: [email protected]\r\n";
$headers .= "Reply-To: [email protected]\r\n";
$headers .= "Return-Path: [email protected]\r\n";
$headers .= "CC: [email protected]\r\n";
$headers .= "BCC: [email protected]\r\n";
if ( mail($to,$subject,$message,$headers) ) {
echo "The email has been sent!";
} else {
echo "The email has failed!";
}
?>
If you're certain that you have installed ssh, then it's possible that ssh
and/or sshd
has been terminated or the server service hasn't been started. To check whether these processes are running use:
//this tells you whether your ssh instance is active/inactive
sudo service ssh status
OR
//this list all running processes whose names contain the string "ssh"
sudo ps -A | grep ssh
It's likely that ssh
would be active and running but sshd
would not.
To enable them:
sudo service ssh start
NB; - some systems have a restart option but mine didn't
big=small=values[0]; //assigns element to be highest or lowest value
Should be AFTER
fill loop
//counts to 20 and prompts user for value and stores it
for ( int i = 0; i < 20; i++ )
{
cout << "Enter value " << i << ": ";
cin >> values[i];
}
big=small=values[0]; //assigns element to be highest or lowest value
since when you declare array - it's unintialized
(store some undefined values) and so, your big
and small
after assigning would store undefined
values too.
And of course, you can use std::min_element
, std::max_element
, or std::minmax_element
from C++11
, instead of writing your loops.
The temporary tables are defined in "tempdb", and the table names are "mangled".
This query should do the trick:
select c.*
from tempdb.sys.columns c
inner join tempdb.sys.tables t ON c.object_id = t.object_id
where t.name like '#MyTempTable%'
Marc
Maybe you want to track the remote branch with a local branch:
git branch new-local-branch
git branch --set-upstream-to=origin/remote-branch new-local-branch
git checkout new-local-branch
git pull
docker ps -a | grep training/webapp | cut -d ' ' -f 1 | xargs docker rm
- ps -a: list all containers
- grep training/webapp : filter out everything but the containers started from the training/webapp image
- cut -d ' ' -f 1: list only the container ids (first field when delimited by space)
- xargs docker rm : send the container id list output to the docker rm command to remove the container
If you have access to SRV Records, you can use them to get what you want :)
E.G
A Records
Name: mc1.domain.com
Value: <yourIP>
Name: mc2.domain.com
Value: <yourIP>
SRV Records
Name: _minecraft._tcp.mc1.domain.com
Priority: 5
Weight: 5
Port: 25565
Value: mc1.domain.com
Name: _minecraft._tcp.mc2.domain.com
Priority: 5
Weight: 5
Port: 25566
Value: mc2.domain.com
then in minecraft you can use
mc1.domain.com which will sign you into server 1 using port 25565
and
mc2.domain.com which will sign you into server 2 using port 25566
then on your router you can have it point 25565 and 25566 to the machine with both servers on and Voilà!
Source: This works for me running 2 minecraft servers on the same machine with ports 50500 and 50501
I figured out how to do this in Powershell that someone asked about:
$keyname=(((gci cert:\LocalMachine\my | ? {$_.thumbprint -like $thumbprint}).PrivateKey).CspKeyContainerInfo).UniqueKeyContainerName
$keypath = $env:ProgramData + “\Microsoft\Crypto\RSA\MachineKeys\”
$fullpath=$keypath+$keyname
$Acl = Get-Acl $fullpath
$Ar = New-Object System.Security.AccessControl.FileSystemAccessRule("IIS AppPool\$iisAppPoolName", "Read", "Allow")
$Acl.SetAccessRule($Ar)
Set-Acl $fullpath $Acl
Just install the sdk command line tool(latest) the below in android studio.
The number of arguments is $#
Search for it on this page to learn more: http://tldp.org/LDP/abs/html/internalvariables.html#ARGLIST
You have to put:
<html ng-app="urlApp" ng-controller="urlCtrl">
This way the angular function can access into "window" object
sprintf() is the PHP function for all sorts of string formatting http://php.net/manual/en/function.sprintf.php
I use this function:
function formatDollars($dollars){
return '$ '.sprintf('%0.2f', $dollars);
}
As rebenvp said I used:
g++ *.cpp -o output
And then do this for output:
./output
But a better solution is to use make
file. Read here to know more about make
files.
Also make sure that you have added the required .h
files in the .cpp
files.
display
settingIt is of course possible - JSFiddle proof of concept where you can see all three possible solutions:
display: inline-block
- this is the one you're not aware of
position: absolute
float: left/right
You have to add it to /etc/paths
.
Reference (which works for me) : Here
instead of id use title to identify your element and write the code as below.
$(document).ready(()=>{
$("input[title='MyObject']").change(()=>{
console.log("Field has been changed...")
})
});
Whilst Cletus' answer is correct, I feel more detail should be added in regards to "evaluates to false" in JavaScript.
var title = title || 'Error';
var msg = msg || 'Error on Request';
Is not just checking if title/msg has been provided, but also if either of them are falsy. i.e. one of the following:
- false.
- 0 (zero)
- "" (empty string)
- null.
- undefined.
- NaN (a special Number value meaning Not-a-Number!)
So in the line
var title = title || 'Error';
If title is truthy (i.e., not falsy, so title = "titleMessage" etc.) then the Boolean OR (||) operator has found one 'true' value, which means it evaluates to true, so it short-circuits and returns the true value (title).
If title is falsy (i.e. one of the list above), then the Boolean OR (||) operator has found a 'false' value, and now needs to evaluate the other part of the operator, 'Error', which evaluates to true, and is hence returned.
It would also seem (after some quick firebug console experimentation) if both sides of the operator evaluate to false, it returns the second 'falsy' operator.
i.e.
return ("" || undefined)
returns undefined, this is probably to allow you to use the behavior asked about in this question when trying to default title/message to "". i.e. after running
var foo = undefined
foo = foo || ""
foo would be set to ""
We have various structural/syntactical difference between interface and abstract class. Some more differences are
[1] Scenario based difference:
Abstract classes are used in scenarios when we want to restrict the user to create object of parent class AND we believe there will be more abstract methods will be added in future.
Interface has to be used when we are sure there can be no more abstract method left to be provided. Then only an interface is published.
[2] Conceptual difference:
"Do we need to provide more abstract methods in future" if YES make it abstract class and if NO make it Interface.
(Most appropriate and valid till java 1.7)
You can use destructuring to only focus on the part of your interest.
So you can do:
let str = "My cow always gives milk";
let [, result] = str.match(/\bcow\s+(.*?)\s+milk\b/) || [];
console.log(result);
_x000D_
In this way you ignore the first part (the complete match) and only get the capture group's match. The addition of || []
may be interesting if you are not sure there will be a match at all. In that case match
would return null
which cannot be destructured, and so we return []
instead in that case, and then result
will be null
.
The additional \b
ensures the surrounding words "cow" and "milk" are really separate words (e.g. not "milky"). Also \s+
is needed to avoid that the match includes some outer spacing.
It took me a little more than just one method in the struct like the swift book called for but I set up next functions in the enum
. I would have used a protocol I'm not sure why but having rank set as int messes it up.
enum Rank: Int {
case Ace = 1
case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
case Jack, Queen, King
func simpleDescription() -> String {
switch self {
case .Ace:
return "ace"
case .Jack:
return "jack"
case .Queen:
return "Queen"
case .King:
return "King"
default:
return String(self.toRaw())
}
}
mutating func next() -> Rank {
var rank = self
var rawrank = rank.toRaw()
var nrank: Rank = self
rawrank = rawrank + 1
if let newRank = Rank.fromRaw(rawrank) {
println("\(newRank.simpleDescription())")
nrank = newRank
} else {
return self
}
return nrank
}
}
enum Suit {
case Spades, Hearts, Diamonds, Clubs
func color() -> String {
switch self {
case .Spades, .Clubs:
return "black"
default:
return "red"
}
}
func simpleDescription() -> String {
switch self {
case .Spades:
return "spades"
case .Hearts:
return "hearts"
case .Diamonds:
return "diamonds"
case .Clubs:
return "clubs"
}
}
mutating func next() -> Suit {
switch self {
case .Spades:
return Hearts
case .Hearts:
return Diamonds
case .Diamonds:
return Clubs
case .Clubs:
return Spades
}
}
}
struct Card {
var rank: Rank
var suit: Suit
func deck() -> Card[] {
var tRank = self.rank
var tSuit = self.suit
let tcards = 52 // we start from 0
var cards: Card[] = []
for i in 0..tcards {
var card = Card(rank: tRank, suit: tSuit)
cards.append(card)
tRank = tRank.next()
tSuit = tSuit.next()
}
return cards
}
func simpleDescription() -> String {
return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"
}
}
var card = Card(rank: .Ace, suit: .Spades)
var deck = card.deck()
I used a little general knowledge but that can be easily rectified by multiplying suits by rank (if you aren't using a standard deck of cards and you'd have to change the enums accordingly and if basically just steps through the different enums. To save time I used ranks rawValues
you could do the same for suits if you wanted. However, the example did not have it so I decided to figure it out without changing suits rawValue
In theory like so:
# BOLD
$ echo -e "\033[1mThis is a BOLD line\033[0m"
This is a BOLD line
# Using tput
tput bold
echo "This" #BOLD
tput sgr0 #Reset text attributes to normal without clear.
echo "This" #NORMAL
# UNDERLINE
$ echo -e "\033[4mThis is a underlined line.\033[0m"
This is a underlined line.
But in practice it may be interpreted as "high intensity" color instead.
(source: http://unstableme.blogspot.com/2008/01/ansi-escape-sequences-for-writing-text.html)
Here's an abstraction of Will Nathan's answer if anyone just wants an easy copy-paste add-in function:
function find (name, query, cb) {
mongoose.connection.db.collection(name, function (err, collection) {
collection.find(query).toArray(cb);
});
}
simply do find(collection_name, query, callback);
to be given the result.
for example, if I have a document { a : 1 } in a collection 'foo' and I want to list its properties, I do this:
find('foo', {a : 1}, function (err, docs) {
console.dir(docs);
});
//output: [ { _id: 4e22118fb83406f66a159da5, a: 1 } ]
display:none
will hide the element and collapse the space is was taking up, whereas visibility:hidden
will hide the element and preserve the elements space. display:none also effects some of the properties available from javascript in older versions of IE and Safari.
To make the Share work with the facebook app, you only need to have suply at least one link:
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, "Wonderful search engine http://www.google.fr/");
startActivity(Intent.createChooser(intent, "Share with"));
This will show the correct sharing window but when you click on share, nothing happends (I also tried with the official Twitter App, it does not work).
The only way I found to make the Facebook app sharing work is to share only a link with no text:
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, "http://www.google.fr/");
startActivity(Intent.createChooser(intent, "Share with"));
It will show the following window and the Share button will work:
Apparently it automatically takes an image and text from the link to populate the share.
If you want to share only text, you will have to use the facebook api: https://github.com/facebook/facebook-android-sdk
Please make sure you are using latest jdbc connector as per the mysql. I was facing this problem and when I replaced my old jdbc connector with the latest one, the problem was solved.
You can download latest jdbc driver from https://dev.mysql.com/downloads/connector/j/
Select Operating System as Platform Independent. It will show you two options. One as tar and one as zip. Download the zip and extract it to get the jar file and replace it with your old connector.
This is not only for hibernate framework, it can be used with any platform which requires a jdbc connector.
looks like you have maven project and so resources are in classpath by
go for
getClass().getResource("classpath:storedProcedures.sql")
Here is a website to create a Parcelable Class from your created class:
@Jason-V, it really help, thanks. then, i found this examples and composed to own snippet.
#!/usr/bin/env python3
import os, readline, atexit
python_history = os.path.join(os.environ['HOME'], '.python_history')
try:
readline.read_history_file(python_history)
readline.parse_and_bind("tab: complete")
readline.set_history_length(5000)
atexit.register(readline.write_history_file, python_history)
except IOError:
pass
del os, python_history, readline, atexit
Here is the correct solution to solving this problem:
public void hideProgress() {
if(mProgressDialog != null) {
if(mProgressDialog.isShowing()) { //check if dialog is showing.
//get the Context object that was used to great the dialog
Context context = ((ContextWrapper)mProgressDialog.getContext()).getBaseContext();
//if the Context used here was an activity AND it hasn't been finished or destroyed
//then dismiss it
if(context instanceof Activity) {
if(!((Activity)context).isFinishing() && !((Activity)context).isDestroyed())
mProgressDialog.dismiss();
} else //if the Context used wasnt an Activity, then dismiss it too
mProgressDialog.dismiss();
}
mProgressDialog = null;
}
}
Instead of blindly catching all exceptions, this solution addresses the root of the problem: trying to dimiss a dialog when the activity used to initialize the dialog has already been finished. Working on my Nexus 4 running KitKat, but should work for all versions of Android.
Just tossing it out there, but WordPress has a structure for this kind of stuff (at least WordPress was the first place I observed it, it probably originated elsewhere).
It allows limitless keys, and is faster to search than using a JSON blob, but not as fast as some of the NoSQL solutions.
uid | meta_key | meta_val
----------------------------------
1 name Frank
1 age 12
2 name Jeremiah
3 fav_food pizza
.................
EDIT
For storing history/multiple keys
uid | meta_id | meta_key | meta_val
----------------------------------------------------
1 1 name Frank
1 2 name John
1 3 age 12
2 4 name Jeremiah
3 5 fav_food pizza
.................
and query via something like this:
select meta_val from `table` where meta_key = 'name' and uid = 1 order by meta_id desc
This is clearly a classpath problem. Take into consideration that the classpath must change a bit when you run your program outside the IDE. This is because the IDE loads the other JARs relative to the root folder of your project, while in the case of the final JAR this is usually not true.
What I like to do in these situations is build the JAR manually. It takes me at most 5 minutes and it always solves the problem. I do not suggest you do this. Find a way to use Maven, that's its purpose.
Here are two extension methods you can use. They ensure any existing classes are preserved and do not duplicate classes being added.
public static void RemoveCssClass(this WebControl control, String css) {
control.CssClass = String.Join(" ", control.CssClass.Split(' ').Where(x => x != css).ToArray());
}
public static void AddCssClass(this WebControl control, String css) {
control.RemoveCssClass(css);
css += " " + control.CssClass;
control.CssClass = css;
}
Usage: hlCreateNew.AddCssClass("disabled");
Usage: hlCreateNew.RemoveCssClass("disabled");
this may be also possibly solution.It some times also occurs when you keep your Development project into too deep, means may be possible project directory may have too many directories so please don't make too many directories keep it in a simple folder inside the drives. For Example- I was also getting this error when my project was kept like this-
D:\Sharad\LatestWorkings\GenericSurveyApplication020120\GenericSurveyApplication\GenericSurveyApplication
then I simply Pasted my project inside
D:\Sharad\LatestWorkings\GenericSurveyApplication
And Problem was solved.
If you are on linux systems
please try running sudo php artisan migrate
As for me,sometimes database operations need to run with sudo in laravel.
You can zip
the list with itself sans the first element:
a = [5, 7, 11, 4, 5]
for previous, current in zip(a, a[1:]):
print(previous, current)
This works even if your list has no elements or only 1 element (in which case zip
returns an empty iterable and the code in the for
loop never executes). It doesn't work on generators, only sequences (tuple
, list
, str
, etc).
I was having the same problem with 3 of 4 inline svgs I was using, and they only disappeared (in one case, partially) on IE11.
I had <meta http-equiv="x-ua-compatible" content="ie=edge">
on the page.
In the end, the problem was extra clipping paths on the svg file. I opened the files on Illustrator, removed the clipping path (normally at the bottom of the layers) and now they're all working.
First create assets
folder then create fonts
folder in it.
Then you can set font
from assets
or directory
like bellow :
public class FontSampler extends Activity {
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
TextView tv = (TextView) findViewById(R.id.custom);
Typeface face = Typeface.createFromAsset(getAssets(), "fonts/HandmadeTypewriter.ttf");
tv.setTypeface(face);
File font = new File(Environment.getExternalStorageDirectory(), "MgOpenCosmeticaBold.ttf");
if (font.exists()) {
tv = (TextView) findViewById(R.id.file);
face = Typeface.createFromFile(font);
tv.setTypeface(face);
} else {
findViewById(R.id.filerow).setVisibility(View.GONE);
}
}
}
//function a(callback){_x000D_
setTimeout(function() {_x000D_
console.log('Hi I am order 1');_x000D_
}, 3000);_x000D_
// callback();_x000D_
//}_x000D_
_x000D_
//function b(callback){_x000D_
setTimeout(function() {_x000D_
console.log('Hi I am order 2');_x000D_
}, 2000);_x000D_
// callback();_x000D_
//}_x000D_
_x000D_
_x000D_
_x000D_
//function c(callback){_x000D_
setTimeout(function() {_x000D_
console.log('Hi I am order 3');_x000D_
}, 1000);_x000D_
// callback();_x000D_
_x000D_
//}_x000D_
_x000D_
_x000D_
/*function d(callback){_x000D_
a(function(){_x000D_
b(function(){_x000D_
_x000D_
c(callback);_x000D_
_x000D_
});_x000D_
_x000D_
});_x000D_
_x000D_
_x000D_
}_x000D_
d();*/_x000D_
_x000D_
_x000D_
async function funa(){_x000D_
_x000D_
var pr1=new Promise((res,rej)=>{_x000D_
_x000D_
setTimeout(()=>res("Hi4 I am order 1"),3000)_x000D_
_x000D_
})_x000D_
_x000D_
_x000D_
var pr2=new Promise((res,rej)=>{_x000D_
_x000D_
setTimeout(()=>res("Hi4 I am order 2"),2000)_x000D_
_x000D_
})_x000D_
_x000D_
var pr3=new Promise((res,rej)=>{_x000D_
_x000D_
setTimeout(()=>res("Hi4 I am order 3"),1000)_x000D_
_x000D_
})_x000D_
_x000D_
_x000D_
var res1 = await pr1;_x000D_
var res2 = await pr2;_x000D_
var res3 = await pr3;_x000D_
console.log(res1,res2,res3);_x000D_
console.log(res1);_x000D_
console.log(res2);_x000D_
console.log(res3);_x000D_
_x000D_
} _x000D_
funa();_x000D_
_x000D_
_x000D_
_x000D_
async function f1(){_x000D_
_x000D_
await new Promise(r=>setTimeout(r,3000))_x000D_
.then(()=>console.log('Hi3 I am order 1'))_x000D_
return 1; _x000D_
_x000D_
}_x000D_
_x000D_
async function f2(){_x000D_
_x000D_
await new Promise(r=>setTimeout(r,2000))_x000D_
.then(()=>console.log('Hi3 I am order 2'))_x000D_
return 2; _x000D_
_x000D_
}_x000D_
_x000D_
async function f3(){_x000D_
_x000D_
await new Promise(r=>setTimeout(r,1000))_x000D_
.then(()=>console.log('Hi3 I am order 3'))_x000D_
return 3; _x000D_
_x000D_
}_x000D_
_x000D_
async function finaloutput2(arr){_x000D_
_x000D_
return await Promise.all([f3(),f2(),f1()]);_x000D_
}_x000D_
_x000D_
//f1().then(f2().then(f3()));_x000D_
//f3().then(f2().then(f1()));_x000D_
_x000D_
//finaloutput2();_x000D_
_x000D_
//var pr1=new Promise(f3)_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
async function f(){_x000D_
console.log("makesure");_x000D_
var pr=new Promise((res,rej)=>{_x000D_
setTimeout(function() {_x000D_
console.log('Hi2 I am order 1');_x000D_
}, 3000);_x000D_
});_x000D_
_x000D_
_x000D_
var result=await pr;_x000D_
console.log(result);_x000D_
}_x000D_
_x000D_
// f(); _x000D_
_x000D_
async function g(){_x000D_
console.log("makesure");_x000D_
var pr=new Promise((res,rej)=>{_x000D_
setTimeout(function() {_x000D_
console.log('Hi2 I am order 2');_x000D_
}, 2000);_x000D_
});_x000D_
_x000D_
_x000D_
var result=await pr;_x000D_
console.log(result);_x000D_
}_x000D_
_x000D_
// g(); _x000D_
_x000D_
async function h(){_x000D_
console.log("makesure");_x000D_
var pr=new Promise((res,rej)=>{_x000D_
setTimeout(function() {_x000D_
console.log('Hi2 I am order 3');_x000D_
}, 1000);_x000D_
});_x000D_
_x000D_
_x000D_
var result=await pr;_x000D_
console.log(result);_x000D_
}_x000D_
_x000D_
async function finaloutput(arr){_x000D_
_x000D_
return await Promise.all([f(),g(),h()]);_x000D_
}_x000D_
_x000D_
//finaloutput();_x000D_
_x000D_
//h(); _x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
This is similar to the answer mplungjan referenced from another post, but more concise:
const secs = 456;_x000D_
_x000D_
const formatted = moment.utc(secs*1000).format('HH:mm:ss');_x000D_
_x000D_
document.write(formatted);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
_x000D_
It suffers from the same caveats, e.g. if seconds exceed one day (86400), you'll not get what you expect.
Sample XML:
<X>
<Y ATTRIB1=attrib1_value ATTRIB2=attrib2_value/>
</X>
string xPath="/" + X + "/" + Y +
"[@" + ATTRIB1 + "='" + attrib1_value + "']" +
"[@" + ATTRIB2 + "='" + attrib2_value + "']"
XPath Testbed: http://www.whitebeam.org/library/guide/TechNotes/xpathtestbed.rhtm
You can use T-SQL:
use master
GO
CREATE LOGIN [NT AUTHORITY\LOCALSERVICE] FROM WINDOWS WITH
DEFAULT_DATABASE=yourDbName
GO
CREATE LOGIN [NT AUTHORITY\NETWORKSERVICE] FROM WINDOWS WITH
DEFAULT_DATABASE=yourDbName
I use this as a part of restore from production server to testing machine:
USE master
GO
ALTER DATABASE yourDbName SET OFFLINE WITH ROLLBACK IMMEDIATE
RESTORE DATABASE yourDbName FROM DISK = 'd:\DropBox\backup\myDB.bak'
ALTER DATABASE yourDbName SET ONLINE
GO
CREATE LOGIN [NT AUTHORITY\LOCALSERVICE] FROM WINDOWS WITH
DEFAULT_DATABASE=yourDbName
GO
CREATE LOGIN [NT AUTHORITY\NETWORKSERVICE] FROM WINDOWS WITH
DEFAULT_DATABASE=yourDbName
GO
You will need to use localized name of services in case of German or French Windows, see How to create a SQL Server login for a service account on a non-English Windows?
What you have to do is something like this:
<Button Name="MyFlatImageButton"
Background="Transparent"
BorderBrush="Transparent"
BorderThickness="0"
Padding="-4">
<Image Source="MyImage.png"/>
</Button>
Hope this is what you were looking for.
Edit: Sorry, forgot to mention that if you want to see the button-border when you hover over the image, all you have to do is skip the Padding="-4".
you need surrounded my constraint-layout with a ScrollView tag and gave it the property android:isScrollContainer="true".
After allocating DateFormatter
you need to give the formatted string
then you can convert as string like this way
var date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let myString = formatter.string(from: date)
let yourDate: Date? = formatter.date(from: myString)
formatter.dateFormat = "dd-MMM-yyyy"
let updatedString = formatter.string(from: yourDate!)
print(updatedString)
OutPut
01-Mar-2017
C or C++ does not provide this functionality, although I've needed it often.
The following code works, although it's best suited for non-sparse enums.
typedef enum { ONE, TWO, THREE } Numbers;
char *strNumbers[] = {"one","two","three"};
printf ("Value for TWO is %s\n",strNumbers[TWO]);
By non-sparse, I mean not of the form
typedef enum { ONE, FOUR_THOUSAND = 4000 } Numbers;
since that has huge gaps in it.
The advantage of this method is that it put the definitions of the enums and strings near each other; having a switch statement in a function spearates them. This means you're less likely to change one without the other.
global static variables are initialized at compile-time unlike automatic
Based on something found on Code Project
Once the data table is declared based on the grid's data source, lookup the column index by column name from the columns collection. At this point, use the index as needed to obtain information from or to format the cell.
protected void gridMyGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataTable dt = (DataTable)((GridView)sender).DataSource;
int colIndex = dt.Columns["MyColumnName"].Ordinal;
e.Row.Cells[colIndex].BackColor = Color.FromName("#ffeb9c");
}
}
If you only want to change form's action, I prefer changing action on-form-submit, rather than on-input-change. It fires only once.
$('#search-form').submit(function(){
var formAction = $("#selectsearch").val() == "people" ? "user" : "content";
$("#search-form").attr("action", "/search/" + formAction);
});
Peter's answer with an additional check! Of course, not 100% guaranteed!
var isJson = false;
outPutValue = ""
var objectConstructor = {}.constructor;
if(jsonToCheck.constructor === objectConstructor){
outPutValue = JSON.stringify(jsonToCheck);
try{
JSON.parse(outPutValue);
isJson = true;
}catch(err){
isJson = false;
}
}
if(isJson){
alert("Is json |" + JSON.stringify(jsonToCheck) + "|");
}else{
alert("Is other!");
}
You can do following
<div id="circle"></div>
CSS
#circle {
width: 100px;
height: 100px;
background: red;
-moz-border-radius: 50px;
-webkit-border-radius: 50px;
border-radius: 50px;
}
Other shape SOURCE
Sometimes it's asking the question that makes the answer jump out. The methods and extra arguments are listed on the ggplot2 wiki stat_smooth page.
Which is alluded to on the geom_smooth()
page with:
"See stat_smooth for examples of using built in model fitting if you need some more flexible, this example shows you how to plot the fits from any model of your choosing".
It's not the first time I've seen arguments in examples for ggplot graphs that aren't specifically in the function. It does make it tough to work out the scope of each function, or maybe I am yet to stumble upon a magic explicit list that says what will and will not work within each function.
You can loop all of the array and add into ArrayList:
ArrayList<String> files = new ArrayList<String>(filesOrig.length);
for(String file: filesOrig) {
files.add(file);
}
Or use Arrays.asList(T... a)
to do as the comment posted.
JSON regulates key type to be string. The purpose is to support the dot notation to access the members of the object.
For example, person = {"height":170, "weight":60, "age":32}. You can access members by person.height, person.weight, etc. If JSON supports value keys, then it would look like person.0, person.1, person.2.
Use java.util.LinkedList. Like this:
list = new java.util.LinkedList()
If you'd like to initialize the array to values other than 0, with gcc
you can do:
int array[1024] = { [ 0 ... 1023 ] = -1 };
This is a GNU extension of C99 Designated Initializers. In older GCC, you may need to use -std=gnu99
to compile your code.
<html>
<head>
<title>orientation and device detection in css3</title>
<link rel="stylesheet" media="all and (max-device-width: 480px) and (orientation:portrait)" href="iphone-portrait.css" />
<link rel="stylesheet" media="all and (max-device-width: 480px) and (orientation:landscape)" href="iphone-landscape.css" />
<link rel="stylesheet" media="all and (device-width: 768px) and (device-height: 1024px) and (orientation:portrait)" href="ipad-portrait.css" />
<link rel="stylesheet" media="all and (device-width: 768px) and (device-height: 1024px) and (orientation:landscape)" href="ipad-landscape.css" />
<link rel="stylesheet" media="all and (device-width: 800px) and (device-height: 1184px) and (orientation:portrait)" href="htcdesire-portrait.css" />
<link rel="stylesheet" media="all and (device-width: 800px) and (device-height: 390px) and (orientation:landscape)" href="htcdesire-landscape.css" />
<link rel="stylesheet" media="all and (min-device-width: 1025px)" href="desktop.css" />
</head>
<body>
<div id="iphonelandscape">iphone landscape</div>
<div id="iphoneportrait">iphone portrait</div>
<div id="ipadlandscape">ipad landscape</div>
<div id="ipadportrait">ipad portrait</div>
<div id="htcdesirelandscape">htc desire landscape</div>
<div id="htcdesireportrait">htc desire portrait</div>
<div id="desktop">desktop</div>
<script type="text/javascript">
function res() { document.write(screen.width + ', ' + screen.height); }
res();
</script>
</body>
</html>
mysqli is provided by php-mysql-5.3.3-40.el6_6.x86_64
You may need to try the following
yum install php-mysql-5.3.3-40.el6_6.x86_64
I know that are are a lot of solution for this issue. The best and the easiest solution is to add .htaccess file in the root directory.
I tried the answers that we provided for this issue however I faced some issues with auth:api guard in Laravel.
Here's the updated solution:
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ ^$1 [N]
RewriteCond %{REQUEST_URI} (\.\w+$) [NC]
RewriteRule ^(.*)$ public/$1
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ server.php
</IfModule>
Create the .htaccess file in your root directory and add this code. And everything goes right
So, every reader here now should have a clear understanding about the facts, the situation. If not, then you must read paercebal's outstandingly comprehensive answer [btw: thanks!].
My pragmatical conclusion is shockingly simple: all that C++ (and STL) "character encoding" stuff is substantially broken and useless. Blame it on Microsoft or not, that will not help anyway.
My solution, after in-depth investigation, much frustration and the consequential experiences is the following:
accept, that you have to be responsible on your own for the encoding and conversion stuff (and you will see that much of it is rather trivial)
use std::string for any UTF-8 encoded strings (just a typedef std::string UTF8String
)
accept that such an UTF8String object is just a dumb, but cheap container. Do never ever access and/or manipulate characters in it directly (no search, replace, and so on). You could, but you really just really, really do not want to waste your time writing text manipulation algorithms for multi-byte strings! Even if other people already did such stupid things, don't do that! Let it be! (Well, there are scenarios where it makes sense... just use the ICU library for those).
use std::wstring for UCS-2 encoded strings (typedef std::wstring UCS2String
) - this is a compromise, and a concession to the mess that the WIN32 API introduced). UCS-2 is sufficient for most of us (more on that later...).
use UCS2String instances whenever a character-by-character access is required (read, manipulate, and so on). Any character-based processing should be done in a NON-multibyte-representation. It is simple, fast, easy.
add two utility functions to convert back & forth between UTF-8 and UCS-2:
UCS2String ConvertToUCS2( const UTF8String &str );
UTF8String ConvertToUTF8( const UCS2String &str );
The conversions are straightforward, google should help here ...
That's it. Use UTF8String wherever memory is precious and for all UTF-8 I/O. Use UCS2String wherever the string must be parsed and/or manipulated. You can convert between those two representations any time.
Alternatives & Improvements
conversions from & to single-byte character encodings (e.g. ISO-8859-1) can be realized with help of plain translation tables, e.g. const wchar_t tt_iso88951[256] = {0,1,2,...};
and appropriate code for conversion to & from UCS2.
if UCS-2 is not sufficient, than switch to UCS-4 (typedef std::basic_string<uint32_t> UCS2String
)
ICU or other unicode libraries?
Below are some of the way by which you can create a link button in MVC.
@Html.ActionLink("Admin", "Index", "Home", new { area = "Admin" }, null)
@Html.RouteLink("Admin", new { action = "Index", controller = "Home", area = "Admin" })
@Html.Action("Action", "Controller", new { area = "AreaName" })
@Url.Action("Action", "Controller", new { area = "AreaName" })
<a class="ui-btn" data-val="abc" href="/Home/Edit/ANTON">Edit</a>
<a data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#CustomerList" href="/Home/Germany">Customer from Germany</a>
<a data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#CustomerList" href="/Home/Mexico">Customer from Mexico</a>
Hope this will help you.
When working with pennies/integers. You will run into a problem with 115 (as in $1.15) and other numbers.
I had a function that would convert an Integer to a Float.
...
return float(115 * 0.01)
That worked most of the time but sometimes it would return something like 1.1500000000000001
.
So I changed my function to return like this...
...
return float(format(115 * 0.01, '.2f'))
and that will return 1.15
. Not '1.15'
or 1.1500000000000001
(returns a float, not a string)
I'm mostly posting this so I can remember what I did in this scenario since this is the first result in google.
The WHEN part is compared with ==, but you can't really compare with NULL. Try
CASE WHEN last_name is NULL THEN ... ELSE .. END
instead or COALESCE:
COALESCE(' '+last_name,'')
(' '+last_name is NULL when last_name is NULL, so it should return '' in that case)
The problem was that in XCode 4, the dependencies do not assume the architecture settings of the main project, as they previously did in XCode 3. I had to go through all of my dependencies setting them for the correct architecture.
Try using the html() function.
$('#<%=Label1.ClientID%>').html();
You're also missing the # to make it an ID you're searching for. Without the #, it's looking for a tag type.
Use a DecimalFormat object with a format string of "0.#".
The recommendations from this article Extracting Data From Excel with SSIS resolved the issue for me.
I downloaded MS Access Database Engine 2010 32 bit driver from the link in that article.
Also set Project Configuration Properties for Debugging Run64BitRuntime = False
In SQL Server 2014 SSMS (Integration Service Catalog -> SSISDB -> Environments -> Projects for all Packages in Validate checked box 32 bit Runtime
.
My SSIS packages are working now in both VS 2013 and SQL Server 2014 environments.
You can pass as many arguments as you want, separating them by commas:
{{ path('_files_manage', {project: project.id, user: user.id}) }}
C:\Users\>mysqldump -u root -p -h ip address --databases database_name -r sql_file.sql
Enter password: your_password
Joining lines with svgs was worth a shot for me, and it worked perfectly...
first of all, Scalable Vector Graphics (SVG) is an XML-based vector image format for two-dimensional graphics with support for interactivity and animation. SVG images and their behaviors are defined in XML text files. you can create an svg in HTML using <svg>
tag. Adobe Illustrator is one of the best software used to create an complex svgs using paths.
Procedure to join two divs using a line :
create two divs and give them any position as you need
<div id="div1" style="width: 100px; height: 100px; top:0; left:0; background:#e53935 ; position:absolute;"></div>
<div id="div2" style="width: 100px; height: 100px; top:0; left:300px; background:#4527a0 ; position:absolute;"></div>
(for the sake of explanation I am doing some inline styling but it is always good to make a separate css file for styling)
<svg><line id="line1"/></svg>
Line tag allows us to draw a line between two specified points(x1,y1) and (x2,y2). (for a reference visit w3schools.) we haven't specified them yet. because we will be using jQuery to edit the attributes (x1,y1,x2,y2) of line tag.
in <script>
tag write
line1 = $('#line1');
div1 = $('#div1');
div2 = $('#div2');
I used selectors to select the two divs and line...
var pos1 = div1.position();
var pos2 = div2.position();
jQuery position()
method allows us to obtain the current position of an element. For more information, visit https://api.jquery.com/position/ (you can use offset()
method too)
Now as we have obtained all the positions we need we can draw line as follows...
line1
.attr('x1', pos1.left)
.attr('y1', pos1.top)
.attr('x2', pos2.left)
.attr('y2', pos2.top);
jQuery .attr()
method is used to change attributes of the selected element.
All we did in above line is we changed attributes of line from
x1 = 0
y1 = 0
x2 = 0
y2 = 0
to
x1 = pos1.left
y1 = pos1.top
x2 = pos2.left
y2 = pos2.top
as position()
returns two values, one 'left' and other 'top', we can easily access them using .top and .left using the objects (here pos1 and pos2) ...
Now line tag has two distinct co-ordinates to draw line between two points.
Tip: add event listeners as you need to divs
Tip: make sure you import jQuery library first before writing anything in script tag
After adding co-ordinates through JQuery ... It will look something like this
Following snippet is for demonstration purpose only, please follow steps above to get correct solution
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="div1" style="width: 100px; height: 100px; top:0; left:0; background:#e53935 ; position:absolute;"></div>_x000D_
<div id="div2" style="width: 100px; height: 100px; top:0; left:300px; background:#4527a0 ; position:absolute;"></div>_x000D_
<svg width="500" height="500"><line x1="50" y1="50" x2="350" y2="50" stroke="red"/></svg>
_x000D_
Why not use margin? you can apply all kinds off margins to an element. Not just the whole margin around it.
You should use css classes since this is referencing more than one element and you can use id's for those that you want to be different specifically
i.e:
<style>
.box { height: 50px; background: #0F0; width: 100%; margin-top: 10px; }
#first { margin-top: 20px; }
#second { background: #00F; }
h1.box { background: #F00; margin-bottom: 50px; }
</style>
<h1 class="box">Hello World</h1>
<div class="box" id="first"></div>
<div class="box" id="second"></div>?
Here is a jsfiddle example:
REFERENCE:
You put it as =(B0+4)/($A$0)
You can also go across WorkSheets with Sheet1!$a$0
This is my code to set the service to foreground:
private void runAsForeground(){
Intent notificationIntent = new Intent(this, RecorderMainActivity.class);
PendingIntent pendingIntent=PendingIntent.getActivity(this, 0,
notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
Notification notification=new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentText(getString(R.string.isRecording))
.setContentIntent(pendingIntent).build();
startForeground(NOTIFICATION_ID, notification);
}
I need to build a notification using PendingIntent, so that I can start my main activity from the notification.
To remove the notification, just call the stopForeground(true);
It is called in the onStartCommand(). Please refer to my code at : https://github.com/bearstand/greyparrot/blob/master/src/com/xiong/richard/greyparrot/Mp3Recorder.java
Are you changing the primary key value of a User object somewhere? You shouldn't do that. Check that your mapping for the primary key is correct.
What does your mapping XML file or mapping annotations look like?
Although this answer is very late but might help other developer so I'm posting it here.
Answers above showing only how to set transparent background of TextView. We can achieve transparent Textview backcgorund in two way:
Second approach is better because it gives flexibility to set background with different color and then setting setting opacity to widget using android:alpha="0.2"
Example
<TextView
android:id="@+id/tv_name"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/black"
android:alpha="0.3"
android:textColor="@color/white"
android:textStyle="bold"/>
Just turn the LIKE around
SELECT * FROM customers
WHERE 'Robert Bob Smith III, PhD.' LIKE CONCAT('%',name,'%')
Probably a maximized Form helps, or you can do this manually upon form load:
Code Block
this.Location = new Point(0, 0);
this.Size = Screen.PrimaryScreen.WorkingArea.Size;
And then, play with anchoring, so the child controls inside your form automatically fit in your form's new size.
Hope this helps,
You can use justify-content: space-between
in .test
like so:
.test {_x000D_
display: flex;_x000D_
justify-content: space-between;_x000D_
width: 20rem;_x000D_
border: .1rem red solid;_x000D_
}
_x000D_
<div class="test">_x000D_
<button>test</button>_x000D_
<button>test</button>_x000D_
</div>
_x000D_
For those who want to use Bootstrap 4 can use justify-content-between
:
div {_x000D_
width: 20rem;_x000D_
border: .1rem red solid;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<div class="d-flex justify-content-between">_x000D_
<button>test</button>_x000D_
<button>test</button>_x000D_
</div>
_x000D_
date("Y-m-d H:i:s", strtotime("2019-05-13"))
I'm was collect most of issues by the web and combine stepping filter for all of them.
After some testing seems it works perfect:
/*
* Total XSS preventer class by Full-R
*
*/
final class xCleaner {
public static function clean( string $html ): string {
return self::cleanXSS(
preg_replace(
[
'/\s?<iframe[^>]*?>.*?<\/iframe>\s?/si',
'/\s?<style[^>]*?>.*?<\/style>\s?/si',
'/\s?<script[^>]*?>.*?<\/script>\s?/si',
'#\son\w*="[^"]+"#',
],
[
'',
'',
''
],
$html
)
);
}
protected static function hexToSymbols( string $s ): string {
return html_entity_decode($s, ENT_XML1, 'UTF-8');
}
protected static function escape( string $s, string $m = 'attr' ): string {
preg_match_all('/data:\w+\/([a-zA-Z]*);base64,(?!_#_#_)([^)\'"]*)/mi', $s, $b64, PREG_OFFSET_CAPTURE);
if( count( array_filter( $b64 ) ) > 0 ) {
switch( $m ) {
case 'attr':
$xclean = self::cleanXSS(
urldecode(
base64_decode(
$b64[ 2 ][ 0 ][ 0 ]
)
)
);
break;
case 'tag':
$xclean = self::cleanTagInnerXSS(
urldecode(
base64_decode(
$b64[ 2 ][ 0 ][ 0 ]
)
)
);
break;
}
return substr_replace(
$s,
'_#_#_'. base64_encode( $xclean ),
$b64[ 2 ][ 0 ][ 1 ],
strlen( $b64[ 2 ][ 0 ][ 0 ] )
);
}
else {
return $s;
}
}
protected static function cleanXSS( string $s ): string {
// base64 injection prevention
$st = self::escape( $s, 'attr' );
return preg_replace([
// JSON unicode
'/\\\\u?{?([a-f0-9]{4,}?)}?/mi', // [1] unicode JSON clean
// Data b64 safe
'/\*\w*\*/mi', // [2] unicode simple clean
// Malware payloads
'/:?e[\s]*x[\s]*p[\s]*r[\s]*e[\s]*s[\s]*s[\s]*i[\s]*o[\s]*n[\s]*(:|;|,)?\w*/mi', // [3] (:expression) evalution
'/l[\s]*i[\s]*v[\s]*e[\s]*s[\s]*c[\s]*r[\s]*i[\s]*p[\s]*t[\s]*(:|;|,)?\w*/mi', // [4] (livescript:) evalution
'/j[\s]*s[\s]*c[\s]*r[\s]*i[\s]*p[\s]*t[\s]*(:|;|,)?\w*/mi', // [5] (jscript:) evalution
'/j[\s]*a[\s]*v[\s]*a[\s]*s[\s]*c[\s]*r[\s]*i[\s]*p[\s]*t[\s]*(:|;|,)?\w*/mi', // [6] (javascript:) evalution
'/b[\s]*e[\s]*h[\s]*a[\s]*v[\s]*i[\s]*o[\s]*r[\s]*(:|;|,)?\w*/mi', // [7] (behavior:) evalution
'/v[\s]*b[\s]*s[\s]*c[\s]*r[\s]*i[\s]*p[\s]*t[\s]*(:|;|,)?\w*/mi', // [8] (vsbscript:) evalution
'/v[\s]*b[\s]*s[\s]*(:|;|,)?\w*/mi', // [9] (vbs:) evalution
'/e[\s]*c[\s]*m[\s]*a[\s]*s[\s]*c[\s]*r[\s]*i[\s]*p[\s]*t*(:|;|,)?\w*/mi', // [10] (ecmascript:) possible ES evalution
'/b[\s]*i[\s]*n[\s]*d[\s]*i[\s]*n[\s]*g*(:|;|,)?\w*/mi', // [11] (-binding) payload
'/\+\/v(8|9|\+|\/)?/mi', // [12] (UTF-7 mutation)
// Some entities
'/&{\w*}\w*/mi', // [13] html entites clenup
'/&#\d+;?/m', // [14] html entites clenup
// Script tag encoding mutation issue
'/\¼\/?\w*\¾\w*/mi', // [21] mutation KOI-8
'/\+ADw-\/?\w*\+AD4-\w*/mi', // [22] mutation old encodings
'/\/*?%00*?\//m',
// base64 escaped
'/_#_#_/mi', // [23] base64 escaped marker cleanup
],
// Replacements steps :: 23
['&#x$1;', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''],
str_ireplace(
['\u0', ':', '&tab;', '&newline;'],
['\0', ':', '', ''],
// U-HEX prepare step
self::hexToSymbols( $st ))
);
}
}
Also you can add Tidy markup correction to make HTML valid.
This is a variation of @mikez302's answer, but modified to support numbers with decimals (per @neu-rah's feedback that numberWithCommas(12345.6789) -> "12,345.6,789" instead of "12,345.6789"
function numberWithCommas(n) {
var parts=n.toString().split(".");
return parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (parts[1] ? "." + parts[1] : "");
}
how remote is that url ? is it from the same domain ? the code looks okay
try this
$.ajaxSetup({async:false});
$.get(remote_url, function(data) { remote = data; });
// or
remote = $.get(remote_url).responseText;
For PHPStorm 2020.3.2 on ubuntu inorder to reset expiration license, you should run following commands:
sudo rm ~/.config/JetBrains/PhpStorm2020.3/options/other.xml
sudo rm ~/.config/JetBrains/PhpStorm2020.3/eval/*
sudo rm -rf .java/.userPrefs
With CREATE TABLE statement
CREATE TABLE my_table (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
PRIMARY KEY (id)
) AUTO_INCREMENT = 100;
or with ALTER TABLE statement
ALTER TABLE my_table AUTO_INCREMENT = 200;
Bootstrap 4
<div class="col-md-9 col-xs-12 text-md-left text-center">md left, xs center</div>
<div class="col-md-9 col-xs-12 text-md-right text-center">md right, xs center</div>
Is there a way for a site to tell the browser not to offer to remember passwords?
The website tells the browser that it is a password by using <input type="password">
. So if you must do this from a website perspective then you would have to change that. (Obviously I don't recommend this).
The best solution would be to have the user configure their browser so it won't remember passwords.
The recommended way to write validation and authorization logic is to put that logic in separate request classes. This way your controller code will remain clean.
You can create a request class by executing php artisan make:request SomeRequest
.
In each request class's rules()
method define your validation rules:
//SomeRequest.php
public function rules()
{
return [
"name" => [
'required',
'array', // input must be an array
'min:3' // there must be three members in the array
],
"name.*" => [
'required',
'string', // input must be of type string
'distinct', // members of the array must be unique
'min:3' // each string must have min 3 chars
]
];
}
In your controller write your route function like this:
// SomeController.php
public function store(SomeRequest $request)
{
// Request is already validated before reaching this point.
// Your controller logic goes here.
}
public function update(SomeRequest $request)
{
// It isn't uncommon for the same validation to be required
// in multiple places in the same controller. A request class
// can be beneficial in this way.
}
Each request class comes with pre- and post-validation hooks/methods which can be customized based on business logic and special cases in order to modify the normal behavior of request class.
You may create parent request classes for similar types of requests (e.g. web
and api
) requests and then encapsulate some common request logic in these parent classes.
For Windows:
$ ssh-keygen -t rsa -b 4096 -C [email protected]
You can use Internet Explorer to browse folders and files together in tree. It is a file explorer in Favorites Window. You just need replace "favorites folder" to folder which you want see as a root folder
sort -u -t, -k1,1 file
-u
for unique-t,
so comma is the delimiter-k1,1
for the key field 1Test result:
[email protected],2009-11-27 00:58:29.793000000,xx3.net,255.255.255.0
[email protected],2009-11-27 01:05:47.893000000,xx2.net,127.0.0.1
Let's say you are writing a test case for a negative flow where the code being tested should raise an exception.
try{
bizMethod(badData);
fail(); // FAIL when no exception is thrown
} catch (BizException e) {
assert(e.errorCode == THE_ERROR_CODE_U_R_LOOKING_FOR)
}
use this from command line: sudo curl -L "https://github.com/docker/compose/releases/download/1.22.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
Apply executable permissions to the binary:
sudo chmod +x /usr/local/bin/docker-compose
Then test version:
$ docker-compose --version
another way is to use the range method
foo = [1,2,3,4,5,6]
bar = [10,20,30,40,50,60]
a = foo[0...3]
b = bar[3...6]
print a + b
=> [1, 2, 3, 40, 50 , 60]
After migrating from Turbo Pascal to C++ back in the day, I used to do this in order to have an equivalent for the Turbo Pascal "inherited" keyword, which works the same way. However, after programming in C++ for a few years I stopped doing it. I found I just didn't need it very much.
Sounds like you want:
var movies = _db.Movies.Where(p => p.Genres.Intersect(listOfGenres).Any());
First, scan the page for labels, and assign a reference to the label from the actual form element:
var labels = document.getElementsByTagName('LABEL');
for (var i = 0; i < labels.length; i++) {
if (labels[i].htmlFor != '') {
var elem = document.getElementById(labels[i].htmlFor);
if (elem)
elem.label = labels[i];
}
}
Then, you can simply go:
document.getElementById('MyFormElem').label.innerHTML = 'Look ma this works!';
No need for a lookup array :)
I personally prefer to use lambdas
in such a scenario, because imo it's clearer and simpler and also doesn't force you to write lots of wrapper methods if you don't have control over the called method, but that's certainly a matter of taste.
That's how you'd do it with a lambda (note there's also some implementation of currying in the functional module, so you can use that too):
button = Tk.Button(master=frame, text='press', command= lambda: action(someNumber))
Instead of what you have written, you can write it directly in the SelectedIndexChanged event of the dropdownlist control, e.g.
protected void ddlleavetype_SelectedIndexChanged(object sender, EventArgs e)
{
//code goes here
}
You need to merge the remote branch into your current branch by running git pull
.
If your local branch is already up-to-date, you may also need to run git pull --rebase
.
A quick google search also turned up this same question asked by another SO user: Cannot push to GitHub - keeps saying need merge. More details there.
Adding this just as an addition to @jimt's excellent answer:
one common way to define it all at initialization time is using an anonymous struct:
var opts = []struct {
shortnm byte
longnm, help string
needArg bool
}{
{'a', "multiple", "Usage for a", false},
{
shortnm: 'b',
longnm: "b-option",
needArg: false,
help: "Usage for b",
},
}
This is commonly used for testing as well to define few test cases and loop through them.
Imagine the .js
files are placed in /my-site/some/path/ui/js/myfile.js
So normally the script tag would look like:
<script src="/my-site/some/path/ui/js/myfile.js"></script>
Now change that to:
<script src="/my-site/some/path/ui-1111111111/js/myfile.js"></script>
Now of course that will not work. To make it work you need to add one or a few lines to your .htaccess
The important line is: (entire .htaccess at the bottom)
RewriteRule ^my-site\/(.*)\/ui\-([0-9]+)\/(.*) my-site/$1/ui/$3 [L]
So what this does is, it kind of removes the 1111111111
from the path and links to the correct path.
So now if you make changes you just have to change the number 1111111111
to whatever number you want. And however you include your files you can set that number via a timestamp when the js-file has last been modified. So cache will work normally if the number does not change. If it changes it will serve the new file (YES ALWAYS) because the browser get's a complete new URL and just believes that file is so new he must go get it.
You can use this for CSS
, favicons
and what ever gets cached. For CSS just use like so
<link href="http://my-domain.com/my-site/some/path/ui-1492513798/css/page.css" type="text/css" rel="stylesheet">
And it will work! Simple to update, simple to maintain.
The promised full .htaccess
If you have no .htaccess yet this is the minimum you need to have there:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^my-site\/(.*)\/ui\-([0-9]+)\/(.*) my-site/$1/ui/$3 [L]
</IfModule>
Your repository is broken. But you can probably fix it AND keep your edits:
cp your_repository your_repositry_bak
git clone your_repository your_repository_clone
rm -rf your_repository/.git && cp your_repository_clone/.git your_repository/ -r
rm -r your_repository_*
From your local machine:
rsync -chavzP --stats [email protected]:/path/to/copy /path/to/local/storage
From your local machine with a non standard ssh port:
rsync -chavzP -e "ssh -p $portNumber" [email protected]:/path/to/copy /local/path
Or from the remote host, assuming you really want to work this way and your local machine is listening on SSH:
rsync -chavzP --stats /path/to/copy [email protected]:/path/to/local/storage
See man rsync
for an explanation of my usual switches.
One more way:
git diff stash@{N}^! -- path/to/file1 path/to/file2 | git apply -R
Yes, you need to use PropTypes.arrayOf
instead of PropTypes.array
in the code, you can do something like this:
import PropTypes from 'prop-types';
MyComponent.propTypes = {
annotationRanges: PropTypes.arrayOf(
PropTypes.shape({
start: PropTypes.string.isRequired,
end: PropTypes.number.isRequired
}).isRequired
).isRequired
}
Also for more details about proptypes, visit Typechecking With PropTypes here
Why not doing it in two lines?
var a, b, c, d; // All in the same scope
a = b = c = d = 1; // Set value to all.
The reason why, is to preserve the local scope on variable declarations, as this:
var a = b = c = d = 1;
will lead to the implicit declarations of b
, c
and d
on the window scope.
You want to use "multiline".
$string =~ /(START)(.+?)(END)/m;
Just try -webkit-flexbox
. it's working for safari.
webkit-flex
safari will not taking.
Without seeing your code, it's hard to answer other than a stab in the dark. I would guess that the string you're passing to encodeURIComponent(), which is the correct method to use, is coming from the result of accessing the innerHTML property. The solution is to get the innerText/textContent property value instead:
var str,
el = document.getElementById("myUrl");
if ("textContent" in el)
str = encodeURIComponent(el.textContent);
else
str = encodeURIComponent(el.innerText);
If that isn't the case, you can use the replace() method to replace the HTML entity:
encodeURIComponent(str.replace(/&/g, "&"));
moment().toISOString(); // or format() - see below
http://momentjs.com/docs/#/displaying/as-iso-string/
Update
Based on the answer: by @sennet and the comment by @dvlsg (see Fiddle) it should be noted that there is a difference between format
and toISOString
. Both are correct but the underlying process differs. toISOString
converts to a Date object, sets to UTC then uses the native Date prototype function to output ISO8601 in UTC with milliseconds (YYYY-MM-DD[T]HH:mm:ss.SSS[Z]
). On the other hand, format
uses the default format (YYYY-MM-DDTHH:mm:ssZ
) without milliseconds and maintains the timezone offset.
I've opened an issue as I think it can lead to unexpected results.
(typeof files[1] === undefined)?
this.props.upload({file: files}):
this.props.postMultipleUpload({file: files widgetIndex: 0, id})
Check if the second item in the array is undefined using the typeof
and checking for undefined
I face this problem 5 minutes before.
I think that a solution (with visual studio 2005) is:
myString = comboBoxTest.GetItemText(comboBoxTest.SelectedItem);
Forgive me if I am wrong.
In case you get a cross-domain error:
If you have control over the content of the iframe - that is, if it is merely loaded in a cross-origin setup such as on Amazon Mechanical Turk - you can circumvent this problem with the <body onload='my_func(my_arg)'>
attribute for the inner html.
For example, for the inner html, use the this
html parameter (yes - this
is defined and it refers to the parent window of the inner body element):
<body onload='changeForm(this)'>
In the inner html :
function changeForm(window) {
console.log('inner window loaded: do whatever you want with the inner html');
window.document.getElementById('mturk_form').style.display = 'none';
</script>
If you really need single quotes, apostrophes, you can use
html | numeric | hex
‘ | ‘ | ‘ // for the left/beginning single-quote and
’ | ’ | ’ // for the right/ending single-quote
As what Jakob said: windows sdk 7.1 cannot be installed if MS VC++ x64 and x86 runtimes and redisrtibutables of version 10.0.40219 are present. after removing them win sdk install is okay, VS C++ SP1 can be installed fine again.
Kind regards
You can simply use it like this:
var regex = /( )/g;
_x000D_
Sample: click here
There are two issues with the code in the original question: there should not be a :
in the timezone and the format string for "timezone as an offset" is lower case %z
not upper %Z
.
This works for me in Python v3.6
>>> from datetime import datetime
>>> t = datetime.strptime("2012-11-01T04:16:13-0400", "%Y-%m-%dT%H:%M:%S%z")
>>> print(t)
2012-11-01 04:16:13-04:00
Here's an example that lists all tags of all images on the registry. It handles a registry configured for HTTP Basic auth too.
THE_REGISTRY=localhost:5000
# Get username:password from docker configuration. You could
# inject these some other way instead if you wanted.
CREDS=$(jq -r ".[\"auths\"][\"$THE_REGISTRY\"][\"auth\"]" .docker/config.json | base64 -d)
curl -s --user $CREDS https://$THE_REGISTRY/v2/_catalog | \
jq -r '.["repositories"][]' | \
xargs -I @REPO@ curl -s --user $CREDS https://$THE_REGISTRY/v2/@REPO@/tags/list | \
jq -M '.["name"] + ":" + .["tags"][]'
Explanation:
Make sure of the conflict origin: if it is the result of a git merge
, see Brian Campbell's answer.
But if is the result of a git rebase
, in order to discard remote (their) changes and use local changes, you would have to do a:
git checkout --theirs -- .
See "Why is the meaning of “ours
” and “theirs
” reversed"" to see how ours
and theirs
are swapped during a rebase (because the upstream branch is checked out).
if(data){}
it's mean !data
You can use Batch update but queries must be action(i.e. insert,update and delete) queries
Statement s = c.createStatement();
String s1 = "update emp set name='abc' where salary=984";
String s2 = "insert into emp values ('Osama',1420)";
s.addBatch(s1);
s.addBatch(s2);
s.executeBatch();
You can use the try
-except
-else
clause , this will catch any conversion/ value errors raised when the value passed cannot be converted to a float
def try_parse_float(item):
result = None
try:
float(item)
except:
pass
else:
result = float(item)
return result
In cross-platform, lowest-common-denominator sh
you use:
#!/bin/sh
value=`cat config.txt`
echo "$value"
In bash
or zsh
, to read a whole file into a variable without invoking cat
:
#!/bin/bash
value=$(<config.txt)
echo "$value"
Invoking cat
in bash
or zsh
to slurp a file would be considered a Useless Use of Cat.
Note that it is not necessary to quote the command substitution to preserve newlines.
See: Bash Hacker's Wiki - Command substitution - Specialities.
If you have other parameters in the query, beyond the IN list, then the following extension to JG's answer may be useful.
ids = [1, 5, 7, 213]
sql = "select * from person where type=%s and id in (%s)"
in_ids = ', '.join(map(lambda x: '%s', ids))
sql = sql % ('%s', in_ids)
params = []
params.append(type)
params.extend(ids)
cursor.execute(sql, tuple(params))
That is, join all the params in a linear array, then pass it as a tuple to the execute method.
Just use for x in f: ...
, this gives you line after line, is much shorter and readable (partly because it automatically stops when the file ends) and also saves you the rstrip
call because the trailing newline is already stipped.
The error is caused by the exit condition, which can never be true: Even if the file is exhausted, readline
will return an empty string, not None
. Also note that you could still run into trouble with empty lines, e.g. at the end of the file. Adding if line.strip() == "": continue
makes the code ignore blank lines, which is propably a good thing anyway.