Django provides it. You can use either:
{{ forloop.counter }}
index starts at 1.{{ forloop.counter0 }}
index starts at 0.In template, you can do:
{% for item in item_list %}
{{ forloop.counter }} # starting index 1
{{ forloop.counter0 }} # starting index 0
# do your stuff
{% endfor %}
More info at: for | Built-in template tags and filters | Django documentation
Others have pointed out that a get_FOO_display method is what you need. I'm using this:
def get_type(self):
return [i[1] for i in Item._meta.get_field('type').choices if i[0] == self.type][0]
which iterates over all of the choices that a particular item has until it finds the one that matches the items type
There are tricks like the one described by John; however, Django's template language by design does not support setting a variable (see the "Philosophy" box in Django documentation for templates).
Because of this, the recommended way to change any variable is via touching the Python code.
There's built-in solution for your problem: ModelChoiceField.
Generally, it's always worth trying to use ModelForm
when you need to create/change database objects. Works in 95% of the cases and it's much cleaner than creating your own implementation.
Now Update word-wrap is replace by :
overflow-wrap:break-word;
Compatible old navigator and css 3 it's good alternative !
it's evolution of word-wrap ( since 2012... )
See more information : https://www.w3.org/TR/css-text-3/#overflow-wrap
See compatibility full : http://caniuse.com/#search=overflow-wrap
Multiline comment in django templates use as follows ex: for .html etc.
{% comment %} All inside this tags are treated as comment {% endcomment %}
str()
is the equivalent.
However you should be filtering your query. At the moment your query is all()
Todo's.
todos = Todo.all().filter('author = ', users.get_current_user().nickname())
or
todos = Todo.all().filter('author = ', users.get_current_user())
depending on what you are defining author as in the Todo model. A StringProperty
or UserProperty
.
Note nickname
is a method. You are passing the method and not the result in template values.
You cannot call a function that requires arguments in a template. Write a template tag or filter instead.
Both {{ request.path }} and {{ request.get_full_path }}
return the current URL but not absolute URL, for example:
your_website.com/wallpapers/new_wallpaper
Both will return
/new_wallpaper/
(notice the leading and trailing slashes)
So you'll have to do something like
{% if request.path == '/new_wallpaper/' %}
<button>show this button only if url is new_wallpaper</button>
{% endif %}
However, you can get the absolute URL using (thanks to the answer above)
{{ request.build_absolute_uri }}
NOTE:
you don't have to include request
in settings.py
, it's already there.
Use the autoescape
to turn HTML escaping off:
{% autoescape off %}{{ message }}{% endautoescape %}
If using Django settings as installed, then why not just use its baked-in, predefined BASE_DIR and TEMPLATES? In the pip installed Django(v1.8), I get:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
### ADD YOUR DIRECTORY HERE LIKE SO:
BASE_DIR + '/templates/',
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
This approach shows how to use a class like django's ModelForm and a template tag like {{ form.as_table }}, but have all the table look like data output, not a form.
The first step was to subclass django's TextInput widget:
from django import forms
from django.utils.safestring import mark_safe
from django.forms.util import flatatt
class PlainText(forms.TextInput):
def render(self, name, value, attrs=None):
if value is None:
value = ''
final_attrs = self.build_attrs(attrs)
return mark_safe(u'<p %s>%s</p>' % (flatatt(final_attrs),value))
Then I subclassed django's ModelForm to swap out the default widgets for readonly versions:
from django.forms import ModelForm
class ReadOnlyModelForm(ModelForm):
def __init__(self,*args,**kwrds):
super(ReadOnlyModelForm,self).__init__(*args,**kwrds)
for field in self.fields:
if isinstance(self.fields[field].widget,forms.TextInput) or \
isinstance(self.fields[field].widget,forms.Textarea):
self.fields[field].widget=PlainText()
elif isinstance(self.fields[field].widget,forms.CheckboxInput):
self.fields[field].widget.attrs['disabled']="disabled"
Those were the only widgets I needed. But it should not be difficult to extend this idea to other widgets.
You can't pull in blocks from an included file into a child template to override the parent template's blocks. However, you can specify a parent in a variable and have the base template specified in the context.
From the documentation:
{% extends variable %} uses the value of variable. If the variable evaluates to a string, Django will use that string as the name of the parent template. If the variable evaluates to a Template object, Django will use that object as the parent template.
Instead of separate "page1.html" and "page2.html", put {% extends base_template %}
at the top of "commondata.html". And then in your view, define base_template
to be either "base1.html" or "base2.html".
I tried a few of the mentioned possibilities, and this is how I solved my problem:
#forms.py
class EditProfileForm(forms.ModelForm):
first_name = forms.CharField(label='First Name',
widget=forms.TextInput(
attrs={'class': 'form-control'}),
required=False)
last_name = forms.CharField(label='Last Name',
widget=forms.TextInput(
attrs={'class': 'form-control'}),
required=False)
# username = forms.CharField(widget=forms.TextInput(
# attrs={'class': 'form-control'}),
# required=True)
address = forms.CharField(max_length=255, widget=forms.TextInput(
attrs={'class': 'form-control'}),
required=False)
phoneNumber = forms.CharField(max_length=11,
widget=forms.TextInput(
attrs={'class': 'form-control'}),
required=False)
photo = forms.ImageField(label='Change Profile Image', required=False)
class Meta:
model = User
fields = ['photo', 'first_name', 'last_name', 'phoneNumber', 'address']
# 'username',
#views.py
def edit_user_profile(request, username):
user = request.user
username = User.objects.get(username=username)
user_extended_photo = UserExtended.objects.get(user=user.id)
form = EditProfileForm(request.POST or None, request.FILES, instance=user)
user_extended = UserExtended.objects.get(user=user)
if request.method == 'POST':
if form.is_valid():
# photo = UserExtended(photo=request.FILES['photo'] or None, )
user.first_name = request.POST['first_name']
user.last_name = request.POST['last_name']
user_extended.address = request.POST['address']
user_extended.phoneNumber = request.POST['phoneNumber']
user_extended.photo = form.cleaned_data["photo"]
# username = request.POST['username']
user_extended.save()
user.save()
context = {
'form': form,
'username': username,
'user_extended_photo': user_extended_photo,
}
return render(request, 'accounts/profile_updated.html', context)
else:
photo = user_extended.photo
first_name = user.first_name
last_name = user.last_name
address = user_extended.address
phoneNumber = user_extended.phoneNumber
form = EditProfileForm(
initial={'first_name': first_name, 'last_name': last_name,
'address': address, 'phoneNumber': phoneNumber,
'photo': photo})
context = {
'form': form,
'username': username,
'user_extended_photo': user_extended_photo,
}
return render_to_response('accounts/edit_profile.html', context,
context_instance=RequestContext(request))
#edit_profile.html
<form action="/accounts/{{ user.username }}/edit_profile/" method="post" enctype='multipart/form-data'>
{% csrf_token %}
<div class="col-md-6">
<div class="form-group">
{{ form.as_p }}
</div>
</div>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<button type="submit" value="Update Profile" class="btn btn-info btn-fill pull-right">Update Profile</button>
<div class="clearfix"></div>
</form>
I am trying to explain this in a way so that beginners may find it easier to understand. Pay close attention to the else:
photo = user_extended.photo
first_name = user.first_name
last_name = user.last_name
address = user_extended.address
phoneNumber = user_extended.phoneNumber
form = EditProfileForm(
initial={'first_name': first_name, 'last_name': last_name,
'address': address, 'phoneNumber': phoneNumber,
'photo': photo})
It is what gets the value attrib, e.g.:
<p><label for="id_first_name">First Name:</label> <input class="form-control" id="id_first_name" name="first_name" type="text" value="Emmanuel" /></p>
<p><label for="id_last_name">Last Name:</label> <input class="form-control" id="id_last_name" name="last_name" type="text" value="Castor" /></p>
A solution that worked for me is using the hidden input field in the template
<input type="hidden" id="myVar" name="variable" value="{{ variable }}">
Then getting the value in javascript this way,
var myVar = document.getElementById("myVar").value;
Another way to do it:
MEDIA_ROOT = '/home/USER/Projects/REPO/src/PROJECT/APP/static/media/'
MEDIA_URL = '/static/media/'
This would require you to move your media folder to a sub directory of a static folder.
Then in your template you can use:
<img class="scale-with-grid" src="{{object.photo.url}}"/>
For Django 2.2 up to 3, you have to load staticfiles in html template first before use static keyword
{% load staticfiles %}
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
For other versions use static
{% load static %}
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
Also you have to check that you defined STATIC_URL in setting.py
At last, make sure the static files exist in the defined folder
I just add an extra template tag like this:
@register.filter
def in_category(things, category):
return things.filter(category=category)
Then I can do:
{% for category in categories %}
{% for thing in things|in_category:category %}
{{ thing }}
{% endfor %}
{% endfor %}
Judging from your example, shouldn't it be {% url myproject.login.views.login_view %}
and end of story? (replace myproject
with your actual project name)
In my project I did it like this:
@register.simple_tag()
def format_string(string: str, *args: str) -> str:
"""
Adds [args] values to [string]
String format [string]: "Drew %s dad's %s dead."
Function call in template: {% format_string string "Dodd's" "dog's" %}
Result: "Drew Dodd's dad's dog's dead."
"""
return string % args
Here, the string you want concatenate and the args can come from the view, for example.
In template and using your case:
{% format_string 'shop/%s/base.html' shop_name as template %}
{% include template %}
The nice part is that format_string can be reused for any type of string formatting in templates
If we were to compare context vs. template tags on a single variable, then knowing the more efficient option could be benificial. However, you might be better off to dip into the settings only from templates that need that variable. In that case it doesn't make sense to pass the variable into all templates. But if you are sending the variable into a common template such as the base.html template, Then it would not matter as the base.html template is rendered on every request, so you can use either methods.
If you decide to go with the template tags option, then use the following code as it allows you to pass a default value in, just in case the variable in-question was undefined.
Example: get_from_settings my_variable as my_context_value
Example: get_from_settings my_variable my_default as my_context_value
class SettingsAttrNode(Node):
def __init__(self, variable, default, as_value):
self.variable = getattr(settings, variable, default)
self.cxtname = as_value
def render(self, context):
context[self.cxtname] = self.variable
return ''
def get_from_setting(parser, token):
as_value = variable = default = ''
bits = token.contents.split()
if len(bits) == 4 and bits[2] == 'as':
variable = bits[1]
as_value = bits[3]
elif len(bits) == 5 and bits[3] == 'as':
variable = bits[1]
default = bits[2]
as_value = bits[4]
else:
raise TemplateSyntaxError, "usage: get_from_settings variable default as value " \
"OR: get_from_settings variable as value"
return SettingsAttrNode(variable=variable, default=default, as_value=as_value)
get_from_setting = register.tag(get_from_setting)
{{ data.0 }}
should work.
Let's say you wrote data.obj
django tries data.obj
and data.obj()
. If they don't work it tries data["obj"]
. In your case data[0]
can be written as {{ data.0 }}
. But I recommend you to pull data[0]
in the view and send it as separate variable.
None, False and True
all are available within template tags and filters. None, False
, the empty string ('', "", """"""
) and empty lists/tuples all evaluate to False
when evaluated by if
, so you can easily do
{% if profile.user.first_name == None %}
{% if not profile.user.first_name %}
A hint: @fabiocerqueira is right, leave logic to models, limit templates to be the only presentation layer and calculate stuff like that in you model. An example:
# someapp/models.py
class UserProfile(models.Model):
user = models.OneToOneField('auth.User')
# other fields
def get_full_name(self):
if not self.user.first_name:
return
return ' '.join([self.user.first_name, self.user.last_name])
# template
{{ user.get_profile.get_full_name }}
Hope this helps :)
1: HTML
<tbody>
{% for ticket in tickets %}
<tr>
<td class="ticket_id">{{ticket.id}}</td>
<td class="ticket_eam">{{ticket.eam}}</td>
<td class="ticket_subject">{{ticket.subject}}</td>
<td>{{ticket.zone}}</td>
<td>{{ticket.plaza}}</td>
<td>{{ticket.lane}}</td>
<td>{{ticket.uptime}}</td>
<td>{{ticket.downtime}}</td>
<td><a href="{% url 'ticket_details' ticket_id=ticket.id %}"><button data-toggle="modal" data-target="#modaldemo3" class="value-modal"><i class="icon ion-edit"></a></i></button> <button><i class="fa fa-eye-slash"></i></button>
</tr>
{% endfor %}
</tbody>
The {% url 'ticket_details' %} is the function name in your views
2: Views.py
def ticket_details(request, ticket_id):
print(ticket_id)
return render(request, ticket.html)
ticket_id is the parameter you will get from the ticket_id=ticket.id
3: URL.py
urlpatterns = [
path('ticket_details/?P<int:ticket_id>/', views.ticket_details, name="ticket_details") ]
/?P - where ticket_id is the name of the group and pattern is some pattern to match.
A list is considered to be False
if it has no elements, so you can do something like this:
{% if mylist %}
<p>I have a list!</p>
{% else %}
<p>I don't have a list!</p>
{% endif %}
I think what you want is to have access to the request context, see RequestContext.
For template, you can use
{% firstof request.user.get_full_name request.user.username %}
firstof will return the first one if not null else the second one
If you pass a variable data
(dictionary type) as context to a template, then you code should be:
{% for key, value in data.items %}
<p>{{ key }} : {{ value }}</p>
{% endfor %}
{% url 'polls:create' poll.id %}
You try this.
I have already tried it in my django template.
It will work fine. Just remove the curly braces pair {{ and }} from {{source}}.
I have also added <table> tag and that's it.
After modification your code will look something like below.
{% for source in sources %}
<table>
<tr>
<td>{{ source }}</td>
<td>
{% if title == source %}
Just now!
{% endif %}
</td>
</tr>
</table>
{% endfor %}
My dictionary looks like below,
{'title':"Rishikesh", 'sources':["Hemkesh", "Malinikesh", "Rishikesh", "Sandeep", "Darshan", "Veeru", "Shwetabh"]}
and OUTPUT looked like below once my template got rendered.
Hemkesh
Malinikesh
Rishikesh Just now!
Sandeep
Darshan
Veeru
Shwetabh
Use Dictionary Items:
{% for key, value in my_dictionay.items %}
<li>{{ key }} : {{ value }}</li>
{% endfor %}
{{yourDate|date:'*Prefered Format*'}}
Example:
{{yourDate|date:'F d, Y'}}
For preferred format: https://docs.djangoproject.com/en/3.1/ref/templates/builtins/#date
From the page you referenced:
When you raise Http404 from within a view, Django will load a special view devoted to handling 404 errors. It finds it by looking for the variable handler404 in your root URLconf (and only in your root URLconf; setting handler404 anywhere else will have no effect), which is a string in Python dotted syntax – the same format the normal URLconf callbacks use. A 404 view itself has nothing special: It’s just a normal view.
So I believe you need to add something like this to your urls.py:
handler404 = 'views.my_404_view'
and similar for handler500.
There are 2 possible solutions that I personally use
1.without using form
<button type="submit" value={{excel_path}} onclick="location.href='{% url 'downloadexcel' %}'" name='mybtn2'>Download Excel file</button>
2.Using Form
<form action="{% url 'downloadexcel' %}" method="post">
{% csrf_token %}
<button type="submit" name='mybtn2' value={{excel_path}}>Download results in Excel</button>
</form>
Where urls.py should have this
path('excel/',views1.downloadexcel,name="downloadexcel"),
I have had this issue before, which I solved by nested if statements first checking for none type separately.
{% if object.some_bool == None %}Empty
{% else %}{% if not object.some_bool %}False{% else %}True{% endif %}{% endif %}
If you only want to test if its false, then just
{% if some_bool == None %}{% else %}{% if not some_bool %}False{% endif %}{% endif %}
EDIT: This seems to work.
{% if 0 == a|length %}Zero-length array{% else %}{% if a == None %}None type{% else %}{% if not a %}False type{% else %}True-type {% endif %}{% endif %}{% endif %}
Now zero-length arrays are recognized as such; None types as None types; falses as False; Trues as trues; strings/arrays above length 0 as true.
You could also include in the Context a variable false_list = [False,] and then do
{% if some_bool in false_list %}False {% endif %}
Unfortunately, that's not supported in the Django template language. There are a couple of suggestions, but they seem a little complex. I would just put a variable in the context:
...
render_to_response('foo.html', {..., 'range': range(10), ...}, ...)
...
and in the template:
{% for i in range %}
...
{% endfor %}
In case anybody is here and the other two solutions do not make the trick, check that what you are using to filter is what you expect:
user = UniversityDetails.objects.get(email=email)
is email a str
, or a None
? or an int
?
if you use android:scaleType="fitXY"
then you must specify
android:layout_width="75dp"
and android:layout_height="75dp"
if use wrap_content it will not stretch to what you need
<ImageView
android:layout_width="75dp"
android:layout_height="75dp"
android:id="@+id/listItemNoteImage"
android:src="@drawable/MyImage"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginStart="12dp"
android:scaleType="fitXY"/>
Here is a somewhat kludgy way to do it that works with GO-batches, by using a "global" variable.
if object_id('tempdb..#vars') is not null
begin
drop table #vars
end
create table #vars (continueScript bit)
set nocount on
insert #vars values (1)
set nocount off
-- Start of first batch
if ((select continueScript from #vars)=1) begin
print '1'
-- Conditionally terminate entire script
if (1=1) begin
set nocount on
update #vars set continueScript=0
set nocount off
return
end
end
go
-- Start of second batch
if ((select continueScript from #vars)=1) begin
print '2'
end
go
And here is the same idea used with a transaction and a try/catch block for each GO-batch. You can try to change the various conditions and/or let it generate an error (divide by 0, see comments) to test how it behaves:
if object_id('tempdb..#vars') is not null
begin
drop table #vars
end
create table #vars (continueScript bit)
set nocount on
insert #vars values (1)
set nocount off
begin transaction;
-- Batch 1 starts here
if ((select continueScript from #vars)=1) begin
begin try
print 'batch 1 starts'
if (1=0) begin
print 'Script is terminating because of special condition 1.'
set nocount on
update #vars set continueScript=0
set nocount off
return
end
print 'batch 1 in the middle of its progress'
if (1=0) begin
print 'Script is terminating because of special condition 2.'
set nocount on
update #vars set continueScript=0
set nocount off
return
end
set nocount on
-- use 1/0 to generate an exception here
select 1/1 as test
set nocount off
end try
begin catch
set nocount on
select
error_number() as errornumber
,error_severity() as errorseverity
,error_state() as errorstate
,error_procedure() as errorprocedure
,error_line() as errorline
,error_message() as errormessage;
print 'Script is terminating because of error.'
update #vars set continueScript=0
set nocount off
return
end catch;
end
go
-- Batch 2 starts here
if ((select continueScript from #vars)=1) begin
begin try
print 'batch 2 starts'
if (1=0) begin
print 'Script is terminating because of special condition 1.'
set nocount on
update #vars set continueScript=0
set nocount off
return
end
print 'batch 2 in the middle of its progress'
if (1=0) begin
print 'Script is terminating because of special condition 2.'
set nocount on
update #vars set continueScript=0
set nocount off
return
end
set nocount on
-- use 1/0 to generate an exception here
select 1/1 as test
set nocount off
end try
begin catch
set nocount on
select
error_number() as errornumber
,error_severity() as errorseverity
,error_state() as errorstate
,error_procedure() as errorprocedure
,error_line() as errorline
,error_message() as errormessage;
print 'Script is terminating because of error.'
update #vars set continueScript=0
set nocount off
return
end catch;
end
go
if @@trancount > 0 begin
if ((select continueScript from #vars)=1) begin
commit transaction
print 'transaction committed'
end else begin
rollback transaction;
print 'transaction rolled back'
end
end
To make the child element positioned absolutely from its parent element you need to set relative position on the parent element AND absolute position on the child element.
Then on the child element 'top' is relative to the height of the parent. So you also need to 'translate' upward the child 50% of its own height.
.base{_x000D_
background-color: green;_x000D_
width: 200px;_x000D_
height: 200px;_x000D_
overflow: auto;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.vert-align {_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
transform: translate(0, -50%);_x000D_
}
_x000D_
<div class="base">_x000D_
<div class="vert-align">_x000D_
Content Here_x000D_
</div>_x000D_
</div>
_x000D_
There is another a solution using flex box.
.base{_x000D_
background-color:green;_x000D_
width: 200px;_x000D_
height: 200px;_x000D_
overflow: auto;_x000D_
display: flex;_x000D_
align-items: center;_x000D_
}
_x000D_
<div class="base">_x000D_
<div class="vert-align">_x000D_
Content Here_x000D_
</div>_x000D_
</div>
_x000D_
You will find advantages/disavantages for both.
If you use Excel, then the command would be Find and MID. Here is what it would look like in Powershell.
$text = "asdfNAME=PC123456<>Diweursejsfdjiwr"
asdfNAME=PC123456<>Diweursejsfdjiwr - Randon line of text, we want PC123456
$text.IndexOf("E=")
7 - this is the "FIND" command for Powershell
$text.substring(10,5)
C1234 - this is the "MID" command for Powershell
$text.substring($text.IndexOf("E=")+2,8)
PC123456 - tada it has found and cut our text
-RavonTUS
It sounds like you have a problem with your dsn or odbc data source.
Try bypassing the dsn first and connect using:
TDSVER=8.0 tsql -S *serverIPAddress* -U *username* -P *password*
If that works, you know its an issue with your dsn or with freetds using your dsn. Also, it is possible that your tds version is not compatible with your server. You might want to try other TDSVER settings (5.0, 7.0, 7.1).
You can use both the $_SERVER['REQUEST_TIME']
variable or the time()
function. Both of these return a Unix timestamp.
Most of the time these two solutions will yield the exact same Unix Timestamp. The difference between these is that $_SERVER['REQUEST_TIME']
returns the time stamp of the most recent server request and time()
returns the current time. This may create minor differences in accuracy depending on your application, but for most cases both of these solutions should suffice.
Based on your example code above, you are going to want to format this information once you obtain the Unix Timestamp. Unformatted Unix time looks like: 1232659628
So in order to get something that will work, you can use the date()
function to format it.
A good reference for ways to use the date()
function is located in the PHP Manual.
As an example, the following code returns a date that looks like this: 01/22/2009 04:35:00 pm
:
echo date("m/d/Y h:i:s a", time());
To find the HSV value of Green, try following commands in Python terminal
green = np.uint8([[[0,255,0 ]]])
hsv_green = cv2.cvtColor(green,cv2.COLOR_BGR2HSV)
print hsv_green
[[[ 60 255 255]]]
VS2008 w/resharper 4.1 has correct typing in the tooltip when you hover over "var" so I think it should be able to find this when you look for all usages of a class.
Haven't yet tested that it does that yet though.
#!/usr/bin/python
import sys
col = int(sys.argv[1]) - 1
for line in sys.stdin:
columns = line.split()
try:
print(columns[col])
except IndexError:
# ignore
pass
Then, supposing you name the script as co, say, do something like this to get the sizes of files (the example assumes you're using Linux, but the script itself is OS-independent) :-
ls -lh | co 5
Try This,
private void button1_Click(object sender, EventArgs e)
{
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("[email protected]");
mail.To.Add("to_address");
mail.Subject = "Test Mail";
mail.Body = "This is for testing SMTP mail from GMAIL";
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
MessageBox.Show("mail Send");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Try this:
^.*(?=.{8,})(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])[a-zA-Z0-9@#$%^&+=]*$
This regular expression works for me perfectly.
function myFunction() {
var str = "c1TTTTaTTT@";
var patt = new RegExp("^.*(?=.{8,})(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])[a-zA-Z0-9@#$%^&+=]*$");
var res = patt.test(str);
console.log("Is regular matches:", res);
}
A short solution without libraries at all. :)
d = "8/16/18"
day_value = d[(d.find('/')+1):d.find('/18')]
tomorrow = f"{d[0:d.find('/')]}/{int(day_value)+1}{d[d.find('/18'):len(d)]}".format()
print(tomorrow)
# 8/17/18
Make sure that "string d" is actually in the form of %m/%d/%Y
so that you won't have problems transitioning from one month to the next.
I had the same problem and resolved it by
\eclipse\p2\org.eclipse.equinox.p2.repository\cache
UPDATE:
[o for d in [{}] for o in lst if o.name != "" or d.setdefault("", o) == o]
or using filter
and lambda
:
flag = {}
filter(lambda o: bool(o.name) or flag.setdefault("", o) == o, lst)
Previous Answer
OK, are you stuck on using filter and lambda?
It seems like this would be better served with a dictionary comprehension,
{o.name : o for o in input}.values()
I think the reason that Python doesn't allow assignment in a lambda is similar to why it doesn't allow assignment in a comprehension and that's got something to do with the fact that these things are evaluated on the C
side and thus can give us an increase in speed. At least that's my impression after reading one of Guido's essays.
My guess is this would also go against the philosophy of having one right way of doing any one thing in Python.
Microsoft Virtual WiFi Miniport
should start and bind automatically to the underlying function driver. Try disabling and reenabling the AR9285
driver.
Run these codes in thread or AsyncTask. In order to avoid duplicated callings of same _url(one time for getContentLength(), one time of openStream()), use IOUtils.toByteArray of Apache.
void downloadFile(String _url, String _name) {
try {
URL u = new URL(_url);
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = IOUtils.toByteArray(stream);
FileOutputStream fos = mContext.openFileOutput(_name, Context.MODE_PRIVATE);
fos.write(buffer);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
} catch (IOException e) {
e.printStackTrace();
return;
}
}
It may be as simple as LIKE '%%[%3]%%'
being [%3]
the input variable.
This works for me with SAP B1 9.1
No, what you are looking for would be called a parent selector. CSS has none; they have been proposed multiple times but I know of no existing or forthcoming standard including them. You are correct that you would need to use something like jQuery or use additional class annotations to achieve the effect you want.
Here are some similar questions with similar results:
Unless you have sudo permissions to change it or its in your own usergroup/account you will not be able to get into it.
Check out man chmod
in the terminal for more information about changing permissions of a directory.
Another alternative might be
Array.from(document.querySelectorAll("a")).map(x => x.href)
With your $$(
its even shorter
Array.from($$("a")).map(x => x.href)
JDK 5.0 does not allow you to use @Override
annotation if you are implementing method declared in interface (its compilation error), but JDK 6.0 allows it. So may be you can configure your project preference according to your requirement.
First off, if you want to extract count features and apply TF-IDF normalization and row-wise euclidean normalization you can do it in one operation with TfidfVectorizer
:
>>> from sklearn.feature_extraction.text import TfidfVectorizer
>>> from sklearn.datasets import fetch_20newsgroups
>>> twenty = fetch_20newsgroups()
>>> tfidf = TfidfVectorizer().fit_transform(twenty.data)
>>> tfidf
<11314x130088 sparse matrix of type '<type 'numpy.float64'>'
with 1787553 stored elements in Compressed Sparse Row format>
Now to find the cosine distances of one document (e.g. the first in the dataset) and all of the others you just need to compute the dot products of the first vector with all of the others as the tfidf vectors are already row-normalized.
As explained by Chris Clark in comments and here Cosine Similarity does not take into account the magnitude of the vectors. Row-normalised have a magnitude of 1 and so the Linear Kernel is sufficient to calculate the similarity values.
The scipy sparse matrix API is a bit weird (not as flexible as dense N-dimensional numpy arrays). To get the first vector you need to slice the matrix row-wise to get a submatrix with a single row:
>>> tfidf[0:1]
<1x130088 sparse matrix of type '<type 'numpy.float64'>'
with 89 stored elements in Compressed Sparse Row format>
scikit-learn already provides pairwise metrics (a.k.a. kernels in machine learning parlance) that work for both dense and sparse representations of vector collections. In this case we need a dot product that is also known as the linear kernel:
>>> from sklearn.metrics.pairwise import linear_kernel
>>> cosine_similarities = linear_kernel(tfidf[0:1], tfidf).flatten()
>>> cosine_similarities
array([ 1. , 0.04405952, 0.11016969, ..., 0.04433602,
0.04457106, 0.03293218])
Hence to find the top 5 related documents, we can use argsort
and some negative array slicing (most related documents have highest cosine similarity values, hence at the end of the sorted indices array):
>>> related_docs_indices = cosine_similarities.argsort()[:-5:-1]
>>> related_docs_indices
array([ 0, 958, 10576, 3277])
>>> cosine_similarities[related_docs_indices]
array([ 1. , 0.54967926, 0.32902194, 0.2825788 ])
The first result is a sanity check: we find the query document as the most similar document with a cosine similarity score of 1 which has the following text:
>>> print twenty.data[0]
From: [email protected] (where's my thing)
Subject: WHAT car is this!?
Nntp-Posting-Host: rac3.wam.umd.edu
Organization: University of Maryland, College Park
Lines: 15
I was wondering if anyone out there could enlighten me on this car I saw
the other day. It was a 2-door sports car, looked to be from the late 60s/
early 70s. It was called a Bricklin. The doors were really small. In addition,
the front bumper was separate from the rest of the body. This is
all I know. If anyone can tellme a model name, engine specs, years
of production, where this car is made, history, or whatever info you
have on this funky looking car, please e-mail.
Thanks,
- IL
---- brought to you by your neighborhood Lerxst ----
The second most similar document is a reply that quotes the original message hence has many common words:
>>> print twenty.data[958]
From: [email protected] (Robert Seymour)
Subject: Re: WHAT car is this!?
Article-I.D.: reed.1993Apr21.032905.29286
Reply-To: [email protected]
Organization: Reed College, Portland, OR
Lines: 26
In article <[email protected]> [email protected] (where's my
thing) writes:
>
> I was wondering if anyone out there could enlighten me on this car I saw
> the other day. It was a 2-door sports car, looked to be from the late 60s/
> early 70s. It was called a Bricklin. The doors were really small. In
addition,
> the front bumper was separate from the rest of the body. This is
> all I know. If anyone can tellme a model name, engine specs, years
> of production, where this car is made, history, or whatever info you
> have on this funky looking car, please e-mail.
Bricklins were manufactured in the 70s with engines from Ford. They are rather
odd looking with the encased front bumper. There aren't a lot of them around,
but Hemmings (Motor News) ususally has ten or so listed. Basically, they are a
performance Ford with new styling slapped on top.
> ---- brought to you by your neighborhood Lerxst ----
Rush fan?
--
Robert Seymour [email protected]
Physics and Philosophy, Reed College (NeXTmail accepted)
Artificial Life Project Reed College
Reed Solar Energy Project (SolTrain) Portland, OR
Rather than the command "python", consider launching Python via the py launcher, as described in sg7's answer, which by runs your latest version of Python (or lets you select a specific version). The py launcher is enabled via a check box during installation (default: "on").
Nevertheless, you can still put the "python" command in your PATH, either at "first installation" or by "modifying" an existing installation.
First Installation:
Checking the "[x] Add Python x.y to PATH" box on the very first dialog. Here's how it looks in version 3.8:
This has the effect of adding the following to the PATH
variable:
C:\Users\...\AppData\Local\Programs\Python\Python38-32\Scripts\
C:\Users\...\AppData\Local\Programs\Python\Python38-32\
Modifying an Existing Installation:
Re-run your installer (e.g. in Downloads, python-3.8.4.exe) and Select "Modify". Check all the optional features you want (likely no changes), then click [Next]. Check [x] "Add Python to environment variables", and [Install].
Yow can change the DropDownStyle in properties to DropDownList. This will not show the TextBox for filter.
(Screenshot provided by FUSION CHA0S.)
With pure HTML you can't influence this - every modern browser (= the user) has complete control over this behavior because it has been misused a lot in the past...
You can open a new window (HTML4) or a new browsing context (HTML5). Browsing context in modern browsers is mostly "new tab" instead of "new window". You have no influence on that, and you can't "force" modern browsers to open a new window.
In order to do this, use the anchor element's attribute target
[1]. The value you are looking for is _blank
[2].
<a href="www.example.com/example.html" target="_blank">link text</a>
Forcing a new window is possible via javascript - see Ievgen's excellent answer below for a javascript solution.
(!) However, be aware, that opening windows via javascript (if not done in the onclick event from an anchor element) are subject to getting blocked by popup blockers!
[1] This attribute dates back to the times when browsers did not have tabs and using framesets was state of the art. In the meantime, the functionality of this attribute has slightly changed (see MDN Docu)
[2] There are some other values which do not make much sense anymore (because they were designed with framesets in mind) like _parent
, _self
or _top
.
Quentin is correct, it can't be done with CSS. If you want to add a title
attribute, you can do it with JavaScript. Here's an example using jQuery:
$('label').attr('title','mandatory');
Neither of these options is correct. You're trying to implement a synchronous interface asynchronously. Don't do that. The problem is that when DoOperation()
returns, the operation won't be complete yet. Worse, if an exception happens during the operation (which is very common with IO operations), the user won't have a chance to deal with that exception.
What you need to do is to modify the interface, so that it is asynchronous:
interface IIO
{
Task DoOperationAsync(); // note: no async here
}
class IOImplementation : IIO
{
public async Task DoOperationAsync()
{
// perform the operation here
}
}
This way, the user will see that the operation is async
and they will be able to await
it. This also pretty much forces the users of your code to switch to async
, but that's unavoidable.
Also, I assume using StartNew()
in your implementation is just an example, you shouldn't need that to implement asynchronous IO. (And new Task()
is even worse, that won't even work, because you don't Start()
the Task
.)
Modulus, in modular arithmetic as you're referring, is the value left over or remaining value after arithmetic division. This is commonly known as remainder. % is formally the remainder operator in C / C++. Example:
7 % 3 = 1 // dividend % divisor = remainder
What's left for discussion is how to treat negative inputs to this % operation. Modern C and C++ produce a signed remainder value for this operation where the sign of the result always matches the dividend input without regard to the sign of the divisor input.
I also had the same issue. Tried most of the things found on this and other forums.
Finally was successful after doing a little own RnD.
I went into IIS Settings and then into my website permission options added my Organizations Domain User Group.
Now as all my domain user have been granted the access to that website i did not encounter that issue.
Hope this helps
String s = "prefix/dir1/dir2/dir3/dir4"
String parts[] = s.split("/");
System.out.println(s[0]); // "prefix"
System.out.println(s[1]); // "dir1"
...
What I did at the end was attach gdb to the process before it crashed, and then when it got the segfault I executed the generate-core-file
command. That forced generation of a core dump.
Let's start with the uncomfortable truth: GWT compiler performance is really lousy. You can use some hacks here and there, but you're not going to get significantly better performance.
A nice performance hack you can do is to compile for only specific browsers, by inserting the following line in your gwt.xml
:
<define-property name="user.agent" values="ie6,gecko,gecko1_8"></define-property>
or in gwt 2.x syntax, and for one browser only:
<set-property name="user.agent" value="gecko1_8"/>
This, for example, will compile your application for IE and FF only. If you know you are using only a specific browser for testing, you can use this little hack.
Another option: if you are using several locales, and again using only one for testing, you can comment them all out so that GWT will use the default locale, this shaves off some additional overhead from compile time.
Bottom line: you're not going to get order-of-magnitude increase in compiler performance, but taking several relaxations, you can shave off a few minutes here and there.
.md
stands for markdown and is generated at the bottom of your github page as html.
Typical syntax includes:
Will become a heading
==============
Will become a sub heading
--------------
*This will be Italic*
**This will be Bold**
- This will be a list item
- This will be a list item
Add a indent and this will end up as code
For more details: http://daringfireball.net/projects/markdown/
Run this
for (Method m : sex.class.getDeclaredMethods()) {
System.out.println(m);
}
you will see
public static test.Sex test.Sex.valueOf(java.lang.String)
public static test.Sex[] test.Sex.values()
These are all public methods that "sex" class has. They are not in the source code, javac.exe added them
Notes:
never use sex as a class name, it's difficult to read your code, we use Sex in Java
when facing a Java puzzle like this one, I recommend to use a bytecode decompiler tool (I use Andrey Loskutov's bytecode outline Eclispe plugin). This will show all what's inside a class
Try Following
Update A a, B b, SET a.column1=b.column1 where b.id=1
EDITED:- Update more than one column
Update A a, B b, SET a.column1=b.column1, a.column2=b.column2 where b.id=1
You can look for the four underscore in this way:
create table #test
( t varchar(50) );
insert into #test values
( 'abc_1_2_3_4.gif'),
('zzz_12_3_3_45.gif');
declare @t varchar(50);
declare @t_aux varchar(50);
declare @t1 int;
declare @t2 int;
declare @t3 int;
declare @t4 int;
DECLARE t_cursor CURSOR
FOR SELECT t FROM #test
OPEN t_cursor
FETCH NEXT FROM t_cursor into @t;?
set @t1 = charindex( '_', @t )
set @t2 = charindex( '_', @t , @t1+1)
set @t3 = charindex( '_', @t , @t2+1)
set @t4 = charindex( '_', @t , @t3+1)
select @t1, @t2, t3, t4
--do a loop to iterate over all table
you can test it here.
Or in this simple way:
select
charindex( '_', t ) as first,
charindex( '_', t, charindex( '_', t ) + 1 ) as second,
...
from
#test
Install a stable version instead of the latest one, I have downgrade my version to node-v0.10.29-x86.msi
from 'node-v0.10.33-x86.msi'
and it is working well for me!
Turns out that the post (or rather the whole table) was locked by the very same connection that I tried to update the post with.
I had a opened record set of the post that was created by:
Set RecSet = Conn.Execute()
This type of recordset is supposed to be read-only and when I was using MS Access as database it did not lock anything. But apparently this type of record set did lock something on MS SQL Server 2012 because when I added these lines of code before executing the UPDATE SQL statement...
RecSet.Close
Set RecSet = Nothing
...everything worked just fine.
So bottom line is to be careful with opened record sets - even if they are read-only they could lock your table from updates.
.crop {
overflow:hidden;
white-space:nowrap;
text-overflow:ellipsis;
width:100px;
}?
public void CreateCSVFile(DataTable dt, string strFilePath,string separator)
{
#region Export Grid to CSV
// Create the CSV file to which grid data will be exported.
StreamWriter sw = new StreamWriter(strFilePath, false);
int iColCount = dt.Columns.Count;
for (int i = 0; i < iColCount; i++)
{
sw.Write(dt.Columns[i]);
if (i < iColCount - 1)
{
sw.Write(separator);
}
}
sw.Write(sw.NewLine);
// Now write all the rows.
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
sw.Write(dr[i].ToString());
}
if (i < iColCount - 1)
{
sw.Write(separator);
}
}
sw.Write(sw.NewLine);
}
sw.Close();
#endregion
}
AES.
(I also am assuming you mean twofish not the much older and weaker blowfish)
Both (AES & twofish) are good algorithms. However even if they were equal or twofish was slightly ahead on technical merit I would STILL chose AES.
Why? Publicity. AES is THE standard for government encryption and thus millions of other entities also use it. A talented cryptanalyst simply gets more "bang for the buck" finding a flaw in AES then it does for the much less know and used twofish.
Obscurity provides no protection in encryption. More bodies looking, studying, probing, attacking an algorithm is always better. You want the most "vetted" algorithm possible and right now that is AES. If an algorithm isn't subject to intense and continual scrutiny you should place a lower confidence of it's strength. Sure twofish hasn't been compromised. Is that because of the strength of the cipher or simply because not enough people have taken a close look ..... YET
The first button is always the default; it can't be changed. Whilst you can try to fix it up with JavaScript, the form will behave unexpectedly in a browser without scripting, and there are some usability/accessibility corner cases to think about. For example, the code linked to by Zoran will accidentally submit the form on Enter press in a <input type="button">
, which wouldn't normally happen, and won't catch IE's behaviour of submitting the form for Enter press on other non-field content in the form. So if you click on some text in a <p>
in the form with that script and press Enter, the wrong button will be submitted... especially dangerous if, as given in that example, the real default button is ‘Delete’!
My advice would be to forget about using scripting hacks to reassign defaultness. Go with the flow of the browser and just put the default button first. If you can't hack the layout to give you the on-screen order you want, then you can do it by having a dummy invisible button first in the source, with the same name/value as the button you want to be default:
<input type="submit" class="defaultsink" name="COMMAND" value="Save" />
.defaultsink {
position: absolute; left: -100%;
}
(note: positioning is used to push the button off-screen because display: none
and visibility: hidden
have browser-variable side-effects on whether the button is taken as default and whether it's submitted.)
Try something like this - it works for the cases you have mentioned.
select * from tbl
where answer like '%[0-9]%'
and answer not like '%[:]%'
and answer not like '%[A-Z]%'
Just do npm update
and then npm install gulp-sass --save-dev
in your root folder, and then when you run you shouldn't have any issues.
'So from this discussion i am thinking this should be the code then.
Sub Button1_Click()
Dim excel As excel.Application
Dim wb As excel.Workbook
Dim sht As excel.Worksheet
Dim f As Object
Set f = Application.FileDialog(3)
f.AllowMultiSelect = False
f.Show
Set excel = CreateObject("excel.Application")
Set wb = excel.Workbooks.Open(f.SelectedItems(1))
Set sht = wb.Worksheets("Data")
sht.Activate
sht.Columns("A:G").Copy
Range("A1").PasteSpecial Paste:=xlPasteValues
wb.Close
End Sub
'Let me know if this is correct or a step was missed. Thx.
It is important to be specific about what exception you're trying to catch when using a try/except block.
string = "abcd"
try:
string_int = int(string)
print(string_int)
except ValueError:
# Handle the exception
print('Please enter an integer')
Try/Excepts are powerful because if something can fail in a number of different ways, you can specify how you want the program to react in each fail case.
in this scenario:
DELETE FROM tableA
WHERE (SELECT q.entitynum
FROM tableA q
INNER JOIN tableB u on (u.qlabel = q.entityrole AND u.fieldnum = q.fieldnum)
WHERE (LENGTH(q.memotext) NOT IN (8,9,10)
OR q.memotext NOT LIKE '%/%/%')
AND (u.FldFormat = 'Date'));
aren't you missing the column you want to compare to? example:
DELETE FROM tableA
WHERE entitynum in (SELECT q.entitynum
FROM tableA q
INNER JOIN tableB u on (u.qlabel = q.entityrole AND u.fieldnum = q.fieldnum)
WHERE (LENGTH(q.memotext) NOT IN (8,9,10)
OR q.memotext NOT LIKE '%/%/%')
AND (u.FldFormat = 'Date'));
I assume it's that column since in your select statement you're selecting from the same table you're wanting to delete from with that column.
//but i cannot really get the id and assign it to an array that is not with in the scope?(or can I)
Yes, you can!
var IDs = [];
$("#mydiv").find("span").each(function(){ IDs.push(this.id); });
This is the beauty of closures.
Note that while you were on the right track, sighohwell and cletus both point out more reliable and concise ways of accomplishing this, taking advantage of attribute filters (to limit matched elements to those with IDs) and jQuery's built-in map()
function:
var IDs = $("#mydiv span[id]") // find spans with ID attribute
.map(function() { return this.id; }) // convert to set of IDs
.get(); // convert to instance of Array (optional)
One of the best answer I know of for this question comes from user zAy0LfpBZLC8mAC at Hacker News. This answer is so good I'm just going to quote it as-is.
TCP has head-of-queue blocking, as it guarantees complete and in-order delivery, so when a packet gets lost in transit, it has to wait for a retransmit of the missing packet, whereas UDP delivers packets to the application as they arrive, including duplicates and without any guarantee that a packet arrives at all or which order they arrive (it really is essentially IP with port numbers and an (optional) payload checksum added), but that is fine for telephony, for example, where it usually simply doesn't matter when a few milliseconds of audio are missing, but delay is very annoying, so you don't bother with retransmits, you just drop any duplicates, sort reordered packets into the right order for a few hundred milliseconds of jitter buffer, and if packets don't show up in time or at all, they are simply skipped, possible interpolated where supported by the codec.
Also, a major part of TCP is flow control, to make sure you get as much througput as possible, but without overloading the network (which is kinda redundant, as an overloaded network will drop your packets, which means you'd have to do retransmits, which hurts throughput), UDP doesn't have any of that - which makes sense for applications like telephony, as telephony with a given codec needs a certain amount of bandwidth, you can not "slow it down", and additional bandwidth also doesn't make the call go faster.
In addition to realtime/low latency applications, UDP makes sense for really small transactions, such as DNS lookups, simply because it doesn't have the TCP connection establishment and teardown overhead, both in terms of latency and in terms of bandwidth use. If your request is smaller than a typical MTU and the repsonse probably is, too, you can be done in one roundtrip, with no need to keep any state at the server, and flow control als ordering and all that probably isn't particularly useful for such uses either.
And then, you can use UDP to build your own TCP replacements, of course, but it's probably not a good idea without some deep understanding of network dynamics, modern TCP algorithms are pretty sophisticated.
Also, I guess it should be mentioned that there is more than UDP and TCP, such as SCTP and DCCP. The only problem currently is that the (IPv4) internet is full of NAT gateways which make it impossible to use protocols other than UDP and TCP in end-user applications.
View.GONE makes the view invisible without the view taking up space in the layout. View.INVISIBLE makes the view just invisible still taking up space.
You are first using GONE and then INVISIBLE on the same view.Since, the code is executed sequentially, first the view becomes GONE then it is overridden by the INVISIBLE type still taking up space.
You should add button listener on the button and inside the onClick() method make the views visible. This should be the logic according to me in your onCreate() method.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting);
final DatePicker dp2 = (DatePicker) findViewById(R.id.datePick2);
final Button btn2 = (Button) findViewById(R.id.btnDate2);
final Button btn3 = (Button) findViewById(R.id.btnVisibility);
dp2.setVisibility(View.INVISIBLE);
btn2.setVisibility(View.INVISIBLE);
bt3.setOnClickListener(new View.OnCLickListener(){
@Override
public void onClick(View view)
{
dp2.setVisibility(View.VISIBLE);
bt2.setVisibility(View.VISIBLE);
}
});
}
I think this should work easily. Hope this helps.
With this solution, you probably can resolve all mobile clicks problems. Use only "click" function, but add z-index:99 to the element in css:
$("#test").on('click', function(){_x000D_
alert("CLICKED!")_x000D_
});
_x000D_
#test{ _x000D_
z-index:99;_x000D_
cursor:pointer;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>_x000D_
_x000D_
<div id="test">CLICK ME</div>
_x000D_
Credit:https://foundation.zurb.com/forum/posts/3258-buttons-not-clickable-on-iphone
I will throw in what worked for me in the end. I needed to remove the initial commit on a repository as quarantined data had been misplaced, the commit had already been pushed.
Make sure you are are currently on the right branch.
git checkout master
git update-ref -d HEAD
git commit -m "Initial commit
git push -u origin master
This was able to resolve the problem.
Important
This was on an internal repository which was not publicly accessible, if your repository was publicly accessible please assume anything you need to revert has already been pulled down by someone else.
This blog explains your problem neatly Async Best Practices.
The gist of it being you shouldn't use void as return for an async method, unless it's an async event handler, this is bad practice because it doesn't allow exceptions to be caught ;-).
Best practice would be to change the return type to Task. Also, try to code async all the way trough, make every async method call and be called from async methods. Except for a Main method in a console, which can't be async (before C# 7.1).
You will run into deadlocks with GUI and ASP.NET applications if you ignore this best practice. The deadlock occurs because these applications runs on a context that allows only one thread and won't relinquish it to the async thread. This means the GUI waits synchronously for a return, while the async method waits for the context: deadlock.
This behaviour won't happen in a console application, because it runs on context with a thread pool. The async method will return on another thread which will be scheduled. This is why a test console app will work, but the same calls will deadlock in other applications...
I have worked around for a while, all you need to do is open VirtualBox,
File > Preferences / Network > Host-Only Networks
You will see VirtualBox Host-Only Ethernet Adapter
click on it, and edit.
My IP settings for vagrant VM was 192.168.10.10, you should edit up to your VM IP
Here is my adapter settings;
IF
is a PL/SQL construct. If you are executing a query, you are using SQL not PL/SQL.
In SQL, you can use a CASE
statement in the query itself
SELECT DISTINCT a.item,
(CASE WHEN b.salesman = 'VIKKIE'
THEN 'ICKY'
ELSE b.salesman
END),
NVL(a.manufacturer,'Not Set') Manufacturer
FROM inv_items a,
arv_sales b
WHERE a.co = '100'
AND a.co = b.co
AND A.ITEM_KEY = b.item_key
AND a.item LIKE 'BX%'
AND b.salesman in ('01','15')
AND trans_date BETWEEN to_date('010113','mmddrr')
and to_date('011713','mmddrr')
ORDER BY a.item
Since you aren't doing any aggregation, you don't want a GROUP BY
in your query. Are you really sure that you need the DISTINCT
? People often throw that in haphazardly or add it when they are missing a join condition rather than considering whether it is really necessary to do the extra work to identify and remove duplicates.
Shouldn't it be just the .list-group
? See below,
<ul class="list-group">
<li class="list-group-item active">Cras justo odio</li>
<li class="list-group-item">Dapibus ac facilisis in</li>
<li class="list-group-item">Morbi leo risus</li>
<li class="list-group-item">Porta ac consectetur ac</li>
<li class="list-group-item">Vestibulum at eros</li>
</ul>
Reference: Bootstrap 4 Basic Example of a List group
If you don't mind including the underscore as an allowed character, you could try simply:
result = subject.replace(/\W+/g, "");
If the underscore must be excluded also, then
result = subject.replace(/[^A-Z0-9]+/ig, "");
(Note the case insensitive flag)
codaddict has provided the right answer. As for what you've tried, I'll explain why they don't make the cut:
[0-9]{1,45}
is almost there, however it matches a 1-to-45-digit string even if it occurs within another longer string containing other characters. Hence you need ^
and $
to restrict it to an exact match.
^[0-9]{45}*$
matches an exactly-45-digit string, repeated 0 or any number of times (*
). That means the length of the string can only be 0 or a multiple of 45 (90, 135, 180...).
You can further modify the hput()/hget() interface so that you have named hashes as follows:
hput() {
eval "$1""$2"='$3'
}
hget() {
eval echo '${'"$1$2"'#hash}'
}
and then
hput capitals France Paris
hput capitals Netherlands Amsterdam
hput capitals Spain Madrid
echo `hget capitals France` and `hget capitals Netherlands` and `hget capitals Spain`
This lets you define other maps that don't conflict (e.g., 'rcapitals' which does country lookup by capital city). But, either way, I think you'll find that this is all pretty terrible, performance-wise.
If you really want fast hash lookup, there's a terrible, terrible hack that actually works really well. It is this: write your key/values out to a temporary file, one-per line, then use 'grep "^$key"' to get them out, using pipes with cut or awk or sed or whatever to retrieve the values.
Like I said, it sounds terrible, and it sounds like it ought to be slow and do all sorts of unnecessary IO, but in practice it is very fast (disk cache is awesome, ain't it?), even for very large hash tables. You have to enforce key uniqueness yourself, etc. Even if you only have a few hundred entries, the output file/grep combo is going to be quite a bit faster - in my experience several times faster. It also eats less memory.
Here's one way to do it:
hinit() {
rm -f /tmp/hashmap.$1
}
hput() {
echo "$2 $3" >> /tmp/hashmap.$1
}
hget() {
grep "^$2 " /tmp/hashmap.$1 | awk '{ print $2 };'
}
hinit capitals
hput capitals France Paris
hput capitals Netherlands Amsterdam
hput capitals Spain Madrid
echo `hget capitals France` and `hget capitals Netherlands` and `hget capitals Spain`
To complete André's answer, an ant solution could be like the one described in Emacs, JDEE, Ant, and the Eclipse Java Compiler, as in:
<javac
srcdir="${src}"
destdir="${build.dir}/classes">
<compilerarg
compiler="org.eclipse.jdt.core.JDTCompilerAdapter"
line="-warn:+unused -Xemacs"/>
<classpath refid="compile.classpath" />
</javac>
The compilerarg element also allows you to pass in additional command line args to the eclipse compiler.
You can find a full ant script example here which would be invoked in a command line with:
java -cp C:/eclipse-SDK-3.4-win32/eclipse/plugins/org.eclipse.equinox.launcher_1.0.100.v20080509-1800.jar org.eclipse.core.launcher.Main -data "C:\Documents and Settings\Administrator\workspace" -application org.eclipse.ant.core.antRunner -buildfile build.xml -verbose
BUT all that involves ant, which is not what Keith is after.
For a batch compilation, please refer to Compiling Java code, especially the section "Using the batch compiler"
The batch compiler class is located in the JDT Core plug-in. The name of the class is org.eclipse.jdt.compiler.batch.BatchCompiler. It is packaged into plugins/org.eclipse.jdt.core_3.4.0..jar. Since 3.2, it is also available as a separate download. The name of the file is ecj.jar.
Since 3.3, this jar also contains the support for jsr199 (Compiler API) and the support for jsr269 (Annotation processing). In order to use the annotations processing support, a 1.6 VM is required.
Running the batch compiler From the command line would give
java -jar org.eclipse.jdt.core_3.4.0<qualifier>.jar -classpath rt.jar A.java
or:
java -jar ecj.jar -classpath rt.jar A.java
All java compilation options are detailed in that section as well.
The difference with the Visual Studio command line compilation feature is that Eclipse does not seem to directly read its .project and .classpath in a command-line argument. You have to report all information contained in the .project and .classpath in various command-line options in order to achieve the very same compilation result.
So, then short answer is: "yes, Eclipse kind of does." ;)
A File object in Java is a representation of a path to a directory or file, not the file itself. You don't need to have write access to the filesystem to create a File
object, you only need it if you intend to actually write to the file (using a FileOutputStream for example)
To give a little more flexibility I would add the next function to my repository:
public function findByNot($field, $value)
{
$qb = $this->createQueryBuilder('a');
$qb->where($qb->expr()->not($qb->expr()->eq('a.'.$field, '?1')));
$qb->setParameter(1, $value);
return $qb->getQuery()
->getResult();
}
Then, I could call it in my controller like this:
$this->getDoctrine()->getRepository('MyBundle:Image')->findByNot('id', 1);
SELECT id FROM TAG_TABLE WHERE 'aaaaaaaa' LIKE '%' || "tag_name" || '%';
tag_name
should be in quotation otherwise it will give error as tag_name doest not exist
redux-loop takes a cue from Elm and provides this pattern.
The best way according to me is to use the Moment.js isValid() method by specifying the format and use strict parsing.
As moment.js documentation says
As of version 2.3.0, you may specify a boolean for the last argument to make Moment use strict parsing. Strict parsing requires that the format and input match exactly, including delimiters.
value = '2020-05-25';
format = 'YYYY-MM-DD';
moment(value, format, true).isValid() // true
Workaround (not a clean, nice (or even working! see comments) solution):
Disable his credentials one time.
You can move your HTTP authentication logic to PHP by sending the appropriate headers (if not logged in):
Header('WWW-Authenticate: Basic realm="protected area"');
Header('HTTP/1.0 401 Unauthorized');
And parsing the input with:
$_SERVER['PHP_AUTH_USER'] // httpauth-user
$_SERVER['PHP_AUTH_PW'] // httpauth-password
So disabling his credentials one time should be trivial.
You have to manage your back button pressed action on your main Activity because your main Activity is container for your fragment.
First, add your all fragment to transaction.addToBackStack(null) and now navigation back button call will be going on main activity. I hope following code will help you...
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
you can also use
Fragment fragment =fragmentManager.findFragmentByTag(Constant.TAG);
if(fragment!=null) {
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.remove(fragment).commit();
}
And to change the title according to fragment name from fragment you can use the following code:
activity.getSupportActionBar().setTitle("Keyword Report Detail");
In v2.0 of the Graph API, calling /me/friends
returns the person's friends who also use the app.
In addition, in v2.0, you must request the user_friends
permission from each user. user_friends
is no longer included by default in every login. Each user must grant the user_friends
permission in order to appear in the response to /me/friends
. See the Facebook upgrade guide for more detailed information, or review the summary below.
The /me/friendlists
endpoint and user_friendlists
permission are not what you're after. This endpoint does not return the users friends - its lets you access the lists a person has made to organize their friends. It does not return the friends in each of these lists. This API and permission is useful to allow you to render a custom privacy selector when giving people the opportunity to publish back to Facebook.
If you want to access a list of non-app-using friends, there are two options:
If you want to let your people tag their friends in stories that they publish to Facebook using your App, you can use the /me/taggable_friends
API. Use of this endpoint requires review by Facebook and should only be used for the case where you're rendering a list of friends in order to let the user tag them in a post.
If your App is a Game AND your Game supports Facebook Canvas, you can use the /me/invitable_friends
endpoint in order to render a custom invite dialog, then pass the tokens returned by this API to the standard Requests Dialog.
In other cases, apps are no longer able to retrieve the full list of a user's friends (only those friends who have specifically authorized your app using the user_friends
permission).
For apps wanting allow people to invite friends to use an app, you can still use the Send Dialog on Web or the new Message Dialog on iOS and Android.
I followed around five different answers as well as all the blog posts in the previous answers and still had problems. I was trying to add a listener to some existing code that was tracing using the TraceSource.TraceEvent(TraceEventType, Int32, String)
method where the TraceSource
object was initialised with a string making it a 'named source'.
For me the issue was not creating a valid combination of source and switch elements to target this source. Here is an example that will log to a file called tracelog.txt
. For the following code:
TraceSource source = new TraceSource("sourceName");
source.TraceEvent(TraceEventType.Verbose, 1, "Trace message");
I successfully managed to log with the following diagnostics configuration:
<system.diagnostics>
<sources>
<source name="sourceName" switchName="switchName">
<listeners>
<add
name="textWriterTraceListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="tracelog.txt" />
</listeners>
</source>
</sources>
<switches>
<add name="switchName" value="Verbose" />
</switches>
</system.diagnostics>
Use JSON.stringify() to wrap your json
var parameter = JSON.stringify({type:"user", username:user_email, password:user_password});
$http.post(url, parameter).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
console.log(data);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
PHP 7 is already worked on such memory management issues and its reduced up-to minimal usage.
<?php
$start = microtime(true);
for ($i = 0; $i < 10000000; $i++) {
$a = 'a';
$a = NULL;
}
$elapsed = microtime(true) - $start;
echo "took $elapsed seconds\r\n";
$start = microtime(true);
for ($i = 0; $i < 10000000; $i++) {
$a = 'a';
unset($a);
}
$elapsed = microtime(true) - $start;
echo "took $elapsed seconds\r\n";
?>
PHP 7.1 Outpu:
took 0.16778993606567 seconds took 0.16630101203918 seconds
In my situation, some problems happened with my node package. So I run npm audit fix
and it fixed all problems
ES6 & without mutation: (October 2016)
const removeByIndex = (list, index) =>_x000D_
[_x000D_
...list.slice(0, index),_x000D_
...list.slice(index + 1)_x000D_
];_x000D_
_x000D_
output = removeByIndex([33,22,11,44],1) //=> [33,11,44]_x000D_
_x000D_
console.log(output)
_x000D_
Use preg_grep
$array = preg_grep(
'/(my\n+string\n+)/i',
array( 'file' , 'my string => name', 'this')
);
First make sure you have SessionMiddleware
and AuthenticationMiddleware
middlewares added to your MIDDLEWARE_CLASSES
setting.
The current user
is in request
object, you can get it by:
def sample_view(request):
current_user = request.user
print current_user.id
request.user
will give you a User
object representing the currently logged-in user. If a user isn't currently logged in, request.user
will be set to an instance of AnonymousUser
. You can tell them apart with the field is_authenticated
, like so:
if request.user.is_authenticated:
# Do something for authenticated users.
else:
# Do something for anonymous users.
Since you've already received help on the query, I'll take a poke at your syntax question:
The first query employs some lesser-known ANSI SQL syntax which allows you to nest joins between the join
and on
clauses. This allows you to scope/tier your joins and probably opens up a host of other evil, arcane things.
Now, while a nested join cannot refer any higher in the join hierarchy than its immediate parent, joins above it or outside of its branch can refer to it... which is precisely what this ugly little guy is doing:
select
count(*)
from Table1 as t1
join Table2 as t2
join Table3 as t3
on t2.Key = t3.Key -- join #1
and t2.Key2 = t3.Key2
on t1.DifferentKey = t3.DifferentKey -- join #2
This looks a little confusing because join #2 is joining t1 to t2 without specifically referencing t2... however, it references t2 indirectly via t3 -as t3 is joined to t2 in join #1. While that may work, you may find the following a bit more (visually) linear and appealing:
select
count(*)
from Table1 as t1
join Table3 as t3
join Table2 as t2
on t2.Key = t3.Key -- join #1
and t2.Key2 = t3.Key2
on t1.DifferentKey = t3.DifferentKey -- join #2
Personally, I've found that nesting in this fashion keeps my statements tidy by outlining each tier of the relationship hierarchy. As a side note, you don't need to specify inner. join is implicitly inner unless explicitly marked otherwise.
The good news is a transaction in SQL Server can span multiple batches (each exec
is treated as a separate batch.)
You can wrap your EXEC
statements in a BEGIN TRANSACTION
and COMMIT
but you'll need to go a step further and rollback if any errors occur.
Ideally you'd want something like this:
BEGIN TRY
BEGIN TRANSACTION
exec( @sqlHeader)
exec(@sqlTotals)
exec(@sqlLine)
COMMIT
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK
END CATCH
The BEGIN TRANSACTION
and COMMIT
I believe you are already familiar with. The BEGIN TRY
and BEGIN CATCH
blocks are basically there to catch and handle any errors that occur. If any of your EXEC
statements raise an error, the code execution will jump to the CATCH
block.
Your existing SQL building code should be outside the transaction (above) as you always want to keep your transactions as short as possible.
try something like this:
a = buffer[3];
a = a*256 + buffer[2];
a = a*256 + buffer[1];
a = a*256 + buffer[0];
this is assuming that the lowest byte comes first. if the highest byte comes first you might have to swap the indices (go from 0 to 3).
basically for each byte you want to add, you first multiply a by 256 (which equals a shift to the left by 8 bits) and then add the new byte.
ES6 one liner (if we can call it that way seeing the long line)
[...new URLSearchParams(location.search).entries()].reduce((prev, [key,val]) => {prev[key] = val; return prev}, {})
Easy way to get the column name
Sub column()
cell=cells(1,1)
column = Replace(cell.Address(False, False), cell.Row, "")
msgbox column
End Sub
I hope it helps =)
Hashicorp's https://github.com/mitchellh/mapstructure library does this out of the box:
import "github.com/mitchellh/mapstructure"
mapstructure.Decode(myData, &result)
The second result
parameter has to be an address of the struct.
Time for a due update.
First off, the deprecated list with the API in which it was deprecated:
configuration.locale
(API 17)updateConfiguration(configuration, displaymetrics)
(API 17)The thing no question answered recently has gotten right is the usage of the new method.
createConfigurationContext is the new method for updateConfiguration.
Some have used it standalone like this:
Configuration overrideConfiguration = ctx.getResources().getConfiguration();
Locale locale = new Locale("en_US");
overrideConfiguration.setLocale(locale);
createConfigurationContext(overrideConfiguration);
... but that doesn't work. Why? The method returns a context, which then is used to handle Strings.xml translations and other localized resources (images, layouts, whatever).
The proper usage is like this:
Configuration overrideConfiguration = ctx.getResources().getConfiguration();
Locale locale = new Locale("en_US");
overrideConfiguration.setLocale(locale);
//the configuration can be used for other stuff as well
Context context = createConfigurationContext(overrideConfiguration);
Resources resources = context.getResources();
If you just copy-pasted that into your IDE, you may see a warning that the API requires you targeting API 17 or above. This can be worked around by putting it in a method and adding the annotation @TargetApi(17)
But wait. What about the older API's?
You need to create another method using updateConfiguration without the TargetApi annotation.
Resources res = YourApplication.getInstance().getResources();
// Change locale settings in the app.
DisplayMetrics dm = res.getDisplayMetrics();
android.content.res.Configuration conf = res.getConfiguration();
conf.locale = new Locale("th");
res.updateConfiguration(conf, dm);
You don't need to return a context here.
Now, managing these can be difficult. In API 17+ you need the context created (or the resources from the context created) to get the appropriate resources based on localization. How do you handle this?
Well, this is the way I do it:
/**
* Full locale list: https://stackoverflow.com/questions/7973023/what-is-the-list-of-supported-languages-locales-on-android
* @param lang language code (e.g. en_US)
* @return the context
* PLEASE READ: This method can be changed for usage outside an Activity. Simply add a COntext to the arguments
*/
public Context setLanguage(String lang/*, Context c*/){
Context c = AndroidLauncher.this;//remove if the context argument is passed. This is a utility line, can be removed totally by replacing calls to c with the activity (if argument Context isn't passed)
int API = Build.VERSION.SDK_INT;
if(API >= 17){
return setLanguage17(lang, c);
}else{
return setLanguageLegacy(lang, c);
}
}
/**
* Set language for API 17
* @param lang
* @param c
* @return
*/
@TargetApi(17)
public Context setLanguage17(String lang, Context c){
Configuration overrideConfiguration = c.getResources().getConfiguration();
Locale locale = new Locale(lang);
Locale.setDefault(locale);
overrideConfiguration.setLocale(locale);
//the configuration can be used for other stuff as well
Context context = createConfigurationContext(overrideConfiguration);//"local variable is redundant" if the below line is uncommented, it is needed
//Resources resources = context.getResources();//If you want to pass the resources instead of a Context, uncomment this line and put it somewhere useful
return context;
}
public Context setLanguageLegacy(String lang, Context c){
Resources res = c.getResources();
// Change locale settings in the app.
DisplayMetrics dm = res.getDisplayMetrics();//Utility line
android.content.res.Configuration conf = res.getConfiguration();
conf.locale = new Locale(lang);//setLocale requires API 17+ - just like createConfigurationContext
Locale.setDefault(conf.locale);
res.updateConfiguration(conf, dm);
//Using this method you don't need to modify the Context itself. Setting it at the start of the app is enough. As you
//target both API's though, you want to return the context as you have no clue what is called. Now you can use the Context
//supplied for both things
return c;
}
This code works by having one method that makes calls to the appropriate method based on what API. This is something I have done with a lot of different deprecated calls (including Html.fromHtml). You have one method that takes in the arguments needed, which then splits it into one of two (or three or more) methods and returns the appropriate result based on API level. It is flexible as you do't have to check multiple times, the "entry" method does it for you. The entry-method here is setLanguage
PLEASE READ THIS BEFORE USING IT
You need to use the Context returned when you get resources. Why? I have seen other answers here who use createConfigurationContext and doesn't use the context it returns. To get it to work like that, updateConfiguration has to be called. Which is deprecated. Use the context returned by the method to get resources.
Example usage:
Constructor or somewhere similar:
ctx = getLanguage(lang);//lang is loaded or generated. How you get the String lang is not something this answer handles (nor will handle in the future)
And then, whereever you want to get resources you do:
String fromResources = ctx.getString(R.string.helloworld);
Using any other context will (in theory) break this.
AFAIK you still have to use an activity context to show dialogs or Toasts. for that you can use an instance of an activity (if you are outside)
And finally, use recreate()
on the activity to refresh the content. Shortcut to not have to create an intent to refresh.
I had the same problem. I lost hours, then I saw that version of node.js installed was 0.8. But I downloaded and installed version 0.10 from node.js website.
I downloaded and installed again, and now version is 0.10. Result: PhoneGap has been sucessfully installed with this version.
Add a
-webkit-animation-play-state: paused;
to your CSS file, then you can control whether the animation is running or not by using this JS line:
document.getElementById("myDIV").style.WebkitAnimationPlayState = "running";
if you want the animation to run once, every time you click. Remember to set
-webkit-animation-iteration-count: 1;
If you are supporting IE9+ the you can use the following. The same concept is incorporated in You Might Not Need jQuery.
function addEventListener(el, eventName, handler) {_x000D_
if (el.addEventListener) {_x000D_
el.addEventListener(eventName, handler);_x000D_
} else {_x000D_
el.attachEvent('on' + eventName, function() {_x000D_
handler.call(el);_x000D_
});_x000D_
}_x000D_
}_x000D_
_x000D_
function triggerEvent(el, eventName, options) {_x000D_
var event;_x000D_
if (window.CustomEvent) {_x000D_
event = new CustomEvent(eventName, options);_x000D_
} else {_x000D_
event = document.createEvent('CustomEvent');_x000D_
event.initCustomEvent(eventName, true, true, options);_x000D_
}_x000D_
el.dispatchEvent(event);_x000D_
}_x000D_
_x000D_
// Add an event listener._x000D_
addEventListener(document, 'customChangeEvent', function(e) {_x000D_
document.body.innerHTML = e.detail;_x000D_
});_x000D_
_x000D_
// Trigger the event._x000D_
triggerEvent(document, 'customChangeEvent', {_x000D_
detail: 'Display on trigger...'_x000D_
});
_x000D_
If you are already using jQuery, here is the jQuery version of the code above.
$(function() {_x000D_
// Add an event listener._x000D_
$(document).on('customChangeEvent', function(e, opts) {_x000D_
$('body').html(opts.detail);_x000D_
});_x000D_
_x000D_
// Trigger the event._x000D_
$(document).trigger('customChangeEvent', {_x000D_
detail: 'Display on trigger...'_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
_x000D_
There is a way to store multiple solutions in one instance of VS.
Attempt the following steps:
NOTE: This worked for Visual Studio 2013 Professional
Forgive me for being a Stack virgin... I'm not sure how to reply to Brian Ramsay's answer...
Using round will not work for second values between 59.5 and 59.99999. The second value will be 60 during this period. Use trunc instead...
double progress;
int minutes = floor(progress/60);
int seconds = trunc(progress - minutes * 60);
More recent answer in the case you want to delete every entries in every tables:
def reset
Rails.application.eager_load!
ActiveRecord::Base.descendants.each { |c| c.delete_all unless c == ActiveRecord::SchemaMigration }
end
More information about the eager_load
here.
After calling it, we can access to all of the descendants of ActiveRecord::Base
and we can apply a delete_all
on all the models.
Note that we make sure not to clear the SchemaMigration table.
Addition with @cletus answer, You have to fetch all model fields(upper hierarchy) and set field.setAccessible(true)
to access private members. Here is the full snippet:
@Override
public String toString() {
StringBuilder result = new StringBuilder();
String newLine = System.getProperty("line.separator");
result.append(getClass().getSimpleName());
result.append( " {" );
result.append(newLine);
List<Field> fields = getAllModelFields(getClass());
for (Field field : fields) {
result.append(" ");
try {
result.append(field.getName());
result.append(": ");
field.setAccessible(true);
result.append(field.get(this));
} catch ( IllegalAccessException ex ) {
// System.err.println(ex);
}
result.append(newLine);
}
result.append("}");
result.append(newLine);
return result.toString();
}
private List<Field> getAllModelFields(Class aClass) {
List<Field> fields = new ArrayList<>();
do {
Collections.addAll(fields, aClass.getDeclaredFields());
aClass = aClass.getSuperclass();
} while (aClass != null);
return fields;
}
From within modules of a python package I had to refer to a file that resided in the same directory as package. Ex.
some_dir/
maincli.py
top_package/
__init__.py
level_one_a/
__init__.py
my_lib_a.py
level_two/
__init__.py
hello_world.py
level_one_b/
__init__.py
my_lib_b.py
So in above I had to call maincli.py from my_lib_a.py module knowing that top_package and maincli.py are in the same directory. Here's how I get the path to maincli.py:
import sys
import os
import imp
class ConfigurationException(Exception):
pass
# inside of my_lib_a.py
def get_maincli_path():
maincli_path = os.path.abspath(imp.find_module('maincli')[1])
# top_package = __package__.split('.')[0]
# mod = sys.modules.get(top_package)
# modfile = mod.__file__
# pkg_in_dir = os.path.dirname(os.path.dirname(os.path.abspath(modfile)))
# maincli_path = os.path.join(pkg_in_dir, 'maincli.py')
if not os.path.exists(maincli_path):
err_msg = 'This script expects that "maincli.py" be installed to the '\
'same directory: "{0}"'.format(maincli_path)
raise ConfigurationException(err_msg)
return maincli_path
Based on posting by PlasmaBinturong I modified the code.
CURLOPT_POSTFIELDS
as the name suggests, is for the body (payload) of a POST
request. For GET
requests, the payload is part of the URL in the form of a query string.
In your case, you need to construct the URL with the arguments you need to send (if any), and remove the other options to cURL.
curl_setopt($ch, CURLOPT_URL, $this->service_url.'user/'.$id_user);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
//$body = '{}';
//curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
//curl_setopt($ch, CURLOPT_POSTFIELDS,$body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
require(ggplot2)
require(nlme)
set.seed(101)
mp <-data.frame(year=1990:2010)
N <- nrow(mp)
mp <- within(mp,
{
wav <- rnorm(N)*cos(2*pi*year)+rnorm(N)*sin(2*pi*year)+5
wow <- rnorm(N)*wav+rnorm(N)*wav^3
})
m01 <- gls(wow~poly(wav,3), data=mp, correlation = corARMA(p=1))
Get fitted values (the same as m01$fitted
)
fit <- predict(m01)
Normally we could use something like predict(...,se.fit=TRUE)
to get the confidence intervals on the prediction, but gls
doesn't provide this capability. We use a recipe similar to the one shown at http://glmm.wikidot.com/faq :
V <- vcov(m01)
X <- model.matrix(~poly(wav,3),data=mp)
se.fit <- sqrt(diag(X %*% V %*% t(X)))
Put together a "prediction frame":
predframe <- with(mp,data.frame(year,wav,
wow=fit,lwr=fit-1.96*se.fit,upr=fit+1.96*se.fit))
Now plot with geom_ribbon
(p1 <- ggplot(mp, aes(year, wow))+
geom_point()+
geom_line(data=predframe)+
geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))
It's easier to see that we got the right answer if we plot against wav
rather than year
:
(p2 <- ggplot(mp, aes(wav, wow))+
geom_point()+
geom_line(data=predframe)+
geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))
It would be nice to do the predictions with more resolution, but it's a little tricky to do this with the results of poly()
fits -- see ?makepredictcall
.
You can use the bit_length() function to convert numbers to their two's complement:
def twos_complement(j):
return j-(1<<(j.bit_length()))
In [1]: twos_complement(0b111111111111)
Out[1]: -1
MySQL 8.0.16 is the first version that supports CHECK constraints.
Read https://dev.mysql.com/doc/refman/8.0/en/create-table-check-constraints.html
If you use MySQL 8.0.15 or earlier, the MySQL Reference Manual says:
The
CHECK
clause is parsed but ignored by all storage engines.
Try a trigger...
mysql> delimiter //
mysql> CREATE TRIGGER trig_sd_check BEFORE INSERT ON Customer
-> FOR EACH ROW
-> BEGIN
-> IF NEW.SD<0 THEN
-> SET NEW.SD=0;
-> END IF;
-> END
-> //
mysql> delimiter ;
Hope that helps.
Here is how I did it in AngularJS
app = angular.module('MM_Graph')
class Keyboard
constructor: ($injector)->
@.$injector = $injector
@.$window = @.$injector.get('$window') # get reference to $window and $rootScope objects
@.$rootScope = @.$injector.get('$rootScope')
on_Key_Down:($event)=>
@.$rootScope.$broadcast 'keydown', $event # broadcast a global keydown event
if $event.code is 'KeyS' and ($event.ctrlKey or $event.metaKey) # detect S key pressed and either OSX Command or Window's Control keys pressed
@.$rootScope.$broadcast '', $event # broadcast keyup_CtrS event
#$event.preventDefault() # this should be used by the event listeners to prevent default browser behaviour
setup_Hooks: ()=>
angular.element(@.$window).bind "keydown", @.on_Key_Down # hook keydown event in window (only called once per app load)
@
app.service 'keyboard', ($injector)=>
return new Keyboard($injector).setup_Hooks()
First make sure that the input element is visible
As stated by Mark Collin in the discussion here:
Don't click on the browse button, it will trigger an OS level dialogue box and effectively stop your test dead.
Instead you can use:
driver.findElement(By.id("myUploadElement")).sendKeys("<absolutePathToMyFile>");
myUploadElement is the id of that element (button in this case) and in sendKeys you have to specify the absolute path of the content you want to upload (Image,video etc). Selenium will do the rest for you.
Keep in mind that the upload will work only If the element you send a file should be in the form <input type="file">
In my case, I wanted to move a submodule from one directory into a subdirectory, e.g. "AFNetworking" -> "ext/AFNetworking". These are the steps I followed:
[core] worktree
line. Mine changed from ../../../AFNetworking
to ../../../../ext/AFNetworking
gitdir
. Mine changed from ../.git/modules/AFNetworking
to ../../git/modules/ext/AFNetworking
git add .gitmodules
git rm --cached AFNetworking
git submodule add -f <url> ext/AFNetworking
Finally, I saw in the git status:
matt$ git status
# On branch ios-master
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# modified: .gitmodules
# renamed: AFNetworking -> ext/AFNetworking
Et voila. The above example doesn't change the directory depth, which makes a big difference to the complexity of the task, and doesn't change the name of the submodule (which may not really be necessary, but I did it to be consistent with what would happen if I added a new module at that path.)
Yes, there are a number of ways that you can do this. The "fastest" way would be to add CSS to the div similar to the following
#term-defs {
height: 300px;
overflow: scroll; }
This will force the div to be scrollable, but this might not get the best effect. Another route would be to absolute fix the position of the items at the top, you can play with this by doing something like this.
#top {
position: fixed;
top: 0;
left: 0;
z-index: 999;
width: 100%;
height: 23px;
}
This will fix it to the top, on top of other content with a height of 23px.
The final implementation will depend on what effect you really want.
I suggest you use null to represent a null value.
What is the exception you get?
BTW:
There is no year called 0 or 0000. (Though some dates allow this year)
And there is no 0 month of the year or 0 day of the month. (Which may be the cause of your problem)
It depends what you wanted to do with that column e.g. here's an example of appending a new column to a recordset which can be updated on the client side:
Sub MSDataShape_AddNewCol()
Dim rs As ADODB.Recordset
Set rs = CreateObject("ADODB.Recordset")
With rs
.ActiveConnection = _
"Provider=MSDataShape;" & _
"Data Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:\Tempo\New_Jet_DB.mdb"
.Source = _
"SHAPE {" & _
" SELECT ExistingField" & _
" FROM ExistingTable" & _
" ORDER BY ExistingField" & _
"} APPEND NEW adNumeric(5, 4) AS NewField"
.LockType = adLockBatchOptimistic
.Open
Dim i As Long
For i = 0 To .RecordCount - 1
.Fields("NewField").Value = Round(.Fields("ExistingField").Value, 4)
.MoveNext
Next
rs.Save "C:\rs.xml", adPersistXML
End With
End Sub
Use the following instead:
boost::function<void (int)> f2( boost::bind( &myclass::fun2, this, _1 ) );
This forwards the first parameter passed to the function object to the function using place-holders - you have to tell Boost.Bind how to handle the parameters. With your expression it would try to interpret it as a member function taking no arguments.
See e.g. here or here for common usage patterns.
Note that VC8s cl.exe regularly crashes on Boost.Bind misuses - if in doubt use a test-case with gcc and you will probably get good hints like the template parameters Bind-internals were instantiated with if you read through the output.
I have just sent an email with gmail through Python. Try to use smtplib.SMTP_SSL to make the connection. Also, you may try to change the gmail domain and port.
So, you may get a chance with:
server = smtplib.SMTP_SSL('smtp.googlemail.com', 465)
server.login(gmail_user, password)
server.sendmail(gmail_user, TO, BODY)
As a plus, you could check the email builtin module. In this way, you can improve the readability of you your code and handle emails headers easily.
Microsoft Visual Studio 2008 Service Pack 1 (iso)
http://www.microsoft.com/en-us/download/details.aspx?id=13276
Version: SP1 File Name: VS2008SP1ENUX1512962.iso Date Published: 8/11/2008 File Size: 831.3 MB
Supported Operating System
Windows Server 2003, Windows Server 2008, Windows Vista, Windows XP
Minimum: 1.6 GHz CPU, 384 MB RAM, 1024x768 display, 5400 RPM hard disk
Recommended: 2.2 GHz or higher CPU, 1024 MB or more RAM, 1280x1024 display, 7200 RPM or higher hard disk
On Windows Vista: 2.4 GHz CPU, 768 MB RAM
Maintain Internet connectivity during the installation of the service pack until seeing the “Installation Completed Successfully” message before disconnecting.
The modern approach uses java.time classes.
Instant.now() // Capture current moment in UTC.
.truncatedTo( ChronoUnit.SECONDS ) // Lop off any fractional second.
.plus( 8 , ChronoUnit.HOURS ) // Add eight hours.
.atZone( ZoneId.of( "America/Montreal" ) ) // Adjust from UTC to the wall-clock time used by the people of a certain region (a time zone). Returns a `ZonedDateTime` object.
.format( // Generate a `String` object representing textually the value of the `ZonedDateTime` object.
DateTimeFormatter.ofPattern( "dd/MM/uuuu HH:mm:ss" )
.withLocale( Locale.US ) // Specify a `Locale` to determine the human language and cultural norms used in localizing the text being generated.
) // Returns a `String` object.
23/01/2017 15:34:56
FYI, the old Calendar
and Date
classes are now legacy. Supplanted by the java.time classes. Much of java.time is back-ported to Java 6, Java 7, and Android (see below).
Instant
Capture the current moment in UTC with the Instant
class.
Instant instantNow = Instant.now();
instant.toString(): 2017-01-23T12:34:56.789Z
If you want only whole seconds, without any fraction of a second, truncate.
Instant instant = instantNow.truncatedTo( ChronoUnit.SECONDS );
instant.toString(): 2017-01-23T12:34:56Z
The Instant
class can do math, adding an amount of time. Specify the amount of time to add by the ChronoUnit
enum, an implementation of TemporalUnit
.
instant = instant.plus( 8 , ChronoUnit.HOURS );
instant.toString(): 2017-01-23T20:34:56Z
ZonedDateTime
To see that same moment through the lens of a particular region’s wall-clock time, apply a ZoneId
to get a ZonedDateTime
.
Specify a proper time zone name in the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-4 letter abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
zdt.toString(): 2017-01-23T15:34:56-05:00[America/Montreal]
You can generate a String in your desired format by specifying a formatting pattern in a DateTimeFormatter
object.
Note that case matters in the letters of your formatting pattern. The Question’s code had hh
which is for 12-hour time while uppercase HH
is 24-hour time (0-23) in both java.time.DateTimeFormatter
as well as the legacy java.text.SimpleDateFormat
.
The formatting codes in java.time are similar to those in the legacy SimpleDateFormat
but not exactly the same. Carefully study the class doc. Here, HH
happens to work identically.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu HH:mm:ss" ).withLocale( Locale.US );
String output = zdt.format( f );
Rather than hard-coding a formatting pattern, consider letting java.time fully localize the generation of the String
text by calling DateTimeFormatter.ofLocalizedDateTime
.
And, by the way, be aware that time zone and Locale
have nothing to do with one another; orthogonal issues. One is about content, the meaning (the wall-clock time). The other is about presentation, determining the human language and cultural norms used in presenting that meaning to the user.
Instant instant = Instant.parse( "2017-01-23T12:34:56Z" );
ZoneId z = ZoneId.of( "Pacific/Auckland" ); // Notice that time zone is unrelated to the `Locale` used in localizing.
ZonedDateTime zdt = instant.atZone( z );
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL )
.withLocale( Locale.CANADA_FRENCH ); // The locale determines human language and cultural norms used in generating the text representing this date-time object.
String output = zdt.format( f );
instant.toString(): 2017-01-23T12:34:56Z
zdt.toString(): 2017-01-24T01:34:56+13:00[Pacific/Auckland]
output: mardi 24 janvier 2017 à 01:34:56 heure avancée de la Nouvelle-Zélande
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
Update: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.
Joda-Time makes this kind of work much easier.
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;
DateTime later = DateTime.now().plusHours( 8 );
DateTimeFormatter formatter = DateTimeFormat.forPattern( "dd/MM/yyyy HH:mm:ss" );
String laterAsText = formatter.print( later );
System.out.println( "laterAsText: " + laterAsText );
When run…
laterAsText: 19/12/2013 02:50:18
Beware that this syntax uses default time zone. A better practice is to use an explicit DateTimeZone instance.
OK, I am a Ruby noob, but I did get this fixed slightly differently than the answers here, so hopefully this helps someone else (tl;dr: I used RVM to switch the system Ruby version to the same one expected by rubygems).
First off, listing all Rubies as mentioned by Eimantas was a great starting point:
> which -a ruby
/opt/local/bin/ruby
/Users/Brian/.rvm/rubies/ruby-1.9.2-p290/bin/ruby
/Users/Brian/.rvm/bin/ruby
/usr/bin/ruby
/opt/local/bin/ruby
The default Ruby instance in use by the system appeared to be 1.8.7:
> ruby -v
ruby 1.8.7 (2010-06-23 patchlevel 299) [i686-darwin10]
while the version in use by Rubygems was the 1.9.2 version managed by RVM:
> gem env | grep 'RUBY EXECUTABLE'
- RUBY EXECUTABLE: /Users/Brian/.rvm/rubies/ruby-1.9.2-p290/bin/ruby
So that was definitely the issue. I don't actively use Ruby myself (this is simply a dependency of a build system script I'm trying to run) so I didn't care which version was active for other purposes. Since rubygems expected the 1.9.2 that was already managed by RVM, I simply used RVM to switch the system to use the 1.9.2 version as the default:
> rvm use 1.9.2
Using /Users/Brian/.rvm/gems/ruby-1.9.2-p290
> ruby -v
ruby 1.9.2p290 (2011-07-09 revision 32553) [x86_64-darwin11.3.0]
After doing that my "no such file" issue went away and my script started working.
I have string that displays UTF-8 encoded characters
There is no such thing in .NET. The string class can only store strings in UTF-16 encoding. A UTF-8 encoded string can only exist as a byte[]. Trying to store bytes into a string will not come to a good end; UTF-8 uses byte values that don't have a valid Unicode codepoint. The content will be destroyed when the string is normalized. So it is already too late to recover the string by the time your DecodeFromUtf8() starts running.
Only handle UTF-8 encoded text with byte[]. And use UTF8Encoding.GetString() to convert it.
In my case it helped to remove node_modules
and package-lock.json
.
After that just reinstall everything with npm install
.
NOTE: see Cheetah's answer below as it identifies a prerequisite to get this solution to work. Setting the BackColor
of the TextBox
.
I think what you really want to do is enable the TextBox
and set the ReadOnly
property to true
.
It's a bit tricky to change the color of the text in a disabled TextBox
. I think you'd probably have to subclass and override the OnPaint
event.
ReadOnly
though should give you the same result as !Enabled
and allow you to maintain control of the color and formatting of the TextBox
. I think it will also still support selecting and copying text from the TextBox
which is not possible with a disabled TextBox
.
Another simple alternative is to use a Label
instead of a TextBox
.
I am not sure if this is the case for all versions of Windows, however on the XP machine I have, I need to use the following:
set /p Var1="Prompt String"
Without the prompt string in quotes, I get various results depending on the text.
I am using a regex to make sure that I only allow letters, number and a space
Then it is as simple as adding a space to what you've already got:
$newtag = preg_replace("/[^a-zA-Z0-9 ]/", "", $tag);
(note, I removed the s|
which seemed unintentional? Certainly the s
was redundant; you can restore the |
if you need it)
If you specifically want *a* space, as in only a single one, you will need a more complex expression than this, and might want to consider a separate non-regex piece of logic.
I think by using the content"."; The dot becomes too squared if made too big, thus I believe that this is a better solution, here you can decide the size of the "disc" without affecting the font size.
li {_x000D_
list-style: none;_x000D_
display: list-item;_x000D_
margin-left: 50px;_x000D_
}_x000D_
_x000D_
li:before {_x000D_
content: "";_x000D_
border: 5px #000 solid !important;_x000D_
border-radius: 50px;_x000D_
margin-top: 5px;_x000D_
margin-left: -20px;_x000D_
position: absolute;_x000D_
}
_x000D_
<h2>Look at these examples!</h2>_x000D_
<li>This is an example</li>_x000D_
<li>This is another example</li>
_x000D_
You edit the size of the disk by editing the size of the border px. and you can adjust the distance to the text by how much - margin left you give it. As well as adjust the y position by editing the margin top.
The existing answers solve most cases. However, I ran into a case where I needed the content of the grid-cell to be overflow: visible
. I solved it by absolutely positioning within a wrapper (not ideal, but the best I know), like this:
.month-grid {
display: grid;
grid-template: repeat(6, 1fr) / repeat(7, 1fr);
background: #fff;
grid-gap: 2px;
}
.day-item-wrapper {
position: relative;
}
.day-item {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
padding: 10px;
background: rgba(0,0,0,0.1);
}
set text-decoration: none; for anchor tag.
Example html.
<body>
<ul class="nav-tabs">
<li><a href="#"><i class="fas fa-th"></i>Business</a></li>
<li><a href="#"><i class="fas fa-th"></i>Expertise</a></li>
<li><a href="#"><i class="fas fa-th"></i>Quality</a></li>
</ul>
</body>
Example CSS:
.nav-tabs li a{
text-decoration: none;
}
It seems that Luiggi Mendoza
and joey rohan
both already answered this, but I think it can be clarified a little.
You can write it as a single if
statement:
if (inventory.contains("bread") && !inventory.contains("water")) {
// do something
}
These all are ways:
String imageUri = "drawable://" + R.drawable.image;
Other ways I tested
Uri path = Uri.parse("android.resource://com.segf4ult.test/" + R.drawable.icon);
Uri otherPath = Uri.parse("android.resource://com.segf4ult.test/drawable/icon");
String path = path.toString();
String path = otherPath .toString();
The best way of doing it is:
$('#e1.select2-offscreen').empty(); //#e1 : select 2 ID
$('#e1').append(new Option()); // to add the placeholder and the allow clear
One possible solution is to pad the numeric values with a character in front so that all are of the same string length.
Here is an example using that approach:
select MyColumn
from MyTable
order by
case IsNumeric(MyColumn)
when 1 then Replicate('0', 100 - Len(MyColumn)) + MyColumn
else MyColumn
end
The 100
should be replaced with the actual length of that column.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#000"
android:gravity="center"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:scaleType="fitXY"
android:layout_marginTop="5dp"
android:layout_marginBottom="60dp"
android:src="@drawable/lwt_placeholder"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:visibility="visible"
android:id="@+id/imageView"
android:layout_centerInParent="true"/></RelativeLayout>
and in activity
final ImageView imageView = (ImageView) itemView.findViewById(R.id.imageView);
PhotoViewAttacher photoAttacher;
photoAttacher= new PhotoViewAttacher(imageView);
photoAttacher.update();
Picasso.with(ImageGallery.this).load(imageUrl).placeholder(R.drawable.lwt_placeholder)
.into(imageView);
Thats it!
use the following line on your DataContext to log the SQL activity on the DataContext to the console - then you can see exactly what your linq statements are requesting from the database:
_db.Log = Console.Out
The following LINQ statements:
var movies = from row in _db.Movies
orderby row.CategoryID, row.Name
select row;
AND
var movies = _db.Movies.OrderBy(m => m.CategoryID).ThenBy(m => m.Name);
produce the following SQL:
SELECT [t0].ID, [t0].[Name], [t0].CategoryID
FROM [dbo].[Movies] as [t0]
ORDER BY [t0].CategoryID, [t0].[Name]
Whereas, repeating an OrderBy in Linq, appears to reverse the resulting SQL output:
var movies = from row in _db.Movies
orderby row.CategoryID
orderby row.Name
select row;
AND
var movies = _db.Movies.OrderBy(m => m.CategoryID).OrderBy(m => m.Name);
produce the following SQL (Name and CategoryId are switched):
SELECT [t0].ID, [t0].[Name], [t0].CategoryID
FROM [dbo].[Movies] as [t0]
ORDER BY [t0].[Name], [t0].CategoryID
One possible PHP solution:
// load XML to SimpleXML
$x = simplexml_load_string($xmlstr);
// index it by title once
$index = array();
foreach ($x->CD as &$cd) {
$title = strtolower((string)$cd['title']);
if (!array_key_exists($title, $index)) $index[$title] = array();
$index[$title][] = &$cd;
}
// query the index
$result = $index[strtolower("EMPIRE BURLESQUE")];
If you are running via the IDE, running as administrator should help. To do this locate the Visual Studio 2008/10 application icon, right click it and select "Run as administrator"
In my case, I had started untar before the uploading of the tar file was complete.
simply "CUT" project folder and move it out of workspace directory and do the following
file=>import=>(select new directory)=> mark (copy to my workspace) checkbox
and you done !
You may have a table called 'test'
COPY test(gid, "name", the_geom)
FROM '/home/data/sample.csv'
WITH DELIMITER ','
CSV HEADER
Ubuntu 18.04
Install and ensure mysqld us running..
Go into database and setup root user:
sudo mysql -u root
SELECT User,Host FROM mysql.user;
DROP USER 'root'@'localhost';
CREATE USER 'root'@'%' IDENTIFIED BY 'obamathelongleggedmacdaddy';
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION;
FLUSH PRIVILEGES;
exit;
Edit mysqld permissions and restart:
sudo vi /etc/mysql/mysql.conf.d/mysqld.cnf
# edit the line to be this:
bind-address=0.0.0.0
sudo systemctl stop mysql
sudo systemctl start mysql
From another machine, test.. Obvs port (3306) on mysqld machine must allow connection from test machine.
mysql -u root -p -h 123.456.789.666
All the additional "security" of MySql doesn't help security at all, it just complicates and obfuscates, it is now actually easier to screw it up than in the old days, where you just used a really long password.
I updated Mr. ganaraj answer to show stop and resume functionality and added angular js filter to format countdown timer
controller code
'use strict';
var myApp = angular.module('myApp', []);
myApp.controller('AlbumCtrl', function($scope,$timeout) {
$scope.counter = 0;
$scope.stopped = false;
$scope.buttonText='Stop';
$scope.onTimeout = function(){
$scope.counter++;
mytimeout = $timeout($scope.onTimeout,1000);
}
var mytimeout = $timeout($scope.onTimeout,1000);
$scope.takeAction = function(){
if(!$scope.stopped){
$timeout.cancel(mytimeout);
$scope.buttonText='Resume';
}
else
{
mytimeout = $timeout($scope.onTimeout,1000);
$scope.buttonText='Stop';
}
$scope.stopped=!$scope.stopped;
}
});
filter-code adapted from RobG from stackoverflow
myApp.filter('formatTimer', function() {
return function(input)
{
function z(n) {return (n<10? '0' : '') + n;}
var seconds = input % 60;
var minutes = Math.floor(input / 60);
var hours = Math.floor(minutes / 60);
return (z(hours) +':'+z(minutes)+':'+z(seconds));
};
});
Subplot Colorbar
For subplots with scatter, you can trick a colorbar onto your axes by building the "mappable" with the help of a secondary figure and then adding it to your original plot.
As a continuation of the above example:
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(10)
y = x
t = x
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.scatter(x, y, c=t, cmap='viridis')
ax2.scatter(x, y, c=t, cmap='viridis_r')
# Build your secondary mirror axes:
fig2, (ax3, ax4) = plt.subplots(1, 2)
# Build maps that parallel the color-coded data
# NOTE 1: imshow requires a 2-D array as input
# NOTE 2: You must use the same cmap tag as above for it match
map1 = ax3.imshow(np.stack([t, t]),cmap='viridis')
map2 = ax4.imshow(np.stack([t, t]),cmap='viridis_r')
# Add your maps onto your original figure/axes
fig.colorbar(map1, ax=ax1)
fig.colorbar(map2, ax=ax2)
plt.show()
Note that you will also output a secondary figure that you can ignore.
As Ciro Santilli notes using command substitutions will drop trailing newlines. Their workaround adding trailing characters is great, but after using it for quite some time I decided I needed a solution that didn't use command substitution at all.
My approach now uses read
along with the printf
builtin's -v
flag in order to read the contents of stdin directly into a variable.
# Reads stdin into a variable, accounting for trailing newlines. Avoids
# needing a subshell or command substitution.
# Note that NUL bytes are still unsupported, as Bash variables don't allow NULs.
# See https://stackoverflow.com/a/22607352/113632
read_input() {
# Use unusual variable names to avoid colliding with a variable name
# the user might pass in (notably "contents")
: "${1:?Must provide a variable to read into}"
if [[ "$1" == '_line' || "$1" == '_contents' ]]; then
echo "Cannot store contents to $1, use a different name." >&2
return 1
fi
local _line _contents=()
while IFS='' read -r _line; do
_contents+=("$_line"$'\n')
done
# include $_line once more to capture any content after the last newline
printf -v "$1" '%s' "${_contents[@]}" "$_line"
}
This supports inputs with or without trailing newlines.
Example usage:
$ read_input file_contents < /tmp/file
# $file_contents now contains the contents of /tmp/file
font-family:'Open Sans' , sans-serif;
For light:
font-weight : 100;
Or
font-weight : lighter;
For normal:
font-weight : 500;
Or
font-weight : normal;
For bold:
font-weight : 700;
Or
font-weight : bold;
For more bolder:
font-weight : 900;
Or
font-weight : bolder;
I'm not a Java guy, but OpenCV is great for my needs. Not sure if it fits yours. Here's a Java port, I think: http://docs.opencv.org/2.4/doc/tutorials/introduction/desktop_java/java_dev_intro.html
Instants are already in UTC and already have a default date format of yyyy-MM-dd. If you're happy with that and don't want to mess with time zones or formatting, you could also toString()
it:
Instant instant = Instant.now();
instant.toString()
output: 2020-02-06T18:01:55.648475Z
Don't want the T and Z? (Z indicates this date is UTC. Z stands for "Zulu" aka "Zero hour offset" aka UTC):
instant.toString().replaceAll("[TZ]", " ")
output: 2020-02-06 18:01:55.663763
Want milliseconds instead of nanoseconds? (So you can plop it into a sql query):
instant.truncatedTo(ChronoUnit.MILLIS).toString().replaceAll("[TZ]", " ")
output: 2020-02-06 18:01:55.664
etc.
Guessing from the information I have, you're not actually compiling the program, but trying to run it. That is, ALL_BUILD is set as your startup project. (It should be in a bold font, unlike the other projects in your solution) If you then try to run/debug, you will get the error you describe, because there is simply nothing to run.
The project is most likely generated via CMAKE and included in your Visual Studio solution. Set any of the projects that do generate a .exe as the startup project (by right-clicking on the project and selecting "set as startup project") and you will most likely will be able to start those from within Visual Studio.
Create views on two first "selects" and "union" them.
In 2020 Dec, the fix did finally worked for me was restarting my mac.
The same may be achieved with the stringi package:
library('stringi')
char_array <- c("foo_bar","bar_foo","apple","beer")
a <- data.frame("data"=char_array, "data2"=1:4)
(a$data <- stri_sub(a$data, 1, -4)) # from the first to the last but 4th char
## [1] "foo_" "bar_" "ap" "b"
Ahem u_u
As i've stated the back button is for every one of us a pain in some place... that said...
As long as you load the page normally it makes a lot of trouble... for a standard "site" it will not change that much... however i think you can make something like this
The user access everytime to your page .php that choose what to load. You can try to work a little with cache (to not cache page) and maybe expire date.
But the long term solution will be put a code on "onload" event to fetch the data trought Ajax, this way you can (with Javascript) run the code you want, and example refresh the page.
sometimes you need to select some fields by FirstOrDefault()
or singleOrDefault()
you can use the below query:
List<ResultLine> result = Lines
.GroupBy(l => l.ProductCode)
.Select(cl => new Models.ResultLine
{
ProductName = cl.select(x=>x.Name).FirstOrDefault(),
Quantity = cl.Count().ToString(),
Price = cl.Sum(c => c.Price).ToString(),
}).ToList();
You don't say what system you're using, but as you already have some answers that may or may not work for Windows, I'll answer for POSIX systems.
In POSIX, keyboard input comes through something called a terminal interface, which by default buffers lines of input until Return/Enter is hit, so as to deal properly with backspace. You can change that with the tcsetattr call:
#include <termios.h>
struct termios info;
tcgetattr(0, &info); /* get current terminal attirbutes; 0 is the file descriptor for stdin */
info.c_lflag &= ~ICANON; /* disable canonical mode */
info.c_cc[VMIN] = 1; /* wait until at least one keystroke available */
info.c_cc[VTIME] = 0; /* no timeout */
tcsetattr(0, TCSANOW, &info); /* set immediately */
Now when you read from stdin (with getchar()
, or any other way), it will return characters immediately, without waiting for a Return/Enter. In addition, backspace will no longer 'work' -- instead of erasing the last character, you'll read an actual backspace character in the input.
Also, you'll want to make sure to restore canonical mode before your program exits, or the non-canonical handling may cause odd effects with your shell or whoever invoked your program.
If you just want to throw away local commits and keep the modifications done in files then do
git reset @~
Other answers addressed the hard reset
for what ever it's worth you can do it like this too. very simple.
a = [1, 2, 3, 4, 5, 6, 7]
for x in xrange(len(a)):
x += 1
print a[-x]
I'm stumbling into the same issue. For me it seems to be caused by having 2 projects with the same name, one depending on the other.
For example, I have one project named Foo which produces Foo.lib. I then have another project that's also named Foo which produces Foo.exe and links in Foo.lib.
I watched the file activity w/ Process Monitor. What seems to be happening is Foo(lib) is built first--which is proper because Foo(exe) is marked as depending on Foo(lib). This is all fine and builds successfully, and is placed in the output directory--$(OutDir)$(TargetName)$(TargetExt). Then Foo(exe) is triggered to rebuild. Well, a rebuild is a clean followed by a build. It seems like the 'clean' stage of Foo.exe is deleting Foo.lib from the output directory. This also explains why a subsequent 'build' works--that doesn't delete output files.
A bug in VS I guess.
Unfortunately I don't have a solution to the problem as it involves Rebuild. A workaround is to manually issue Clean, and then Build.
You have to go to the folder where eclipse is installed and then you have to change the eclipse.ini file.
You have to add
-vm
C:\Program Files\Java\jdk1.8.0_202\bin\javaw.exe
Your eclipse.ini file will look like the below screenshot
I think the best place to look is the Super POM.
As an example, at the time of writing, the linked reference shows some of the properties between lines 32 - 48.
The interpretation of this is to follow the XPath as a .
delimited property.
So, for example:
${project.build.testOutputDirectory}
== ${project.build.directory}/test-classes
And:
${project.build.directory}
== ${project.basedir}/target
Thus combining them, we find:
${project.build.testOutputDirectory}
== ${project.basedir}/target/test-classes
(To reference the resources directory(s), see this stackoverflow question)
<project>
<modelVersion>4.0.0</modelVersion>
.
.
.
<build>
<directory>${project.basedir}/target</directory>
<outputDirectory>${project.build.directory}/classes</outputDirectory>
<finalName>${project.artifactId}-${project.version}</finalName>
<testOutputDirectory>${project.build.directory}/test-classes</testOutputDirectory>
<sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
<scriptSourceDirectory>src/main/scripts</scriptSourceDirectory>
<testSourceDirectory>${project.basedir}/src/test/java</testSourceDirectory>
<resources>
<resource>
<directory>${project.basedir}/src/main/resources</directory>
</resource>
</resources>
<testResources>
<testResource>
<directory>${project.basedir}/src/test/resources</directory>
</testResource>
</testResources>
.
.
.
</build>
.
.
.
</project>
This will work if you do not have too many expressions.
Example: ng-show="form.type === 'Limited Company' || form.type === 'Limited Partnership'"
For any more expressions than this use a controller.
A class, in Python, is an object, and just like any other object, it is an instance of "something". This "something" is what is termed as a Metaclass. This metaclass is a special type of class that creates other class's objects. Hence, metaclass is responsible for making new classes. This allows the programmer to customize the way classes are generated.
To create a metaclass, overriding of new() and init() methods is usually done. new() can be overridden to change the way objects are created, while init() can be overridden to change the way of initializing the object. Metaclass can be created by a number of ways. One of the ways is to use type() function. type() function, when called with 3 parameters, creates a metaclass. The parameters are :-
Another way of creating a metaclass comprises of 'metaclass' keyword. Define the metaclass as a simple class. In the parameters of inherited class, pass metaclass=metaclass_name
Metaclass can be specifically used in the following situations :-
Using array formula.
=SUM(COUNT(IF(D1:D5="Yes",COUNT(D1:D5),"")),COUNT(IF(D1:D5="No",COUNT(D1:D5),"")),COUNT(IF(D1:D5="Agree",COUNT(D1:D5),"")))
PRESS = CTRL + SHIFT + ENTER.
If you need to know the amount of every element in array besides existing of that element you may use
my %bad_param_lookup;
@bad_param_lookup{ @bad_params } = ( 1 ) x @bad_params;
%bad_param_lookup = map { $_ => $bad_param_lookup{$_}++} @bad_params;
and then for every $i that is in @bad_params, $bad_param_lookup{$i} contains amount of $i in @bad_params
Use fmod()
from <cmath>
. If you do not want to include the C header file:
template<typename T, typename U>
constexpr double dmod (T x, U mod)
{
return !mod ? x : x - mod * static_cast<long long>(x / mod);
}
//Usage:
double z = dmod<double, unsigned int>(14.3, 4);
double z = dmod<long, float>(14, 4.6);
//This also works:
double z = dmod(14.7, 0.3);
double z = dmod(14.7, 0);
double z = dmod(0, 0.3f);
double z = dmod(myFirstVariable, someOtherVariable);
For Apache Spark 2+, in order to save dataframe into single csv file. Use following command
query.repartition(1).write.csv("cc_out.csv", sep='|')
Here 1
indicate that I need one partition of csv only. you can change it according to your requirements.
The easiest way is to invert the value of the keys and use heapq. For example, turn 1000.0 into -1000.0 and 5.0 into -5.0.
Here's another good one: http://www.saltycrane.com/blog/2009/05/notes-using-pip-and-virtualenv-django/
This one shows how to use pip
and a pip requirements file with virtualenv; Scobal's two suggested tutorials are both very helpful but are both easy_install
-centric.
Note that none of these tutorials explain how to run a different version of Python within a virtualenv - for this, see this SO question: Use different Python version with virtualenv
If you have ReSharper installed clicking Shift+Alt+L will move focus to the current file in Solution Explorer.
Active Item Tracking will also need to be enabled as described in the accepted answer
Tools->Options->Projects and Solutions->Track Active Item in Solution Explorer
Yeah I agree with your approach. To merge mobiledevicesupport into master you can use
git checkout master
git pull origin master //Get all latest commits of master branch
git merge mobiledevicesupport
Similarly you can also merge master in mobiledevicesupport.
Q. If cross merging is an issue or not.
A. Well it depends upon the commits made in mobile* branch and master branch from the last time they were synced. Take this example: After last sync, following commits happen to these branches
Master branch: A -> B -> C [where A,B,C are commits]
Mobile branch: D -> E
Now, suppose commit B made some changes to file a.txt and commit D also made some changes to a.txt. Let us have a look at the impact of each operation of merging now,
git checkout master //Switches to master branch
git pull // Get the commits you don't have. May be your fellow workers have made them.
git merge mobiledevicesupport // It will try to add D and E in master branch.
Now, there are two types of merging possible
Git will first try to make FF merge and if it finds any conflicts are not resolvable by git. It fails the merge and asks you to merge. In this case, a new commit will occur which is responsible for resolving conflicts in a.txt.
So Bottom line is Cross merging is not an issue and ultimately you have to do it and that is what syncing means. Make sure you dirty your hands in merging branches before doing anything in production.
Try this [reverse order traversal]:
var childs = document.getElementById('parent').childNodes;
var len = childs.length;
if(len --) do {
console.log('node: ', childs[len]);
} while(len --);
OR [in order traversal]
var childs = document.getElementById('parent').childNodes;
var len = childs.length, i = -1;
if(++i < len) do {
console.log('node: ', childs[i]);
} while(++i < len);
I see that this question is solved, but, I want to add some information than can help someone.
if you want use hex to set background color, I found this function and work:
func UIColorFromHex(rgbValue:UInt32, alpha:Double=1.0)->UIColor {
let red = CGFloat((rgbValue & 0xFF0000) >> 16)/256.0
let green = CGFloat((rgbValue & 0xFF00) >> 8)/256.0
let blue = CGFloat(rgbValue & 0xFF)/256.0
return UIColor(red:red, green:green, blue:blue, alpha:CGFloat(alpha))
}
I use this function as follows:
view.backgroundColor = UIColorFromHex(0x323232,alpha: 1)
some times you must use self
:
self.view.backgroundColor = UIColorFromHex(0x323232,alpha: 1)
Well that was it, I hope it helps someone .
sorry for my bad english.
this work on iOS 7.1+
Found a way to do this, simply add a querystring to load your components, like so:
@Component({
selector: 'some-component',
templateUrl: `./app/component/stuff/component.html?v=${new Date().getTime()}`,
styleUrls: [`./app/component/stuff/component.css?v=${new Date().getTime()}`]
})
This should force the client to load the server's copy of the template instead of the browser's. If you would like it to refresh only after a certain period of time you could use this ISOString instead:
new Date().toISOString() //2016-09-24T00:43:21.584Z
And substring some characters so that it will only change after an hour for example:
new Date().toISOString().substr(0,13) //2016-09-24T00
Hope this helps
Simple but usefull way:
$query = $this->db->distinct()->select('order_id')->get_where('tbl_order_details', array('seller_id' => $seller_id));
return $query;
see my test here
I could send up to 33 Chinese characters and 13 bytes of custom values.
In windows 7, 8, and 10 you can find at the following location
C:\Users\<user>\AppData\Roaming\Subversion
If you enter the following in the Windows Explorer address bar, it will take you right there.
%appdata%\Subversion
Make sure your id_rsa file doesn't have any extension like .txt or .rtf. Rich Text Format adds additional characters to your file and those gets added to byte array. Which eventually causes invalid private key error. Long story short, Copy the file, not content.
So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.
protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.my_layout); Bitmap bitmap = getIntent().getParcelableExtra("image"); ImageView imageView = (ImageView) findViewById(R.id.imageview); imageView.setImageBitmap(bitmap); }
GET Request with JSON Query Param
package com.rest.jersey.jerseyclient;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
public class JerseyClientGET {
public static void main(String[] args) {
try {
String BASE_URI="http://vaquarkhan.net:8080/khanWeb";
Client client = Client.create();
WebResource webResource = client.resource(BASE_URI);
ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);
/*if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
*/
String output = webResource.path("/msg/sms").queryParam("search","{\"name\":\"vaquar\",\"surname\":\"khan\",\"ext\":\"2020\",\"age\":\"34\""}").get(String.class);
//String output = response.getEntity(String.class);
System.out.println("Output from Server .... \n");
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Post Request :
package com.rest.jersey.jerseyclient;
import com.rest.jersey.dto.KhanDTOInput;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
public class JerseyClientPOST {
public static void main(String[] args) {
try {
KhanDTOInput khanDTOInput = new KhanDTOInput("vaquar", "khan", "20", "E", null, "2222", "8308511500");
ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getFeatures().put( JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
Client client = Client.create(clientConfig);
// final HTTPBasicAuthFilter authFilter = new HTTPBasicAuthFilter(username, password);
// client.addFilter(authFilter);
// client.addFilter(new LoggingFilter());
//
WebResource webResource = client
.resource("http://vaquarkhan.net:12221/khanWeb/messages/sms/api/v1/userapi");
ClientResponse response = webResource.accept("application/json")
.type("application/json").put(ClientResponse.class, khanDTOInput);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code :" + response.getStatus());
}
String output = response.getEntity(String.class);
System.out.println("Server response .... \n");
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
}
}
you can do these line on your mysql query browser or something
SET old_passwords = 0;
UPDATE mysql.user SET Password = PASSWORD('testpass') WHERE User = 'testuser' limit 1;
SELECT LENGTH(Password) FROM mysql.user WHERE User = 'testuser';
FLUSH PRIVILEGES;
note:your username and password
after that it should able to work. I just solved mine too
Even when the query syntax is correct, prepare could return false, if there was a previous statement and it wasn't closed. Always close your previous statement with
$statement->close();
If the syntax is correct, the following query will run well too.
If you need a very minimalistic approach to this, I made one (originally forked from vuejs-tips to also support IE) which is available here: https://www.npmjs.com/package/v-debounce
Usage:
<input v-model.lazy="term" v-debounce="delay" placeholder="Search for something" />
Then in your component:
<script>
export default {
name: 'example',
data () {
return {
delay: 1000,
term: '',
}
},
watch: {
term () {
// Do something with search term after it debounced
console.log(`Search term changed to ${this.term}`)
}
},
directives: {
debounce
}
}
</script>
There's certainly a performance difference when running a compiled script. If you run normal .py
scripts, the machine compiles it every time it is run and this takes time. On modern machines this is hardly noticeable but as the script grows it may become more of an issue.
you can also code like this
IConfiguration config = new ConfigurationBuilder()
.AddCommandLine(args)
.Build();
var host = new WebHostBuilder()
.UseConfiguration(config)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>()
.Build();
and set up your application by command line :dotnet run --server.urls http://*:5555
A note on the difference in speed. Attach the following snipet to an onclick call:
function myfunc()
{
var timer = new Date();
for(var i = 0; i < 10000; i++)
{
//document.getElementById('myID');
$('#myID')[0];
}
console.log('timer: ' + (new Date() - timer));
}
Alternate commenting one out and then comment the other out. In my tests,
document.getElementbyId averaged about 35ms (fluctuating from
25ms
up to52ms
on about15 runs
)
On the other hand, the
jQuery averaged about 200ms (ranging from
181ms
to222ms
on about15 runs
).From this simple test you can see that the jQuery took about 6 times as long.
Of course, that is over 10000
iterations so in a simpler situation I would probably use the jQuery for ease of use and all of the other cool things like .animate
and .fadeTo
. But yes, technically getElementById
is quite a bit faster.
It is unnecessary. You can use an ORDER BY
and just change the sort to DESC
to get the same effect.
Let's say if you want to set 10px
space between the items, you can just set .item {margin-right:10px;}
for all, and reset it on the last one .item:last-child {margin-right:0;}
You can also use general sibling ~
or next +
sibling selector to set left margin on the items excluding the first one .item ~ .item {margin-left:10px;}
or use .item:not(:last-child) {margin-right: 10px;}
Flexbox is so clever that it automatically recalculates and equally distributes the grid.
body {_x000D_
margin: 0;_x000D_
}_x000D_
_x000D_
.container {_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
.item {_x000D_
flex: 1;_x000D_
background: gray;_x000D_
height: 50px;_x000D_
}_x000D_
_x000D_
.item:not(:last-child) {_x000D_
margin-right: 10px;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="item"></div>_x000D_
<div class="item"></div>_x000D_
<div class="item"></div>_x000D_
<div class="item"></div>_x000D_
</div>
_x000D_
If you want to allow flex wrap, see the following example.
body {_x000D_
margin: 0;_x000D_
}_x000D_
_x000D_
.container {_x000D_
display: flex;_x000D_
flex-wrap: wrap;_x000D_
margin-left: -10px;_x000D_
}_x000D_
_x000D_
.item {_x000D_
flex: 0 0 calc(50% - 10px);_x000D_
background: gray;_x000D_
height: 50px;_x000D_
margin: 0 0 10px 10px;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="item"></div>_x000D_
<div class="item"></div>_x000D_
<div class="item"></div>_x000D_
<div class="item"></div>_x000D_
</div>
_x000D_
Try not to do DOM manipulation by referring the DOM directly, it will have lot of performance issue, also event handling becomes more tricky when we try to access DOM directly, instead use data and directives to manipulate the DOM.
This will give you more control over the manipulation, also you will be able to manage functionalities in the modular format.
Thanks to Andrey-Egorov and this answer, I've managed to do it in C#
IWebDriver driver = new ChromeDriver();
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
string value = (string)js.ExecuteScript("document.getElementById('elementID').setAttribute('value', 'new value for element')");
My experience:
var text = $('#myInputField');
var myObj = {title: 'Some title', content: text};
$.post(myUrl, myObj, callback);
The problem is that I forgot to add .val() to the end of $('#myInputField'); this action makes me waste time trying to figure out what was wrong, causing Illegal Invocation Error, since $('#myInputField') was in a different file than that system pointed out incorrect code. Hope this answer help fellows in the same mistake to avoid to loose time.
Thank you RedX and Kaz for your answers. I don't get why by me it gives the path of the exe. I found an other way to do it :
QString pwd("");
char * PWD;
PWD = getenv ("PWD");
pwd.append(PWD);
cout << "Working directory : " << pwd << flush;
It is less elegant than a single line... but it works for me.
You can set sys.dont_write_bytecode = True
in your source, but that would have to be in the first python file loaded. If you execute python somefile.py
then you will not get somefile.pyc
.
When you install a utility using setup.py
and entry_points=
you will have set sys.dont_write_bytecode
in the startup script. So you cannot rely on the "default" startup script generated by setuptools.
If you start Python with python file as argument yourself you can specify -B
:
python -B somefile.py
somefile.pyc
would not be generated anyway, but no .pyc
files for other files imported too.
If you have some utility myutil
and you cannot change that, it will not pass -B to the python interpreter. Just start it by setting the environment variable PYTHONDONTWRITEBYTECODE
:
PYTHONDONTWRITEBYTECODE=x myutil
In view there is not any direct or physical relation with the database. And Modification through a view (e.g. insert, update, delete) is not permitted.Its just a logical set of tables
You need to pass an array of element to jsx
. The problem is that forEach
does not return anything (i.e it returns undefined
). So it's better to use map
because map
returns an array:
class QuestionSet extends Component {
render(){
<div className="container">
<h1>{this.props.question.text}</h1>
{this.props.question.answers.map((answer, i) => {
console.log("Entered");
// Return the element. Also pass key
return (<Answer key={answer} answer={answer} />)
})}
}
export default QuestionSet;
I dont see anyone mentioning the ClassInitialize
attribute method. The attributes are pretty straight forward.
Create methods that are marked with either the [ClassInitialize()]
or [TestInitialize()]
attribute to prepare aspects of the environment in which your unit test will run. The purpose of this is to establish a known state for running your unit test. For example, you may use the [ClassInitialize()]
or the [TestInitialize()]
method to copy, alter, or create certain data files that your test will use.
Create methods that are marked with either the [ClassCleanup()]
or [TestCleanUp{}]
attribute to return the environment to a known state after a test has run. This might mean the deletion of files in folders or the return of a database to a known state. An example of this is to reset an inventory database to an initial state after testing a method that is used in an order-entry application.
[ClassInitialize()]
Use ClassInitialize
to run code before you
run the first test in the class.
[ClassCleanUp()]
Use ClassCleanup
to run code after all tests in
a class have run.
[TestInitialize()]
Use TestInitialize
to run code before you run
each test.
[TestCleanUp()]
Use TestCleanup
to run code after each test has
run.
You can also use AWK which can give you more flexibility to handle the file
awk '{ print "chmod 755 "$0"" | "/bin/sh"}' file.txt
if your file has a field separator like:
field1,field2,field3
To get only the first field you do
awk -F, '{ print "chmod 755 "$1"" | "/bin/sh"}' file.txt
You can check more details on GNU Documentation https://www.gnu.org/software/gawk/manual/html_node/Very-Simple.html#Very-Simple
In case of presence of a Security Manager, one can make use of AccessController.doPrivileged
Taking the same example from accepted answer above:
import java.lang.reflect.*;
public class EverythingIsTrue {
static void setFinalStatic(Field field, Object newValue) throws Exception {
field.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
// wrapping setAccessible
AccessController.doPrivileged(new PrivilegedAction() {
@Override
public Object run() {
modifiersField.setAccessible(true);
return null;
}
});
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, newValue);
}
public static void main(String args[]) throws Exception {
setFinalStatic(Boolean.class.getField("FALSE"), true);
System.out.format("Everything is %s", false); // "Everything is true"
}
}
In lambda expression, AccessController.doPrivileged
, can be simplified to:
AccessController.doPrivileged((PrivilegedAction) () -> {
modifiersField.setAccessible(true);
return null;
});
=arrayformula(if(isblank(B2:B),iferror(1/0),mmult(sign(B2:B=TRANSPOSE(A2:A)),A2:A)))
I got this from a good tutorial - can't remember the title - probably about using MMult
Sorry not sure what was going on this worked in the end:
<VirtualHost *>
ServerName example.com
DocumentRoot /var/www/html/mjp
Alias /ncn "/var/www/html/ncn"
<Directory "/var/www/html/ncn">
Options None
AllowOverride None
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
No, but you could have something like:
bool b;
b = b.YourExtensionMethod();
You can't. Flexbox is not a grid system. It does not have the language constructs to do what you're asking for, at least not if you're using justify-content: space-between
. The closest you can get with Flexbox is to use the column orientation, which requires setting an explicit height:
http://cssdeck.com/labs/pvsn6t4z (note: prefixes not included)
ul {
display: flex;
flex-flow: column wrap;
align-content: space-between;
height: 4em;
}
However, it would be simpler to just use columns, which has better support and doesn't require setting a specific height:
http://cssdeck.com/labs/dwq3x6vr (note: prefixes not included)
ul {
columns: 15em;
}
Create in your Site.css (or in another place) a new class named for example .font-bold and set it to your element
.font-bold {
font-weight: bold;
}
Yes there is. The preferred syntax is to favor str.format
over the deprecated %
operator.
print "First number is {} and second number is {}".format(first, second)
$observe() is a method on the Attributes object, and as such, it can only be used to observe/watch the value change of a DOM attribute. It is only used/called inside directives. Use $observe when you need to observe/watch a DOM attribute that contains interpolation (i.e., {{}}'s).
E.g., attr1="Name: {{name}}"
, then in a directive: attrs.$observe('attr1', ...)
.
(If you try scope.$watch(attrs.attr1, ...)
it won't work because of the {{}}s -- you'll get undefined
.) Use $watch for everything else.
$watch() is more complicated. It can observe/watch an "expression", where the expression can be either a function or a string. If the expression is a string, it is $parse'd (i.e., evaluated as an Angular expression) into a function. (It is this function that is called every digest cycle.) The string expression can not contain {{}}'s. $watch is a method on the Scope object, so it can be used/called wherever you have access to a scope object, hence in
Because strings are evaluated as Angular expressions, $watch is often used when you want to observe/watch a model/scope property. E.g., attr1="myModel.some_prop"
, then in a controller or link function: scope.$watch('myModel.some_prop', ...)
or scope.$watch(attrs.attr1, ...)
(or scope.$watch(attrs['attr1'], ...)
).
(If you try attrs.$observe('attr1')
you'll get the string myModel.some_prop
, which is probably not what you want.)
As discussed in comments on @PrimosK's answer, all $observes and $watches are checked every digest cycle.
Directives with isolate scopes are more complicated. If the '@' syntax is used, you can $observe or $watch a DOM attribute that contains interpolation (i.e., {{}}'s). (The reason it works with $watch is because the '@' syntax does the interpolation for us, hence $watch sees a string without {{}}'s.) To make it easier to remember which to use when, I suggest using $observe for this case also.
To help test all of this, I wrote a Plunker that defines two directives. One (d1
) does not create a new scope, the other (d2
) creates an isolate scope. Each directive has the same six attributes. Each attribute is both $observe'd and $watch'ed.
<div d1 attr1="{{prop1}}-test" attr2="prop2" attr3="33" attr4="'a_string'"
attr5="a_string" attr6="{{1+aNumber}}"></div>
Look at the console log to see the differences between $observe and $watch in the linking function. Then click the link and see which $observes and $watches are triggered by the property changes made by the click handler.
Notice that when the link function runs, any attributes that contain {{}}'s are not evaluated yet (so if you try to examine the attributes, you'll get undefined
). The only way to see the interpolated values is to use $observe (or $watch if using an isolate scope with '@'). Therefore, getting the values of these attributes is an asynchronous operation. (And this is why we need the $observe and $watch functions.)
Sometimes you don't need $observe or $watch. E.g., if your attribute contains a number or a boolean (not a string), just evaluate it once: attr1="22"
, then in, say, your linking function: var count = scope.$eval(attrs.attr1)
. If it is just a constant string – attr1="my string"
– then just use attrs.attr1
in your directive (no need for $eval()).
See also Vojta's google group post about $watch expressions.
Pass your ImageView and based on screen height and width you can make it
public void setScaleImage(EventAssetValueListenerView view){
// Get the ImageView and its bitmap
Drawable drawing = view.getDrawable();
Bitmap bitmap = ((BitmapDrawable)drawing).getBitmap();
// Get current dimensions
int width = bitmap.getWidth();
int height = bitmap.getHeight();
float xScale = ((float) 4) / width;
float yScale = ((float) 4) / height;
float scale = (xScale <= yScale) ? xScale : yScale;
Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
BitmapDrawable result = new BitmapDrawable(scaledBitmap);
width = scaledBitmap.getWidth();
height = scaledBitmap.getHeight();
view.setImageDrawable(result);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
params.width = width;
params.height = height;
view.setLayoutParams(params);
}
To keep beginner attitude you can explain that all the command line is automaticaly splite in a array fo String (the String[]
).
For static
you have to explain, that it not a field like another : it is unique in the JVM even if you have thousand instances of the class
So main
is static, because it is the only way to find it (linked in its own class) in a jar
.
... after you look at coding, and your job begin ...
You can use a defaultdict for this.
from collections import defaultdict
d = defaultdict(list)
d['key'].append('mykey')
This is slightly more efficient than setdefault
since you don't end up creating new lists that you don't end up using. Every call to setdefault
is going to create a new list, even if the item already exists in the dictionary.
The Content-Length
header is a number denoting an the exact byte length of the HTTP body. The HTTP body starts immediately after the first empty line that is found after the start-line and headers.
Generally the Content-Length
header is used for HTTP 1.1 so that the receiving party knows when the current response* has finished, so the connection can be reused for another request.
* ...or request, in the case of request methods that have a body, such as POST, PUT or PATCH
Alternatively, Content-Length
header can be omitted and a chunked Transfer-Encoding
header can be used.
If both Content-Length
and Transfer-Encoding
headers are missing, then at the end of the response the connection must be closed.
The following resource is a guide that I found very useful when learning about HTTP:
Another easy way is to use 2 premade sizes and pass them as parameter when calling the function in your html. use: 'lg' for large modals with width 900px 'sm' for small modals with width 300px or passing no parameter you use the default size which is 600px.
example code:
$scope.openModal = function (size) {
var modal = $modal.open({
templateUrl: "/partials/welcome",
controller: "welcomeCtrl",
backdrop: "static",
scope: $scope,
size: size,
});
modal.result.then(
//close
function (result) {
var a = result;
},
//dismiss
function (result) {
var a = result;
});
};
and in the html I would use something like the following:
<button ng-click="openModal('lg')">open Modal</button>
if you want to just "bold", Mike Hofer's answer is mostly correct.
but notice that the tag bolds its contents by default, but you can change this behavior using css, example:
p strong {
font-weight: normal;
font-style: italic;
}
Now your "bold" is italic :)
So, try to use tags by its meaning, not by its default style.
You can also use BigInteger for variable length bytes. You can convert it to Long, Integer or Short, whichever suits your needs.
new BigInteger(bytes).intValue();
or to denote polarity:
new BigInteger(1, bytes).intValue();
To get bytes back just:
new BigInteger(bytes).toByteArray()
Nope, it doesn't seem like you're doing it wrong. MongoDB joins are "client side". Pretty much like you said:
At the moment, I am first getting the comments which match my criteria, then figuring out all the uid's in that result set, getting the user objects, and merging them with the comment's results. Seems like I am doing it wrong.
1) Select from the collection you're interested in.
2) From that collection pull out ID's you need
3) Select from other collections
4) Decorate your original results.
It's not a "real" join, but it's actually alot more useful than a SQL join because you don't have to deal with duplicate rows for "many" sided joins, instead your decorating the originally selected set.
There is alot of nonsense and FUD on this page. Turns out 5 years later MongoDB is still a thing.
The default expiry_date for google oauth2 access token is 1 hour. The expiry_date is in the Unix epoch time in milliseconds. If you want to read this in human readable format then you can simply check it here..Unix timestamp to human readable time