The Bootstrap Glyphicons are fonts. This means it can be changed like any other text through CSS styling.
CSS:
<style>
.glyphicon-plus {
color: #F00;
}
</style>
HTML:
<span class="glyphicon glyphicon-plus"></span>
Example:
<!doctype html>
<html>
<head>
<title>Glyphicon Colors</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<style>
.glyphicon-plus {
color: #F00;
}
</style>
</head>
<body>
<span class="glyphicon glyphicon-plus"></span>
</body>
</html>
Watch the course Up and Running with Bootstrap 3 by Jen Kramer, or watch the individual lesson on Overriding core CSS with custom styles.
You can put the graphic in a pseudo-element with its own dimensional context:
#graphic {
position: relative;
width: 200px;
height: 100px;
}
#graphic::before {
position: absolute;
content: '';
z-index: -1;
width: 200px;
height: 50px;
background-image: url(image.jpg);
}
#graphic {_x000D_
width: 200px;_x000D_
height: 100px;_x000D_
position: relative;_x000D_
}_x000D_
#graphic::before {_x000D_
content: '';_x000D_
_x000D_
position: absolute;_x000D_
width: 200px;_x000D_
height: 50px;_x000D_
z-index: -1;_x000D_
_x000D_
background-image: url(http://placehold.it/500x500/); /* Image is 500px by 500px, but only 200px by 50px is showing. */_x000D_
}
_x000D_
<div id="graphic">lorem ipsum</div>
_x000D_
Browser support is good, but if you need to support IE8, use a single colon :before
. IE has no support for either syntax in versions prior to that.
It took me a while to create a solution to this problem I was happy with:
Problem:
An SVG sprite of icons - say 80px x 3200px
We want to scale each use of them in content selectors (:before/:after) in various places over various sizes without re-defining the co-ords of each sprite based on the size used.
So this solution allows you to use the same sprite co-ords in a <button>
as a <menuitem>
whilst still scaling it.
[data-command]::before {
content: '';
position: absolute;
background-image: url("images/sprite.svgz");
background-repeat: no-repeat;
background-size: cover;
}
button[data-command]::before {
width: 32px;
height: 32px;
}
menuitem[data-command]::before {
width: 24px;
height: 24px;
}
[data-command="cancel"]::before {
background-position: 0% 35%;
}
[data-command="logoff"]::before {
background-position: 0% 37.5%;
}
By using percentages (to 2 decimal places) in background-position rather than background-size as suggested by others here, you can scale the same icon declaration to any size, without needing to redeclare it.
The position-y percentage is the original sprite height/icon height as a % - in our case here 80px*100/3200px == each sprite is represented by a y-position of 2.5%.
If you have hover/mouseover states you can double the width of the sprite and specify in the position-x coordinate.
The disadvantage of this approach is that adding more icons at a later date will change the sprite height and so y-position %, but if you don't do that then your sprite co-ordinates will need change for each scaled resolution you require.
From all I have read you cannot do exactly what you want without javascript. If you float left before text
<div style="float:left;">widget</div> here is some CONTENT, etc.
Your content wraps as expected. But your widget is in the top left. If you instead put the float after the content
here is some CONTENT, etc. <div style="float:left;">widget</div>
Then your content will wrap the last line to the right of the widget if the last line of content can fit to the right of the widget, otherwise no wrapping is done. To make borders and backgrounds actually include the floated area in the previous example, most people add:
here is some CONTENT, etc. <div style="float:left;">widget</div><div style="clear:both;"></div>
In your question you are using bootstrap which just adds row-fluid::after { content: ""}
which resolves the border/background issue.
Moving your content up will give you the one line wrap : http://jsfiddle.net/jJNPY/34/
<div class="container-fluid">
<div class="row-fluid">
<div class="offset1 span8 pull-right">
... Widget 1...
</div>
.... a lot of content ....
<div class="span8" style="margin-left: 0;">
... Widget 2...
</div>
</div>
</div><!--/.fluid-container-->
This is minor usage is tilde...
def split_train_test_by_id(data, test_ratio, id_column):
ids = data[id_column]
in_test_set = ids.apply(lambda id_: test_set_check(id_, test_ratio))
return data.loc[~in_test_set], data.loc[in_test_set]
the code above is from "Hands On Machine Learning"
you use tilde (~ sign) as alternative to - sign index marker
just like you use minus - is for integer index
ex)
array = [1,2,3,4,5,6]
print(array[-1])
is the samething as
print(array[~1])
POCOs(Plain old CLR objects) are simply entities of your Domain. Normally when we use entity framework the entities are generated automatically for you. This is great but unfortunately these entities are interspersed with database access functionality which is clearly against the SOC (Separation of concern). POCOs are simple entities without any data access functionality but still gives the capabilities all EntityObject functionalities like
Here is a good start for this
You can also generate POCOs so easily from your existing Entity framework project using Code generators.
In Spring 5
@PostMapping( "some/request/path" )
public void someControllerMethod( @RequestParam MultiValueMap body ) {
// import org.springframework.util.MultiValueMap;
String datax = (String) body .getFirst("datax");
}
master
is just the name of a branch, there's nothing magic about it except it's created by default when a new repository is created.
You can add it back with git checkout -b master
.
As a tangential note, one case where the ability to have multiple .gitignore
files is very useful is if you want an extra directory in your working copy that you never intend to commit. Just put a 1-byte .gitignore
(containing just a single asterisk) in that directory and it will never show up in git status
etc.
I really liked Nate Cook's answer but I wanted something a little more idiomatic. I believe this is a really good use case for a convenience initializer via a custom extension.
// UIColorExtensions.swift
import Foundation
import UIKit
extension UIColor {
convenience init(rgb: UInt) {
self.init(
red: CGFloat((rgb & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgb & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgb & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
}
This can now be used like so:
view.backgroundColor = UIColor(rgb: 0x209624)
I would only recommend monkey patching UIKit classes like this in your own client code, not libraries.
I had a problem because of ** instead *
*ngFor="let ingredient of ingredients"
**ngFor="let ingredient of ingredients"
I very often use classes, rather than functions, for my decorators. I was having some trouble with this because an object won't have all the same attributes that are expected of a function. For example, an object won't have the attribute __name__
. I had a specific issue with this that was pretty hard to trace where Django was reporting the error "object has no attribute '__name__
'". Unfortunately, for class-style decorators, I don't believe that @wrap will do the job. I have instead created a base decorator class like so:
class DecBase(object):
func = None
def __init__(self, func):
self.__func = func
def __getattribute__(self, name):
if name == "func":
return super(DecBase, self).__getattribute__(name)
return self.func.__getattribute__(name)
def __setattr__(self, name, value):
if name == "func":
return super(DecBase, self).__setattr__(name, value)
return self.func.__setattr__(name, value)
This class proxies all the attribute calls over to the function that is being decorated. So, you can now create a simple decorator that checks that 2 arguments are specified like so:
class process_login(DecBase):
def __call__(self, *args):
if len(args) != 2:
raise Exception("You can only specify two arguments")
return self.func(*args)
In python 3s print function:
lst = [1, 2, 3]
print('My list:', *lst, sep='\n- ')
Output:
My list:
- 1
- 2
- 3
Con: The sep
must be a string, so you can't modify it based on which element you're printing. And you need a kind of header to do this (above it was 'My list:'
).
Pro: You don't have to join()
a list into a string object, which might be advantageous for larger lists. And the whole thing is quite concise and readable.
Simple! Throw this at the like, bottom of your CSS file and this part of the CSS will be modified within a phone: -
/* ON A PHONE */
@media only screen and (max-width: 600px) { /* CSS HERE ONLY ON PHONE */ }
And voila!
You can use this, just think Job is the name of the model to which you are adding index cader_id:
class AddCaderIdToJob < ActiveRecord::Migration[5.2]
def change
change_table :jobs do |t|
t.integer :cader_id
t.index :cader_id
end
end
end
For me it only fetched new dependencies from Docker Hub with both --no-cache
and --pull
(which are available for docker-compose build
.
# other steps before rebuild
docker-compose build --no-cache --pull nginx # rebuild nginx
# other steps after rebuild, e.g. up (see other answers)
you can use this:
try {
Intent followIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("fb://facewebmodal/f?href=" +
"https://www.facebook.com/app_scoped_user_id/"+scoped user id+"/"));
activity.startActivity(followIntent);
} catch (Exception e) {
activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + user name)));
String errorMessage = (e.getMessage() == null) ? "Message is empty" : e.getMessage();
}
attention: you can get scoped user id from "link" permission facebook api
As pointed out, your hashcode implementation has too many collisions, and fixing it should result in decent performance. Moreover, caching hashCodes and implementing equals efficiently will help.
If you need to optimize even further:
By your description, there are only (52 * 51 / 2) * (52 * 51 * 50 / 6) = 29304600 different keys (of which 26000000, i.e. about 90%, will be present). Therefore, you can design a hash function without any collisions, and use a simple array rather than a hashmap to hold your data, reducing memory consumption and increasing lookup speed:
T[] array = new T[Key.maxHashCode];
void put(Key k, T value) {
array[k.hashCode()] = value;
T get(Key k) {
return array[k.hashCode()];
}
(Generally, it is impossible to design an efficient, collision-free hash function that clusters well, which is why a HashMap will tolerate collisions, which incurs some overhead)
Assuming a
and b
are sorted, you might use the following hash function:
public int hashCode() {
assert a[0] < a[1];
int ahash = a[1] * a[1] / 2
+ a[0];
assert b[0] < b[1] && b[1] < b[2];
int bhash = b[2] * b[2] * b[2] / 6
+ b[1] * b[1] / 2
+ b[0];
return bhash * 52 * 52 / 2 + ahash;
}
static final int maxHashCode = 52 * 52 / 2 * 52 * 52 * 52 / 6;
I think this is collision-free. Proving this is left as an exercise for the mathematically inclined reader.
Not tested, but you can do something like this:
Create Function dbo.AlphasOnly(@s as varchar(max)) Returns varchar(max) As
Begin
Declare @Pos int = 1
Declare @Ret varchar(max) = null
If @s Is Not Null
Begin
Set @Ret = ''
While @Pos <= Len(@s)
Begin
If SubString(@s, @Pos, 1) Like '[A-Za-z]'
Begin
Set @Ret = @Ret + SubString(@s, @Pos, 1)
End
Set @Pos = @Pos + 1
End
End
Return @Ret
End
The key is to use this as a computed column and index it. It doesn't really matter how fast you make this function if the database has to execute it against every row in your large table every time you run the query.
Include the sunfire and jacoco plugins in the pom.xml and Run the maven command as given below.
mvn jacoco:prepare-agent jacoco:report sonar:sonar
<properties>
<surefire.version>2.17</surefire.version>
<jacoco.version>0.7.2.201409121644</jacoco.version>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${surefire.version}</version>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>${jacoco.version}</version>
<executions>
<execution>
<id>default-prepare-agent</id>
<goals><goal>prepare-agent</goal></goals>
</execution>
<execution>
<id>default-report</id>
<phase>prepare-package</phase>
<goals><goal>report</goal></goals>
</execution>
</executions>
</plugin>
</plugins>
<input type="text" value="3" class="field left" readonly>
No styling necessary.
See <input>
on MDN https://developer.mozilla.org/en/docs/Web/HTML/Element/input#Attributes
I am very suprised nobody came up with this kind of solution to bind it against bool array. It might not be the cleanest, but it can be used very easily:
private bool[] _modeArray = new bool[] { true, false, false};
public bool[] ModeArray
{
get { return _modeArray ; }
}
public int SelectedMode
{
get { return Array.IndexOf(_modeArray, true); }
}
in XAML:
<RadioButton GroupName="Mode" IsChecked="{Binding Path=ModeArray[0], Mode=TwoWay}"/>
<RadioButton GroupName="Mode" IsChecked="{Binding Path=ModeArray[1], Mode=TwoWay}"/>
<RadioButton GroupName="Mode" IsChecked="{Binding Path=ModeArray[2], Mode=TwoWay}"/>
NOTE: you dont need two-way binding if you dont want to one checked by default. TwoWay binding is the biggest cons of this solution.
Pros:
This worked for me:
sheet.Cells[currentRow, ++currentColumn] = "'" + theDate.ToString("MM/dd/yy");
Note the tick mark added before the date.
Joshua Bloch's book has a whole chapter entitled "Item 10: Override Clone Judiciously" in which he goes into why overriding clone for the most part is a bad idea because the Java spec for it creates many problems.
He provides a few alternatives:
Use a factory pattern in place of a constructor:
public static Yum newInstance(Yum yum);
Use a copy constructor:
public Yum(Yum yum);
All of the collection classes in Java support the copy constructor (e.g. new ArrayList(l);)
You can use File.WriteAllBytes
I know this post is old but...
I was able to do this, my problem was that I forgot to make my property static.
public static class MyStaticClass
{
private static NonStaticObject _myObject = new NonStaticObject();
//property
public static NonStaticObject MyObject
{
get { return _myObject; }
set { _myObject = value; }
}
}
MessageBox.Show(title, text, messageboxbuttons.yes/no)
This returns a DialogResult which you can check.
For example,
if(MessageBox.Show("","",MessageBoxButtons.YesNo) == DialogResult.Yes)
{
//do something
}
The sizeof "trick" is the best way I know, with one small but (to me, this being a major pet peeve) important change in the use of parenthesis.
As the Wikipedia entry makes clear, C's sizeof
is not a function; it's an operator. Thus, it does not require parenthesis around its argument, unless the argument is a type name. This is easy to remember, since it makes the argument look like a cast expression, which also uses parenthesis.
So: If you have the following:
int myArray[10];
You can find the number of elements with code like this:
size_t n = sizeof myArray / sizeof *myArray;
That, to me, reads a lot easier than the alternative with parenthesis. I also favor use of the asterisk in the right-hand part of the division, since it's more concise than indexing.
Of course, this is all compile-time too, so there's no need to worry about the division affecting the performance of the program. So use this form wherever you can.
It is always best to use sizeof on an actual object when you have one, rather than on a type, since then you don't need to worry about making an error and stating the wrong type.
For instance, say you have a function that outputs some data as a stream of bytes, for instance across a network. Let's call the function send()
, and make it take as arguments a pointer to the object to send, and the number of bytes in the object. So, the prototype becomes:
void send(const void *object, size_t size);
And then you need to send an integer, so you code it up like this:
int foo = 4711;
send(&foo, sizeof (int));
Now, you've introduced a subtle way of shooting yourself in the foot, by specifying the type of foo
in two places. If one changes but the other doesn't, the code breaks. Thus, always do it like this:
send(&foo, sizeof foo);
Now you're protected. Sure, you duplicate the name of the variable, but that has a high probability of breaking in a way the compiler can detect, if you change it.
After adding the ICO file to your apps resources, you can use references it using My.Resources.YourIconNameWithoutExtension
For example if I had a file called Logo-square.ico added to my apps resources, I can set it to an icon with:
NotifyIcon1.Icon = My.Resources.Logo_square
Enable Microsoft ActiveX Data Objects 2.8 Library
Dim oConn As ADODB.Connection
Private Sub ConnectDB()
Set oConn = New ADODB.Connection
oConn.Open "DRIVER={MySQL ODBC 5.1 Driver};" & _
"SERVER=localhost;" & _
"DATABASE=yourdatabase;" & _
"USER=yourdbusername;" & _
"PASSWORD=yourdbpassword;" & _
"Option=3"
End Sub
There rest is here: http://www.heritage-tech.net/908/inserting-data-into-mysql-from-excel-using-vba/
For C++ :
I just faced the same issue and I think it is worth mentioning a problem comes up when one use both __stdcall
(or WINAPI
) and extern "C"
:
As you know extern "C"
removes the decoration so that instead of :
__declspec(dllexport) int Test(void) --> dumpbin : ?Test@@YaHXZ
you obtain a symbol name undecorated:
extern "C" __declspec(dllexport) int Test(void) --> dumpbin : Test
However the _stdcall
( = macro WINAPI, that changes the calling convention) also decorates names so that if we use both we obtain :
extern "C" __declspec(dllexport) int WINAPI Test(void) --> dumpbin : _Test@0
and the benefit of extern "C"
is lost because the symbol is decorated (with _ @bytes)
Note that this only occurs for x86 architecture because the
__stdcall
convention is ignored on x64 (msdn : on x64 architectures, by convention, arguments are passed in registers when possible, and subsequent arguments are passed on the stack.).
This is particularly tricky if you are targeting both x86 and x64 platforms.
Two solutions
Use a definition file. But this forces you to maintain the state of the def file.
the simplest way : define the macro (see msdn) :
#define EXPORT comment(linker, "/EXPORT:" __FUNCTION__ "=" __FUNCDNAME__)
and then include the following pragma in the function body:
#pragma EXPORT
Full Example :
int WINAPI Test(void)
{
#pragma EXPORT
return 1;
}
This will export the function undecorated for both x86 and x64 targets while preserving the __stdcall
convention for x86. The __declspec(dllexport)
is not required in this case.
With the sqldf package, R is capable of not only statistics, but serious data mining as well - assuming there is enough RAM on your machine.
And with the RServe package R becomes a regular TCP/IP server; so you can call R out of java (or any other language if you have the api). There is also a package in R to call java out or R.
You can easily achieve this using ArrayField
:
# in my models...
tags = ArrayField(models.CharField(null=True, blank=True, max_length=100, choices=SECTORS_TAGS_CHOICES), blank=True, default=list)
# in my forms...
class MyForm(forms.ModelForm):
class Meta:
model = ModelClass
fields = [..., 'tags', ...]
I use tagsinput JS library to render my tags but you can use whatever you like: This my template for this widget:
{% if not hidelabel and field.label %}<label for="{{ field.id_for_label }}">{{ field.label }}</label>{% endif %}
<input id="{{ field.id_for_label }}" type="text" name="{{ field.name }}" data-provide="tagsinput"{% if field.value %} value="{{ field.value }}"{% endif %}{% if field.field.disabled %} disabled{% endif %}>
{% if field.help_text %}<small id="{{ field.name }}-help-text" class="form-text text-muted">{{ field.help_text | safe }}</small>{% endif %}
Ofcourse this is a closed issue, i would like to add something to your discussion
In mozilla i have observed a weird behaviour for this code
$(document).keydown(function(){
//my code
});
the code is being triggered twice. When debugged i found that actually there are two events getting fired: 'keypress' and 'keydown'. I disabled one of the event and the code shown me expected behavior.
$(document).unbind('keypress');
$(document).keydown(function(){
//my code
});
This works for all browsers and also there is no need to check for browser specific(if($.browser.mozilla){ }).
Hope this might be useful for someone
In case you want to kill not all java processes but specif jars running. It will work for multiple jars as well.
wmic Path win32_process Where "CommandLine Like '%YourJarName.jar%'" Call Terminate
Else taskkill /im java.exe
will work to kill all java processes
How about without using predefined function like min
or max
?
$arr = [4,5,6,7,8,2,9,1];
$val = $arr[0];
$n = count($arr);
for($i=1;$i<$n;$i++) {
if($val<$arr[$i]) {
$val = $val;
} else {
$val = $arr[$i];
}
}
print($val);
?>
If the image size is variable or the design is responsive, in addition to wrapping the text, you can set a min width for the paragraph to avoid it to become too narrow.
Give an invisible CSS pseudo-element with the desired minimum paragraph width. If there isn't enough space to fit this pseudo-element, then it will be pushed down underneath the image, taking the paragraph with it.
#container:before {
content: ' ';
display: table;
width: 10em; /* Min width required */
}
#floated{
float: left;
width: 150px;
background: red;
}
As of npm 5, npm will now save by default. In case,if you would like npm to work in a similar old fashion (no autosave) to how it was working in previous versions, you can update the config option to enable autosave as below.
npm config set save false
To get the current setting, you can execute the following command:
npm config get save
I know your question does not specify if you are trying to open all a tags in a new window or only the external links.
But in case you only want external links to open in a new tab you can do this:
$( 'a[href^="http://"]' ).attr( 'target','_blank' )
$( 'a[href^="https://"]' ).attr( 'target','_blank' )
To extract a numeric value out of your string you can use these 2 functions (Assuming you have your value in cell 'A1'):
=VALUE(REGEXEXTRACT(A1, "\d+"))
This will get you a numeric value.
I've found no date add function in docs, but you can convert your date into internal date number and then add days number (If your value is in cell 'A2'):
=DATEVALUE(A2) + 30
I hope this will help.
This could also be done using display: flex
with only a few lines of code. Here is an example:
.container {
width: 100px;
height: 100px;
display: flex;
align-items: center;
}
If you don't want any separator after the last cell, then you need a close to zero but non-zero height for your footer.
In your UITableViewDelegate
:
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return .leastNormalMagnitude
}
The easiest way to do this is just:
You will receive a float or double and want it to convert it to the closest round up then just do System.out.println((int)Math.ceil(yourfloat));
it'll work perfectly
I am new to Angular but have found this to solve my issue:
<i class="icon-download" ng-click="showDetails = ! showDetails" ng-class="{'icon-upload': showDetails}"></i>
This will conditionally apply a class based on a var.
It starts off with a icon-download as a default, the using ng-class, I check the status of showDetails
if true/false
and apply class icon-upload. Its working great.
Hope it helps.
You can add a class that implements IDesignTimeDbContextFactory inside of your Web project.
Here is the sample code:
public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<CodingBlastDbContext>
{
public CodingBlastDbContext CreateDbContext(string[] args)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var builder = new DbContextOptionsBuilder<CodingBlastDbContext>();
var connectionString = configuration.GetConnectionString("DefaultConnection");
builder.UseSqlServer(connectionString);
return new CodingBlastDbContext(builder.Options);
}
}
Then, navigate to your Database project and run the following from command line:
dotnet ef migrations add InitialMigration -s ../Web/
dotnet ef database update -s ../Web/
-s stands for startup project and ../Web/ is the location of my web/startup project.
To stage modified and deleted files
git add -u
Same pdo error in sql query while trying to insert into database value from multidimential array:
$sql = "UPDATE test SET field=arr[$s][a] WHERE id = $id";
$sth = $db->prepare($sql);
$sth->execute();
Extracting array arr[$s][a]
from sql query, using instead variable containing it fixes the problem.
According to C99 standard, section 6.5.5 Multiplicative operators, the following is required:
(a / b) * b + a % b = a
The sign of the result of a remainder operation, according to C99, is the same as the dividend's one.
Let's see some examples (dividend / divisor
):
(-3 / 2) * 2 + -3 % 2 = -3
(-3 / 2) * 2 = -2
(-3 % 2) must be -1
(3 / -2) * -2 + 3 % -2 = 3
(3 / -2) * -2 = 2
(3 % -2) must be 1
(-3 / -2) * -2 + -3 % -2 = -3
(-3 / -2) * -2 = -2
(-3 % -2) must be -1
6.5.5 Multiplicative operators
Syntax
- multiplicative-expression:
cast-expression
multiplicative-expression * cast-expression
multiplicative-expression / cast-expression
multiplicative-expression % cast-expression
Constraints
- Each of the operands shall have arithmetic type. The operands of the % operator shall have integer type.
Semantics
The usual arithmetic conversions are performed on the operands.
The result of the binary * operator is the product of the operands.
The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined.
When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded [1]. If the quotient
a/b
is representable, the expression(a/b)*b + a%b
shall equala
.[1]: This is often called "truncation toward zero".
I'm not a 100% sure but I think Aptana let's you do that.
Adding to Dmitri Chebotarev's answer, as for Laravel 5+.
After requiring the doctrine/dbal package:
composer require doctrine/dbal
You can then make a migration with nullable columns, like so:
public function up()
{
Schema::table('users', function (Blueprint $table) {
// change() tells the Schema builder that we are altering a table
$table->integer('user_id')->unsigned()->nullable()->change();
});
}
To revert the operation, do:
public function down()
{
/* turn off foreign key checks for a moment */
DB::statement('SET FOREIGN_KEY_CHECKS = 0');
/* set null values to 0 first */
DB::statement('UPDATE `users` SET `user_id` = 0 WHERE `user_id` IS NULL;');
/* alter table */
DB::statement('ALTER TABLE `users` MODIFY `user_id` INTEGER UNSIGNED NOT NULL;');
/* finally turn foreign key checks back on */
DB::statement('SET FOREIGN_KEY_CHECKS = 1');
}
For strings containing   I've had to double-decode the string. First decode would turn it into the second pass would correctly decode it to the expected character.
var list = new List<string>();
var queryable = list.AsQueryable();
Add a reference to: System.Linq
I was facing the same issues since several days, Today i have found the solution. I have shown the complete file which is ready to execute.
<html>
<head><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.js">
</script>
</head>
<body>
<canvas id="myChart" width="200" height="200"></canvas>
<script>
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
},
onClick:function(e){
var activePoints = myChart.getElementsAtEvent(e);
var selectedIndex = activePoints[0]._index;
alert(this.data.datasets[0].data[selectedIndex]);
}
}
});
</script>
</body>
</html>
I prefer to use the ngModel and ngChange directives when dealing with checkboxes. ngModel allows you to bind the checked/unchecked state of the checkbox to a property on the entity:
<input type="checkbox" ng-model="entity.isChecked">
Whenever the user checks or unchecks the checkbox the entity.isChecked
value will change too.
If this is all you need then you don't even need the ngClick or ngChange directives. Since you have the "Check All" checkbox, you obviously need to do more than just set the value of the property when someone checks a checkbox.
When using ngModel with a checkbox, it's best to use ngChange rather than ngClick for handling checked and unchecked events. ngChange is made for just this kind of scenario. It makes use of the ngModelController for data-binding (it adds a listener to the ngModelController's $viewChangeListeners
array. The listeners in this array get called after the model value has been set, avoiding this problem).
<input type="checkbox" ng-model="entity.isChecked" ng-change="selectEntity()">
... and in the controller ...
var model = {};
$scope.model = model;
// This property is bound to the checkbox in the table header
model.allItemsSelected = false;
// Fired when an entity in the table is checked
$scope.selectEntity = function () {
// If any entity is not checked, then uncheck the "allItemsSelected" checkbox
for (var i = 0; i < model.entities.length; i++) {
if (!model.entities[i].isChecked) {
model.allItemsSelected = false;
return;
}
}
// ... otherwise ensure that the "allItemsSelected" checkbox is checked
model.allItemsSelected = true;
};
Similarly, the "Check All" checkbox in the header:
<th>
<input type="checkbox" ng-model="model.allItemsSelected" ng-change="selectAll()">
</th>
... and ...
// Fired when the checkbox in the table header is checked
$scope.selectAll = function () {
// Loop through all the entities and set their isChecked property
for (var i = 0; i < model.entities.length; i++) {
model.entities[i].isChecked = model.allItemsSelected;
}
};
CSS
What is the best way to... add a CSS class to the
<tr>
containing the entity to reflect its selected state?
If you use the ngModel approach for the data-binding, all you need to do is add the ngClass directive to the <tr>
element to dynamically add or remove the class whenever the entity property changes:
<tr ng-repeat="entity in model.entities" ng-class="{selected: entity.isChecked}">
See the full Plunker here.
The following steps work fine on macOS Sierra 10.12.4. Note that after brew installs Docker, the docker
command (symbolic link) is not available at /usr/local/bin
. Running the Docker app for the first time creates this symbolic link. See the detailed steps below.
Install Docker.
brew cask install docker
Launch Docker.
Docker
to launch Docker.When Docker is launched in this manner, a Docker whale icon appears in the status menu. As soon as the whale icon appears, the symbolic links for docker
, docker-compose
, docker-credential-osxkeychain
and docker-machine
are created in /usr/local/bin
.
$ ls -l /usr/local/bin/docker*
lrwxr-xr-x 1 susam domain Users 67 Apr 12 14:14 /usr/local/bin/docker -> /Users/susam/Library/Group Containers/group.com.docker/bin/docker
lrwxr-xr-x 1 susam domain Users 75 Apr 12 14:14 /usr/local/bin/docker-compose -> /Users/susam/Library/Group Containers/group.com.docker/bin/docker-compose
lrwxr-xr-x 1 susam domain Users 90 Apr 12 14:14 /usr/local/bin/docker-credential-osxkeychain -> /Users/susam/Library/Group Containers/group.com.docker/bin/docker-credential-osxkeychain
lrwxr-xr-x 1 susam domain Users 75 Apr 12 14:14 /usr/local/bin/docker-machine -> /Users/susam/Library/Group Containers/group.com.docker/bin/docker-machine
Click on the docker whale icon in the status menu and wait for it to show Docker is running.
Test that docker works fine.
$ docker run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
78445dd45222: Pull complete
Digest: sha256:c5515758d4c5e1e838e9cd307f6c6a0d620b5e07e6f927b07d05f6d12a1ac8d7
Status: Downloaded newer image for hello-world:latest
Hello from Docker!
This message shows that your installation appears to be working correctly.
To generate this message, Docker took the following steps:
1. The Docker client contacted the Docker daemon.
2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
3. The Docker daemon created a new container from that image which runs the
executable that produces the output you are currently reading.
4. The Docker daemon streamed that output to the Docker client, which sent it
to your terminal.
To try something more ambitious, you can run an Ubuntu container with:
$ docker run -it ubuntu bash
Share images, automate workflows, and more with a free Docker ID:
https://cloud.docker.com/
For more examples and ideas, visit:
https://docs.docker.com/engine/userguide/
$ docker version
Client:
Version: 17.03.1-ce
API version: 1.27
Go version: go1.7.5
Git commit: c6d412e
Built: Tue Mar 28 00:40:02 2017
OS/Arch: darwin/amd64
Server:
Version: 17.03.1-ce
API version: 1.27 (minimum version 1.12)
Go version: go1.7.5
Git commit: c6d412e
Built: Fri Mar 24 00:00:50 2017
OS/Arch: linux/amd64
Experimental: true
If you are going to use docker-machine
to create virtual machines, install VirtualBox.
brew cask install virtualbox
Note that if VirtualBox is not installed, then docker-machine
fails with the following error.
$ docker-machine create manager
Running pre-create checks...
Error with pre-create check: "VBoxManage not found. Make sure VirtualBox is installed and VBoxManage is in the path"
Use document.getElementsByClassName('className').style = your_style
.
var d = document.getElementsByClassName("left1");
d.className = d.className + " otherclass";
Use single quotes for JS strings contained within an html attribute's double quotes
Example
<div class="somelclass"></div>
then document.getElementsByClassName('someclass').style = "NewclassName";
<div class='someclass'></div>
then document.getElementsByClassName("someclass").style = "NewclassName";
This is personal experience.
On my linux system to get just the filenames
diff -q /dir1 /dir2|cut -f2 -d' '
Here is my workaround,
In your example you can add a third element
with "same styles" of .one & .two elements, but without the absolute position and with hidden visibility:
HTML
<article>
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
</article>
CSS
.three{
height: 30px;
z-index: -1;
visibility: hidden;
}
==
and .Equals
are both dependent upon the behavior defined in the actual type and the actual type at the call site. Both are just methods / operators which can be overridden on any type and given any behavior the author so desires. In my experience, I find it's common for people to implement .Equals
on an object but neglect to implement operator ==
. This means that .Equals
will actually measure the equality of the values while ==
will measure whether or not they are the same reference.
When I'm working with a new type whose definition is in flux or writing generic algorithms, I find the best practice is the following
Object.ReferenceEquals
directly (not needed in the generic case)EqualityComparer<T>.Default
In some cases when I feel the usage of ==
is ambiguous I will explicitly use Object.Reference
equals in the code to remove the ambiguity.
Eric Lippert recently did a blog post on the subject of why there are 2 methods of equality in the CLR. It's worth the read
A developer recently added subtitle support to VideoView.
When the MediaPlayer
starts playing a music (or other source), it checks if there is a SubtitleController and shows this message if it's not set.
It doesn't seem to care about if the source you want to play is a music or video. Not sure why he did that.
Short answer: Don't care about this "Exception".
Edit :
Still present in Lollipop,
If MediaPlayer
is only used to play audio files and you really want to remove these errors in the logcat, the code bellow set an empty SubtitleController
to the MediaPlayer
.
It should not be used in production environment and may have some side effects.
static MediaPlayer getMediaPlayer(Context context){
MediaPlayer mediaplayer = new MediaPlayer();
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
return mediaplayer;
}
try {
Class<?> cMediaTimeProvider = Class.forName( "android.media.MediaTimeProvider" );
Class<?> cSubtitleController = Class.forName( "android.media.SubtitleController" );
Class<?> iSubtitleControllerAnchor = Class.forName( "android.media.SubtitleController$Anchor" );
Class<?> iSubtitleControllerListener = Class.forName( "android.media.SubtitleController$Listener" );
Constructor constructor = cSubtitleController.getConstructor(new Class[]{Context.class, cMediaTimeProvider, iSubtitleControllerListener});
Object subtitleInstance = constructor.newInstance(context, null, null);
Field f = cSubtitleController.getDeclaredField("mHandler");
f.setAccessible(true);
try {
f.set(subtitleInstance, new Handler());
}
catch (IllegalAccessException e) {return mediaplayer;}
finally {
f.setAccessible(false);
}
Method setsubtitleanchor = mediaplayer.getClass().getMethod("setSubtitleAnchor", cSubtitleController, iSubtitleControllerAnchor);
setsubtitleanchor.invoke(mediaplayer, subtitleInstance, null);
//Log.e("", "subtitle is setted :p");
} catch (Exception e) {}
return mediaplayer;
}
This code is trying to do the following from the hidden API
SubtitleController sc = new SubtitleController(context, null, null);
sc.mHandler = new Handler();
mediaplayer.setSubtitleAnchor(sc, null)
During recent experience writing a JS interpreter I wrestled plenty with the inner workings of ECMA/JS dates. So, I figure I'll throw in my 2 cents here. Hopefully sharing this stuff will help others with any questions about the differences among browsers in how they handle dates.
All implementations store their date values internally as 64-bit numbers that represent the number of milliseconds (ms) since 1970-01-01 UTC (GMT is the same thing as UTC). This date is the ECMAScript epoch that is also used by other languages such as Java and POSIX systems such as UNIX. Dates occurring after the epoch are positive numbers and dates prior are negative.
The following code is interpreted as the same date in all current browsers, but with the local timezone offset:
Date.parse('1/1/1970'); // 1 January, 1970
In my timezone (EST, which is -05:00), the result is 18000000 because that's how many ms are in 5 hours (it's only 4 hours during daylight savings months). The value will be different in different time zones. This behaviour is specified in ECMA-262 so all browsers do it the same way.
While there is some variance in the input string formats that the major browsers will parse as dates, they essentially interpret them the same as far as time zones and daylight saving is concerned even though parsing is largely implementation dependent.
However, the ISO 8601 format is different. It's one of only two formats outlined in ECMAScript 2015 (ed 6) specifically that must be parsed the same way by all implementations (the other is the format specified for Date.prototype.toString).
But, even for ISO 8601 format strings, some implementations get it wrong. Here is a comparison output of Chrome and Firefox when this answer was originally written for 1/1/1970 (the epoch) on my machine using ISO 8601 format strings that should be parsed to exactly the same value in all implementations:
Date.parse('1970-01-01T00:00:00Z'); // Chrome: 0 FF: 0
Date.parse('1970-01-01T00:00:00-0500'); // Chrome: 18000000 FF: 18000000
Date.parse('1970-01-01T00:00:00'); // Chrome: 0 FF: 18000000
This difference has been fixed as of 2020, but other quirks exist between browsers when parsing ISO 8601 format strings.
But it gets worse. A quirk of ECMA-262 is that the ISO 8601 date–only format (YYYY-MM-DD) is required to be parsed as UTC, whereas ISO 8601 requires it to be parsed as local. Here is the output from FF with the long and short ISO date formats with no time zone specifier.
Date.parse('1970-01-01T00:00:00'); // 18000000
Date.parse('1970-01-01'); // 0
So the first is parsed as local because it's ISO 8601 date and time with no timezone, and the second is parsed as UTC because it's ISO 8601 date only.
So, to answer the original question directly, "YYYY-MM-DD"
is required by ECMA-262 to be interpreted as UTC, while the other is interpreted as local. That's why:
console.log(new Date(Date.parse("Jul 8, 2005")).toString()); // Local
console.log(new Date(Date.parse("2005-07-08")).toString()); // UTC
console.log(new Date(Date.parse("Jul 8, 2005")).toString());
console.log(new Date(Date.parse("2005-07-08T00:00:00")).toString());
The bottom line is this for parsing date strings. The ONLY ISO 8601 string that you can safely parse across browsers is the long form with an offset (either ±HH:mm or "Z"). If you do that you can safely go back and forth between local and UTC time.
console.log(new Date(Date.parse("2005-07-08T00:00:00Z")).toString());
Most current browsers do treat the other input formats equally, including the frequently used '1/1/1970' (M/D/YYYY) and '1/1/1970 00:00:00 AM' (M/D/YYYY hh:mm:ss ap) formats. All of the following formats (except the last) are treated as local time input in all browsers. The output of this code is the same in all browsers in my timezone. The last one is treated as -05:00 regardless of the host timezone because the offset is set in the timestamp:
console.log(Date.parse("1/1/1970"));
console.log(Date.parse("1/1/1970 12:00:00 AM"));
console.log(Date.parse("Thu Jan 01 1970"));
console.log(Date.parse("Thu Jan 01 1970 00:00:00"));
console.log(Date.parse("Thu Jan 01 1970 00:00:00 GMT-0500"));
However, since parsing of even the formats specified in ECMA-262 is not consistent, it is recommended to never rely on the built–in parser and to always manually parse strings, say using a library and provide the format to the parser.
E.g. in moment.js you might write:
let m = moment('1/1/1970', 'M/D/YYYY');
On the output side, all browsers translate time zones the same way but they handle the string formats differently. Here are the toString
functions and what they output. Notice the toUTCString
and toISOString
functions output 5:00 AM on my machine. Also, the timezone name may be an abbreviation and may be different in different implementations.
Converts from UTC to Local time before printing
- toString
- toDateString
- toTimeString
- toLocaleString
- toLocaleDateString
- toLocaleTimeString
Prints the stored UTC time directly
- toUTCString
- toISOString
In Chrome
toString Thu Jan 01 1970 00:00:00 GMT-05:00 (Eastern Standard Time)
toDateString Thu Jan 01 1970
toTimeString 00:00:00 GMT-05:00 (Eastern Standard Time)
toLocaleString 1/1/1970 12:00:00 AM
toLocaleDateString 1/1/1970
toLocaleTimeString 00:00:00 AM
toUTCString Thu, 01 Jan 1970 05:00:00 GMT
toISOString 1970-01-01T05:00:00.000Z
In Firefox
toString Thu Jan 01 1970 00:00:00 GMT-05:00 (Eastern Standard Time)
toDateString Thu Jan 01 1970
toTimeString 00:00:00 GMT-0500 (Eastern Standard Time)
toLocaleString Thursday, January 01, 1970 12:00:00 AM
toLocaleDateString Thursday, January 01, 1970
toLocaleTimeString 12:00:00 AM
toUTCString Thu, 01 Jan 1970 05:00:00 GMT
toISOString 1970-01-01T05:00:00.000Z
I normally don't use the ISO format for string input. The only time that using that format is beneficial to me is when dates need to be sorted as strings. The ISO format is sortable as-is while the others are not. If you have to have cross-browser compatibility, either specify the timezone or use a compatible string format.
The code new Date('12/4/2013').toString()
goes through the following internal pseudo-transformation:
"12/4/2013" -> toUCT -> [storage] -> toLocal -> print "12/4/2013"
I hope this answer was helpful.
While I would have gone with Piotr's answer (because it's all in one line), I was surprised that your sample is closer to your solution than you think. From what you have, you simply assign the model value before you use the Html helper method.
@{Model.RequiredProperty = "default";}
@Html.HiddenFor(model => model.RequiredProperty)
The traditional for loop in Objective-C is inherited from standard C and takes the following form:
for (/* Instantiate local variables*/ ; /* Condition to keep looping. */ ; /* End of loop expressions */)
{
// Do something.
}
For example, to print the numbers from 1 to 10, you could use the for loop:
for (int i = 1; i <= 10; i++)
{
NSLog(@"%d", i);
}
On the other hand, the for in loop was introduced in Objective-C 2.0, and is used to loop through objects in a collection, such as an NSArray instance. For example, to loop through a collection of NSString objects in an NSArray and print them all out, you could use the following format.
for (NSString* currentString in myArrayOfStrings)
{
NSLog(@"%@", currentString);
}
This is logically equivilant to the following traditional for loop:
for (int i = 0; i < [myArrayOfStrings count]; i++)
{
NSLog(@"%@", [myArrayOfStrings objectAtIndex:i]);
}
The advantage of using the for in loop is firstly that it's a lot cleaner code to look at. Secondly, the Objective-C compiler can optimize the for in loop so as the code runs faster than doing the same thing with a traditional for loop.
Hope this helps.
Probably, more intuitive way would be like this
if type(e) is list:
print('Found a list element inside the list')
I am currently responsible for an Excel application with a lot of legacy code. One of the slowest pieces of this code was looping through 500 Rows in 6 Columns, setting conditional formatting formulae for each. The formulae are to identify where the cell contents are non-blank but do not form part of a Named Range, therefore referring twice to the cell itself, originally written as:
=AND(COUNTIF(<rangename>,<cellref>)=0,<cellref><>"")
Obviously the overheads would be much reduced by updating all Cells in each Column (Range) at once. However, as noted above, using ADDRESS(ROW(),COLUMN(),n) does not work in this circumstance, i.e. this does not work:
=AND(COUNTIF(<rangename>,ADDRESS(ROW(),COLUMN(),1))=0,ADDRESS(ROW(),COLUMN(),1)<>"")
I experimented extensively with a blank workbook and could find no way around this, using various alternatives such as ISBLANK. In the end, to get around this, I created two User-Defined Functions (using a tip I found elsewhere on this site):
Public Function returnCellContent() As Variant
returnCellContent = Application.Caller.Value
End Function
Public Function Cell_HasContent() As Boolean
If Application.Caller.Value = "" Then
Cell_HasContent = False
Else
Cell_HasContent = True
End If
End Function
The conditional formula is now:
=AND(COUNTIF(<rangename>,returnCellContent()=0,Cell_HasContent())
which works fine.
This has sped the code up, in Excel 2010, from 5s to 1s. Because this code is run whenever data is loaded into the application, this saving is significant and noticeable to the user. It's also a lot cleaner and reusable.
I've taken the time to post this because I could not find any answers on this site or elsewhere that cover all of the circumstances, whilst I'm sure that there are others who could benefit from the above approach, potentially with much larger numbers of cells to update.
Create your AlphaAnimation
Object that decides how much will be the fading effect of the button, then let it start in the onClickListener
of your buttons
For example :
private AlphaAnimation buttonClick = new AlphaAnimation(1F, 0.8F);
// some code
public void onClick(View v) {
v.startAnimation(buttonClick);
}
of course this is just a way, not the most preferred one, it's just easier
gene_name = no_headers.iloc[1:,[1]]
This creates a DataFrame because you passed a list of columns (single, but still a list). When you later do this:
gene_name[x]
you now have a Series object with a single value. You can't hash the Series.
The solution is to create Series from the start.
gene_type = no_headers.iloc[1:,0]
gene_name = no_headers.iloc[1:,1]
disease_name = no_headers.iloc[1:,2]
Also, where you have orph_dict[gene_name[x]] =+ 1
, I'm guessing that's a typo and you really mean orph_dict[gene_name[x]] += 1
to increment the counter.
extern "C"
is meant to be recognized by a C++ compiler and to notify the compiler that the noted function is (or will be) compiled in C style, so that while linking, it links to the correct version of the function from C.
If the method of this code is not static, you can get a work-around in 5.2 by using get_class($this)
.
class A {
public function create1() {
$class = get_class($this);
return new $class();
}
public function create2() {
return new static();
}
}
class B extends A {
}
$b = new B();
var_dump(get_class($b->create1()), get_class($b->create2()));
The results:
string(1) "B"
string(1) "B"
font-weight: 900;
I had a different issue with Font Awesome 5. Default font-weight should be 900 for FontAwesome icons but I overwrote it to 400 for span and i tags. It just worked, when I corrected it.
Here is the issue reference in their Github page, https://github.com/FortAwesome/Font-Awesome/issues/11946
I hope it will help someone.
To stick with the Maven terms:
http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html#Lifecycle_Reference
use
~/.bash_profile
or
~/.MacOSX/environment.plist
(see Runtime Configuration Guidelines)
You can change the icon in your by adding whatever icon you want to your respective drawable folders, then changing this line in your AndroidManifest.xml file:
android:icon="@drawable/ic_launcher"
to match whatever the name of your icon is in there. Or put your icon as ic_launcher, if they're the same icon. As for what it says, add or change whatever strings match up to that in your res/values/strings.xml file. Then, once again in your AndroidManifest.xml file, change this line:
android:label="@string/app_name"
to whatever the string you have in their. You'll have to do this for the application as a whole, and whichever activities you want, but the lines are the same.
Hope this helps.
Give your inputs ref like this
<input type="text" name="email" placeholder="Email" ref="email" />
<input type="password" name="password" placeholder="Password" ref="password" />
then you can access it in your handleLogin like soo
handleLogin: function(e) {
e.preventDefault();
console.log(this.refs.email.value)
console.log(this.refs.password.value)
}
When everything sounded so complicated, this command worked for me:
keytool -genkey -alias foo -keystore cacerts -dname cn=test -storepass changeit -keypass changeit
When a developer is in trouble, I believe a simple working solution snippet is more than enough for him. Later he could diagnose the root cause and basic understanding related to the issue.
Using the 'close' action on the alert does not work for me, because it removes the alert from the DOM and I need the alert multiple times (I'm posting data with ajax and I show a message to the user on every post). So I created this function that create the alert every time I need it and then starts a timer to close the created alert. I pass into the function the id of the container to which I want to append the alert, the type of alert ('success', 'danger', etc.) and the message. Here is my code:
function showAlert(containerId, alertType, message) {
$("#" + containerId).append('<div class="alert alert-' + alertType + '" id="alert' + containerId + '">' + message + '</div>');
$("#alert" + containerId).alert();
window.setTimeout(function () { $("#alert" + containerId).alert('close'); }, 2000);
}
None of these worked for me. I have pod version 1.5.3 and the correct method was to remove the pods that were not longer needed from the Podfile and then run:
pod update
This updates your Podfile.lock file from your Podfile, removes libraries that have been removed and updates all of your libraries.
pyinstaller unpacks your data into a temporary folder, and stores this directory path in the _MEIPASS2
environment variable. To get the _MEIPASS2
dir in packed-mode and use the local directory in unpacked (development) mode, I use this:
def resource_path(relative):
return os.path.join(
os.environ.get(
"_MEIPASS2",
os.path.abspath(".")
),
relative
)
Output:
# in development
>>> resource_path("app_icon.ico")
"/home/shish/src/my_app/app_icon.ico"
# in production
>>> resource_path("app_icon.ico")
"/tmp/_MEI34121/app_icon.ico"
Use the Len function
length = Len(myString)
Here's the simple way to do It !
string fullPath =openFileDialog1.FileName;
string directory;
directory = fullPath.Substring(0, fullPath.LastIndexOf('\\'));
Here is a simple snippet that converts a XmlNode (recursively) into a hashtable, and groups multiple instances of the same child into an array (as an ArrayList). The Hashtable is usually accepted to convert into JSON by most of the JSON libraries.
protected object convert(XmlNode root){
Hashtable obj = new Hashtable();
for(int i=0,n=root.ChildNodes.Count;i<n;i++){
object result = null;
XmlNode current = root.ChildNodes.Item(i);
if(current.NodeType != XmlNodeType.Text)
result = convert(current);
else{
int resultInt;
double resultFloat;
bool resultBoolean;
if(Int32.TryParse(current.Value, out resultInt)) return resultInt;
if(Double.TryParse(current.Value, out resultFloat)) return resultFloat;
if(Boolean.TryParse(current.Value, out resultBoolean)) return resultBoolean;
return current.Value;
}
if(obj[current.Name] == null)
obj[current.Name] = result;
else if(obj[current.Name].GetType().Equals(typeof(ArrayList)))
((ArrayList)obj[current.Name]).Add(result);
else{
ArrayList collision = new ArrayList();
collision.Add(obj[current.Name]);
collision.Add(result);
obj[current.Name] = collision;
}
}
return obj;
}
function _modulename_getData($field, $table) {
try {
if (empty($field)) {
throw new Exception("The field is undefined.");
}
// rest of code here...
}
catch (Exception $e) {
/*
Here you can either echo the exception message like:
echo $e->getMessage();
Or you can throw the Exception Object $e like:
throw $e;
*/
}
}
You should now use DbFunctions.TruncateTime
var anyCalls = _db.CallLogs.Where(r => DbFunctions.TruncateTime(r.DateTime) == callDateTime.Date).ToList();
.NET can do it with its System.Speech namespace.
You would have to convert to .wav first or capture the audio live from the mic.
Details on implementation can be found here: Transcribing Audio with .NET
This problem comes from a strange quirk within Office/Windows.
After developing the same piece of VBA code and running it hundreds of times (literally) over the last couple days I ran into this problem just now. The only thing that has been different is that just prior to experiencing this perplexing problem I accidentally ended the execution of the VBA code with an unorthodox method.
I cleaned out all temp files, rebooted, etc... When I ran the code again after all of this I still got the issue - before I entered the first loop. It makes sense that "press "Debug" button in the popup, then press twice [Ctrl+Break] and after this can continue without stops" because something in the combination of Office/Windows has not released the execution. It is stuck.
The redundant Ctrl+Break action probably resolves the lingering execution.
From the documentation of the HttpWebRequest.Timeout property:
A Domain Name System (DNS) query may take up to 15 seconds to return or time out. If your request contains a host name that requires resolution and you set Timeout to a value less than 15 seconds, it may take 15 seconds or more before a WebException is thrown to indicate a timeout on your request.
Is it possible that your DNS query is the cause of the timeout?
You could also put non-breaking spaces (&nbsp;) in lieu of the spaces so that they're forced to stay together.
How do I wrap this line of text
- asked by Peter 2 days ago
There's actually a good reason:
The non-static access does not always work, for reasons of ambiguity.
Suppose we have two classes, A and B, the latter being a subclass of A, with static fields with the same name:
public class A {
public static String VALUE = "Aaa";
}
public class B extends A {
public static String VALUE = "Bbb";
}
Direct access to the static variable:
A.VALUE (="Aaa")
B.VALUE (="Bbb")
Indirect access using an instance (gives a compiler warning that VALUE should be statically accessed):
new B().VALUE (="Bbb")
So far, so good, the compiler can guess which static variable to use, the one on the superclass is somehow farther away, seems somehow logical.
Now to the point where it gets tricky: Interfaces can also have static variables.
public interface C {
public static String VALUE = "Ccc";
}
public interface D {
public static String VALUE = "Ddd";
}
Let's remove the static variable from B, and observe following situations:
B implements C, D
B extends A implements C
B extends A implements C, D
B extends A implements C
where A implements D
B extends A implements C
where C extends D
The statement new B().VALUE
is now ambiguous, as the compiler cannot decide which static variable was meant, and will report it as an error:
error: reference to VALUE is ambiguous
both variable VALUE in C and variable VALUE in D match
And that's exactly the reason why static variables should be accessed in a static way.
You could easily use the ng-pattern.
ng-pattern="/^[1-9][0-9]{0,2}(?:,?[0-9]{3}){0,3}(?:\.[0-9]{1,2})?$/"
I had the same issue, what worked for me:
I wanted to show/hide a FAB with an offset before the very bottom of the scrollview. This is the solution I came up with (Kotlin):
scrollview.viewTreeObserver.addOnScrollChangedListener {
if (scrollview.scrollY < scrollview.getChildAt(0).bottom - scrollview.height - offset) {
// fab.hide()
} else {
// fab.show()
}
}
I think this is possible in one case
1.Some of the native music players in android device where handling this,they restrict the music when call is in TelephonyManager.EXTRA_STATE_OFFHOOK (OFFHOOK STATE) so there is no way of playing the background music using native players and some other players like "poweramp music palyer"
2.By using the MediaPlayer class also it is not possible(clearly mentioned in documentation)
3.It is possible only in one case if your developing custom music player(with out using MediaPlayer class) in that implements
AudioManager.OnAudioFocusChangeListener by using this you can get the state of the audiomanager in the below code "focusChange=AUDIOFOCUS_LOSS_TRANSIENT"(this state calls when music is playing in background any incoming call came) this state is completely in developers hand whether to play or pause the music. As according to your requriment as for question you asked if you want to play the music when call is in OFFHOOK STATE dont pause playing music in OFFHOOK STATE .And this is only possible when headset is disabled
AudioManager am = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
OnAudioFocusChangeListener afChangeListener = new OnAudioFocusChangeListener() {
public void onAudioFocusChange(int focusChange) {
if (focusChange == AUDIOFOCUS_LOSS_TRANSIENT
// Pause playback (during incoming call)
} else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
// Resume playback (incoming call ends)
} else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
am.unregisterMediaButtonEventReceiver(RemoteControlReceiver);
am.abandonAudioFocus(afChangeListener);
// Stop playback (when any other app playing music in that situation current app stop the audio)
}
}
};
You can try this solution
var d = new Date();
d.setTime(d.getTime());
var expires = "expires="+d.toUTCString();
document.cookie = 'COOKIE_NAME' + "=" + "" + ";domain=domain.com;path=/;" + expires;
Simple using html like this downloads the file mentioned using static keyword
<a href="{% static 'bt.docx' %}" class="btn btn-secondary px-4 py-2 btn-sm">Download CV</a>
NSLocale* currentLocale = [NSLocale currentLocale];
[[NSDate date] descriptionWithLocale:currentLocale];
or use
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
// or @"yyyy-MM-dd hh:mm:ss a" if you prefer the time with AM/PM
NSLog(@"%@",[dateFormatter stringFromDate:[NSDate date]]);
An old thread, but...Answer of Konerak works, but why would you even set size of a container by default. What I prefer is to use code wherever no matter of hog big page size is. So this my code:
<style>
#container {
position: relative;
height: 100%;
}
#footer {
position: absolute;
bottom: 0;
}
</style>
</HEAD>
<BODY>
<div id="container">
<h1>Some heading</h1>
<p>Some text you have</p>
<br>
<br>
<div id="footer"><p>Rights reserved</p></div>
</div>
</BODY>
</HTML>
The trick is in <br>
where you break new line. So, when page is small you'll see footer at bottom of page, as you want.
BUT, when a page is big SO THAT YOU MUST SCROLL IT DOWN, then your footer is going to be 2 new lines under the whole content above. And If you will then make page bigger, your footer is allways going to go DOWN. I hope somebody will find this useful.
Here's the answer of your 2nd question :
location / {
rewrite ^/(.*)$ /$1.php last;
}
it's work for me (based my experience), means that all of your blabla.php will rewrite into blabla
like http://yourwebsite.com/index.php to http://yourwebsite.com/index
Just a small observation: you keep mentioning conn usr\pass, and this is a typo, right? Cos it should be conn usr/pass. Or is it different on a Unix based OS?
Furthermore, just to be sure: if you use tnsnames, your login string will look different from when you use the login method you started this topic out with.
tnsnames.ora should be in $ORACLE_HOME$\network\admin. That is the Oracle home on the machine from which you are trying to connect, so in your case your PC. If you have multiple oracle_homes and wish to use only one tnsnames.ora, you can set environment variable tns_admin (e.g. set TNS_ADMIN=c:\oracle\tns), and place tnsnames.ora in that directory.
Your original method of logging on (usr/[email protected]:port/servicename) should always work. So far I think you have all the info, except for the port number, which I am sure your DBA will be able to give you. If this method still doesn't work, either the server's IP address is not available from your client, or it is a firewall issue (blocking a certain port), or something else not (directly) related to Oracle or SQL*Plus.
hth! Regards, Remco
Genealogical data is cyclic and does not fit into an acyclic graph, so if you have assertions against cycles you should remove them.
The way to handle this in a view without creating a custom view is to treat the cyclic parent as a "ghost" parent. In other words, when a person is both a father and a grandfather to the same person, then the grandfather node is shown normally, but the father node is rendered as a "ghost" node that has a simple label like ("see grandfather") and points to the grandfather.
In order to do calculations you may need to improve your logic to handle cyclic graphs so that a node is not visited more than once if there is a cycle.
That's one of most useless desires of beginner Android developers, and unfortunately it seems to be very popular. How do you define "close" an Android application? Hide it's user interface? Interrupt background work? Stop handling broadcasts?
Android applications are a set of modules, bundled in an .apk and exposed to the system trough AndroidManifest.xml. Activities can be arranged and re-arranged trough different task stacks, and finish()-ing or any other navigating away from a single Activity may mean totally different things in different situations. Single application can run inside multiple processes, so killing one process doesn't necessary mean there will be no application code left running. And finally, BroadcastReceivers can be called by the system any time, recreating the needed processes if they are not running.
The main thing is that you don't need to stop/kill/close/whatever your app trough a single line of code. Doing so is an indication you missed some important point in Android development. If for some bizarre reason you have to do it, you need to finish() all Activities, stop all Services and disable all BroadcastReceivers declared in AndroidManifest.xml. That's not a single line of code, and maybe launching the Activity that uninstalls your own application will do the job better.
Drawable drawable = Common.getDrawableFromUrl(this, product.getMapPath());
if (drawable == null) {
drawable = getRandomDrawable();
}
The equals()
method checks for value equality, which means that it compares the contents of two objects. Since null
is not an object, this crashes when trying to compare the contents of your object to the contents of null
.
The ==
operator checks for reference equality, which means that it looks whether the two objects are actually the very same object. This does not require the objects to actually exist; two nonexistent objects (null
references) are also equal.
Also have a look into the built-in DataFrame.filter
function.
Minimalistic but greedy approach (sufficient for the given df):
df.filter(regex="[^BD]")
Conservative/lazy approach (exact matches only):
df.filter(regex="^(?!(B|D)$).*$")
Conservative and generic:
exclude_cols = ['B','C']
df.filter(regex="^(?!({0})$).*$".format('|'.join(exclude_cols)))
With the release of RecyclerView library, now you can align a list of images bind with text easily. You can use LinearLayoutManager to specify the direction in which you would like to orient your list, either vertical or horizontal as shown below.
You can download a full working demo from this post
For future people struggling with a similar problem, the situation is that the compiler simply cannot find the type you are using (even if your Intelisense can find it).
This can be caused in many ways:
#include
the header that defines it.#ifndef BLAH_H
) are defective (your #ifndef BLAH_H
doesn't match your #define BALH_H
due to a typo or copy+paste mistake).#define MYHEADER_H
, even if they are in separate directories)new Vector()
should be new Vector<int>()
)NamespaceA::NamespaceB
, AND a <global scope>::NamespaceB
, if you are already within NamespaceA
, it'll look in NamespaceA::NamespaceB
and not bother checking <global scope>::NamespaceB
) unless you explicitly access it.To explicitly access something in the global namespace, prefix it with ::
, as if the global namespace is a namespace with no name (e.g. ::MyType
or ::MyNamespace::MyType
).
alter table table_name add field_name (size);
alter table arnicsc add place number(10);
Android SDK is 32 bit app, and it requires the 32 bit of JDK to work... the 64 bit JDK won't make any use for it...
using java you can do this:
Using the Scanner:
Scanner reader = new Scanner(System.in);
String line = reader.nextLine();
// now you can use some converter to change the String value to the value you need.
// for example Long.parseLong(line) or Integer.parseInt(line) or other type cast
Using the BufferedReader:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line = reader.readLine();
// now you can use some converter to change the String value to the value you need.
// for example Long.parseLong(line) or Integer.parseInt(line) or other type cast
In the two cases you need to pass you Default input, in my case System.in
This doesn't quite yet look like what I want, but I accomplished something like
this by stacking nav pills in the leftmost two spans. This is what my app's
app/views/layouts/application.html.erb
file looks like:
<!DOCTYPE html>
...
<body>
<!-- top navigation bar -->
<div class="navbar navbar-fixed-top">
...
</div>
<div class="container-fluid">
<!-- the navigation buttons bar on the left -->
<div class="sidebar-nav span2"> <!-- we reserve 2 spans out of 12 for this -->
<ul class="nav nav-pills nav-stacked">
<li class="<%= current_page?(root_path) ? 'active' : 'inactive' %>">
<%= link_to "Home", root_path %>
</li>
<li class="<%= current_page?(section_a_path) ? 'active' : 'inactive' %>">
<%= link_to "Section A", section_a_path %>
</li>
<li class="<%= current_page?(section_b_path) ? 'active' : 'inactive' %>">
<%= link_to "Section B", section_b_path %>
</li>
</ul>
</div>
<div class="container-fluid span10"> <!-- use the remaining 10 spans -->
<%= flash_messages %>
<%= yield :layout %> <!-- the content page sees a full 12 spans -->
</div>
</div> <!-- class="container-fluid" -->
...
</body>
</html>
Now the stacked pills appear on the top left, below the navbar. When the user clicks on
one of them, the corresponding page loads. From the point of view of
application.html.erb
, that page has the 10 rightmost spans available for it,
but from the page's view, it has the full 12 spans available.
The button corresponding to the page currently being displayed is rendered as
active, and the others as inactive. Specify the colours for active and inactive
buttons in file app/assets/stylesheets/custom.css.scss
(in this case, the
colour for a disabled state is also defined):
@import "bootstrap";
...
$spray: #81c9e2;
$grey_light: #dddddd;
...
.nav-pills {
.inactive > a, .inactive > a:hover {
background-color: $spray;
}
.disabled > a, .disabled > a:hover {
background-color: $grey_light;
}
}
The active pill's colour is not defined, so it appears as the default blue.
File custom.css.scss
is included because of the line *= require_tree .
in
file app/assets/stylesheets/application.css
.
localStorage
is something that is kept on the client side. There is no data transmitted to the server side.
You can only get the data with JavaScript and you can send it to the server side with Ajax.
What is your PHP version? Extension "Mysql" was deprecated in PHP 5.5.0. Use extension Mysqli (like mysqli_query).
cmsjr had the right solution. I just wanted to point out a couple of things for your future trigger development. If you are using the values statement in an insert in a trigger, there is a stong possibility that you are doing the wrong thing. Triggers fire once for each batch of records inserted, deleted, or updated. So if ten records were inserted in one batch, then the trigger fires once. If you are refering to the data in the inserted or deleted and using variables and the values clause then you are only going to get the data for one of those records. This causes data integrity problems. You can fix this by using a set-based insert as cmsjr shows above or by using a cursor. Don't ever choose the cursor path. A cursor in a trigger is a problem waiting to happen as they are slow and may well lock up your table for hours. I removed a cursor from a trigger once and improved an import process from 40 minutes to 45 seconds.
You may think nobody is ever going to add multiple records, but it happens more frequently than most non-database people realize. Don't write a trigger that will not work under all the possible insert, update, delete conditions. Nobody is going to use the one record at a time method when they have to import 1,000,000 sales target records from a new customer or update all the prices by 10% or delete all the records from a vendor whose products you don't sell anymore.
The result of your code will be the same. The reason is that the two incrementation operations can be seen as two distinct function calls. Both functions cause an incrementation of the variable, and only their return values are different. In this case, the return value is just thrown away, which means that there's no distinguishable difference in the output.
However, under the hood there's a difference: The post-incrementation i++
needs to create a temporary variable to store the original value of i
, then performs the incrementation and returns the temporary variable. The pre-incrementation ++i
doesn't create a temporary variable. Sure, any decent optimization setting should be able to optimize this away when the object is something simple like an int
, but remember that the ++-operators are overloaded in more complicated classes like iterators. Since the two overloaded methods might have different operations (one might want to output "Hey, I'm pre-incremented!" to stdout for example) the compiler can't tell whether the methods are equivalent when the return value isn't used (basically because such a compiler would solve the unsolvable halting problem), it needs to use the more expensive post-incrementation version if you write myiterator++
.
Three reasons why you should pre-increment:
I have found this to be the easiest way by far.
Use this method:
public static String getJSON(String url) {
HttpsURLConnection con = null;
try {
URL u = new URL(url);
con = (HttpsURLConnection) u.openConnection();
con.connect();
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
return sb.toString();
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (con != null) {
try {
con.disconnect();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
return null;
}
And use it like this:
String json = getJSON(url);
JSONObject obj;
try {
obj = new JSONObject(json);
JSONArray results_arr = obj.getJSONArray("results");
final int n = results_arr.length();
for (int i = 0; i < n; ++i) {
// get the place id of each object in JSON (Google Search API)
String place_id = results_arr.getJSONObject(i).getString("place_id");
}
}
If you want to select the first gap, use this:
SELECT @r
FROM (
SELECT @r := MIN(id) - 1
FROM t_source2
) vars,
t_source2
WHERE (@r := @r + 1) <> id
ORDER BY
id
LIMIT 1;
There is an ANSI
syntax version of the same query:
SELECT id
FROM mytable mo
WHERE (
SELECT id + 1
FROM mytable mi
WHERE mi.id < mo.id
ORDER BY
mi.id DESC
LIMIT 1
) <> id
ORDER BY
id,
LIMIT 1
however, it will be slow, due to optimizer bug in MySQL
.
OnCreate:
//Add comment fragment
container = FindViewById<FrameLayout>(Resource.Id.frmAttachPicture);
mPictureFragment = new fmtAttachPicture();
var trans = SupportFragmentManager.BeginTransaction();
trans.Add(container.Id, mPictureFragment, "fmtPicture");
trans.Show(mPictureFragment); trans.Commit();
This is how I hide the fragment in click event 1
//Close fragment
var trans = SupportFragmentManager.BeginTransaction();
trans.Hide(mPictureFragment);
trans.AddToBackStack(null);
trans.Commit();
Then Shows it back int event 2
var trans = SupportFragmentManager.BeginTransaction();
trans.Show(mPictureFragment); trans.Commit();
As far as I understand, you create a Movie class:
class Movie
{
private:
std::string _title;
std::string _director;
int _year;
int _rating;
std::vector<std::string> actors;
};
and having such class, you create a vector instance:
std::vector<Movie*> movies;
so, you can add any movie to your movies collection. Since you are creating a vector of pointers to movies, do not forget to free the resources allocated by your movie instances OR you could use some smart pointer to deallocate the movies automatically:
std::vector<shared_ptr<Movie>> movies;
Try running all targets individually to check that all are running correct
run ant target name to run a target individually
e.g. ant build-project
Also the default target you specified is
project basedir="." default="build" name="iControlSilk4J"
This will only execute build-subprojects,build-project and init
$array = array("Jonathan","Sampson");
foreach($array as $value) {
print $value;
}
or
$length = count($array);
for ($i = 0; $i < $length; $i++) {
print $array[$i];
}
In my cases, I solved the problem when using the labs()
instead of abs()
.
Using d.Keys()(i)
method is a very bad idea, because on each call it will re-create a new array (you will have significant speed reduction).
Here is an analogue of Scripting.Dictionary
called "Hash Table" class from @TheTrick, that support such enumerator: http://www.cyberforum.ru/blogs/354370/blog2905.html
Dim oDict As clsTrickHashTable
Sub aaa()
Set oDict = New clsTrickHashTable
oDict.Add "a", "aaa"
oDict.Add "b", "bbb"
For i = 0 To oDict.Count - 1
Debug.Print oDict.Keys(i) & " - " & oDict.Items(i)
Next
End Sub
In addition to what John Skeet said, here's an overview of the Java 7 project. It includes a list and description of the features.
Note: JDK 7 was released on July 28, 2011, so you should now go to the official java SE site.
I added the following to the manifest for that activity
android:configChanges="keyboardHidden|orientation|screenLayout"
You can't pass objects using router params, only strings because it needs to be reflected in the URL. It would be probably a better approach to use a shared service to pass data around between routed components anyway.
The old router allows to pass data
but the new (RC.1
) router doesn't yet.
Update
data
was re-introduced in RC.4
How do I pass data in Angular 2 components while using Routing?
Megabyte means 2^20 bytes. I know that technically that doesn't mesh with the SI units, and that some folks have come up with a new terminology to mean 2^20. None of that matters. Efforts to change the language to "clarify" things are doomed to failure.
Hard-drive manufacturers use it to mean 1,000,000 bytes, because that's what it means in SI so they figure technically they aren't lying (while actually they are). That falls under lies, damn lies, and marketing.
For my case, I was trying to execute procedure code in MySQL, and due to some issue with server in which Server can't figure out where to end the statement I was getting Error Code 1064. So I wrapped the procedure with custom DELIMITER and it worked fine.
For example, Before it was:
DROP PROCEDURE IF EXISTS getStats;
CREATE PROCEDURE `getStats` (param_id INT, param_offset INT, param_startDate datetime, param_endDate datetime)
BEGIN
/*Procedure Code Here*/
END;
After putting DELIMITER it was like this:
DROP PROCEDURE IF EXISTS getStats;
DELIMITER $$
CREATE PROCEDURE `getStats` (param_id INT, param_offset INT, param_startDate datetime, param_endDate datetime)
BEGIN
/*Procedure Code Here*/
END;
$$
DELIMITER ;
i have an error like this, but after
1/
mvn eclipse:clean
mvn eclipse:eclipse -Dwtpversion=2.0
2/ run eclipse, and open the project
3/
mvn package
it's work
Apparently not, my two suggestions are:
char dirpath[80] = "/path/to/some/directory";
sprintf(mkcmd, "mkdir -p %s", dirpath);
system(mkcmd);
Or if you don't want to use system()
try looking at the coreutils mkdir
source code and see how they implemented the -p
option.
Use expandRows()
from the splitstackshape
package:
library(splitstackshape)
expandRows(df, "freq")
Simple syntax, very fast, works on data.frame
or data.table
.
Result:
var1 var2
1 a d
2 b e
2.1 b e
3 c f
3.1 c f
3.2 c f
For Swift 5
Remove Cell
let indexPath = [NSIndexPath(row: yourArray-1, section: 0)]
yourArray.remove(at: buttonTag)
self.tableView.beginUpdates()
self.tableView.deleteRows(at: indexPath as [IndexPath] , with: .fade)
self.tableView.endUpdates()
self.tableView.reloadData()// Not mendatory, But In my case its requires
Add new cell
yourArray.append(4)
tableView.beginUpdates()
tableView.insertRows(at: [
(NSIndexPath(row: yourArray.count-1, section: 0) as IndexPath)], with: .automatic)
tableView.endUpdates()
You could do the following:
pg_dump -h <host ip address> -U <host db user name> -t <host table> > <host database> | psql -h localhost -d <local database> -U <local db user>
I've been working on this problem of ditching those irritable Google error pages today. It is possible with the Android example code seen above and in plenty of other forums (ask how I know):
wv.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
if (view.canGoBack()) {
view.goBack();
}
Toast.makeText(getBaseContext(), description, Toast.LENGTH_LONG).show();
}
}
});
IF you put it in shouldOverrideUrlLoading() as one more webclient. At least, this is working for me on my 2.3.6 device. We'll see where else it works later. That would only depress me now, I'm sure. The goBack bit is mine. You may not want it.
No one has ever suggested a RegExp solution. So here is one:
Function TrimTrailingLineBreak(pText)
Dim oRE: Set oRE = New RegExp: oRE.Global = True
oRE.Pattern = "(.*?)(\n|(\r\n)){1}$"
TrimTrailingLineBreak = oRE.Replace(pText, "$1")
End Function
It captures and returns everything up until a single ({1}
) trailing new line (\n
), or carriage return & new line (\r\n
), at the end of the text ($
).
To remove all trailing line breaks change {1}
to *
.
And to remove all trailing whitespace (including line breaks) use oRE.Pattern = "(.*?)\s*$"
.
Something that your code doesn't account for is displaying multiple errors. As you have noted above it is possible for the user to upload a file >2MB of the wrong type, but your code can only report one of the issues. Try something like:
if(isset($_FILES['uploaded_file'])) {
$errors = array();
$maxsize = 2097152;
$acceptable = array(
'application/pdf',
'image/jpeg',
'image/jpg',
'image/gif',
'image/png'
);
if(($_FILES['uploaded_file']['size'] >= $maxsize) || ($_FILES["uploaded_file"]["size"] == 0)) {
$errors[] = 'File too large. File must be less than 2 megabytes.';
}
if((!in_array($_FILES['uploaded_file']['type'], $acceptable)) && (!empty($_FILES["uploaded_file"]["type"]))) {
$errors[] = 'Invalid file type. Only PDF, JPG, GIF and PNG types are accepted.';
}
if(count($errors) === 0) {
move_uploaded_file($_FILES['uploaded_file']['tmpname'], '/store/to/location.file');
} else {
foreach($errors as $error) {
echo '<script>alert("'.$error.'");</script>';
}
die(); //Ensure no more processing is done
}
}
Look into the docs for move_uploaded_file()
(it's called move not store) for more.
I realize this is an old question and has been answered but this could help someone.
In your activity
private ScheduledExecutorService scheduleTaskExecutor;
In onCreate
scheduleTaskExecutor = Executors.newScheduledThreadPool(5);
//Schedule a task to run every 5 seconds (or however long you want)
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
// Do stuff here!
runOnUiThread(new Runnable() {
@Override
public void run() {
// Do stuff to update UI here!
Toast.makeText(MainActivity.this, "Its been 5 seconds", Toast.LENGTH_SHORT).show();
}
});
}
}, 0, 5, TimeUnit.SECONDS); // or .MINUTES, .HOURS etc.
According to the create table statement, the default charset of the table is already utf8mb4. It seems that you have a wrong connection charset.
In Java, set the datasource url like this: jdbc:mysql://127.0.0.1:3306/testdb?useUnicode=true&characterEncoding=utf-8.
"?useUnicode=true&characterEncoding=utf-8" is necessary for using utf8mb4.
It works for my application.
This works just fine for me:
INSERT INTO table VALUES ('', NULLIF('$date',''))
(first ''
increments id field)
You'd need to reverse your collection if you want to use the for each syntax out of the box and go in reverse order.
To optimize the EXISTS
, be very literal; something just has to be there, but you don't actually need any data returned from the correlated sub-query. You're just evaluating a Boolean condition.
So:
WHERE EXISTS (SELECT TOP 1 1 FROM Base WHERE bx.BoxID = Base.BoxID AND [Rank] = 2)
Because the correlated sub-query is RBAR
, the first result hit makes the condition true, and it is processed no further.
Copy Data
INSERT INTO Alfestonline..url_details(url,[status],recycle)
SELECT url,status,recycle FROM AlfestonlineOld..url_details
I have almost same issue with VideoView. I try to play a video (1080*1080) with a Nexus 5 and it works well, but the same video on Galaxy ace 2 give me the Cannot Play Video message.
But I notice that with a lower definition of the video (120x120), it works fine.
So perhaps just a matter of "Size" (and especially with blonde_secretary.3gp video ....)
It depends on what the zip contains. Take a look to see if it got content.jar and artifacts.jar. If it does, it is an archived updated site. Install from it the same way as you install from a remote site.
If the zip doesn't contain content.jar and artifacts.jar, go to your Eclipse install's dropins directory, create a subfolder (name doesn't matter) and expand your zip into that folder. Restart Eclipse.
JObject implements IDictionary, so you can use it that way. For ex,
var cycleJson = JObject.Parse(@"{""name"":""john""}");
//add surname
cycleJson["surname"] = "doe";
//add a complex object
cycleJson["complexObj"] = JObject.FromObject(new { id = 1, name = "test" });
So the final json will be
{
"name": "john",
"surname": "doe",
"complexObj": {
"id": 1,
"name": "test"
}
}
You can also use dynamic
keyword
dynamic cycleJson = JObject.Parse(@"{""name"":""john""}");
cycleJson.surname = "doe";
cycleJson.complexObj = JObject.FromObject(new { id = 1, name = "test" });
Line numbers were added to the IDLE editor two days ago and will appear in the upcoming 3.8.0a3 and later 3.7.5. For new windows, they are off by default, but this can be reversed on the Setting dialog, General tab, Editor section. For existing windows, there is a new Show (Hide) Line Numbers entry on the Options menu. There is currently no hotkey. One can select a line or bloc of lines by clicking on a line or clicking and dragging.
Some people may have missed Edit / Go to Line. The right-click context menu Goto File/Line works on grep (Find in Files) output as well as on trackbacks.
Your team's advice is almost right, except for the mistake that was made. Once you find out why, you will never forget it. Take a look at this mistake.
/^(7|8|9)\d{9}$/
What this does:
^
and $
denotes anchored matches, which asserts that the subpattern in between these anchors are the entire match. The string will only match if the subpattern matches the entirety of it, not just a section.()
denotes a capturing group.7|8|9
denotes matching either of 7
, 8
, or 9
. It does this with alternations, which is what the pipe operator |
does — alternating between alternations. This backtracks between alternations: If the first alternation is not matched, the engine has to return before the pointer location moved during the match of the alternation, to continue matching the next alternation; Whereas the character class can advance sequentially. See this match on a regex engine with optimizations disabled:Pattern: (r|f)at
Match string: carat
Pattern: [rf]at
Match string: carat
\d{9}
matches nine digits. \d
is a shorthanded metacharacter, which matches any digits./^[7|8|9][\d]{9}$/
Look at what it does:
^
and $
denotes anchored matches as well.[7|8|9]
is a character class. Any characters from the list 7
, |
, 8
, |
, or 9
can be matched, thus the |
was added in incorrectly. This matches without backtracking.[\d]
is a character class that inhabits the metacharacter \d
. The combination of the use of a character class and a single metacharacter is a bad idea, by the way, since the layer of abstraction can slow down the match, but this is only an implementation detail and only applies to a few of regex implementations. JavaScript is not one, but it does make the subpattern slightly longer.{9}
indicates the previous single construct is repeated nine times in total.The optimal regex is /^[789]\d{9}$/
, because /^(7|8|9)\d{9}$/
captures unnecessarily which imposes a performance decrease on most regex implementations (javascript happens to be one, considering the question uses keyword var
in code, this probably is JavaScript). The use of php which runs on PCRE for preg matching will optimize away the lack of backtracking, however we're not in PHP either, so using classes []
instead of alternations |
gives performance bonus as the match does not backtrack, and therefore both matches and fails faster than using your previous regular expression.
I suspect this is what the numpy diff command does anyway, but just for completeness you can simply difference the sub-vectors:
from numpy import array as a
a(x[1:])-a(x[:-1])
In addition, I wanted to add these solutions to generalizations of the question:
Solution with periodic boundaries
Sometimes with numerical integration you will want to difference a list with periodic boundary conditions (so the first element calculates the difference to the last. In this case the numpy.roll function is helpful:
v-np.roll(v,1)
Solutions with zero prepended
Another numpy solution (just for completeness) is to use
numpy.ediff1d(v)
This works as numpy.diff, but only on a vector (it flattens the input array). It offers the ability to prepend or append numbers to the resulting vector. This is useful when handling accumulated fields that is often the case fluxes in meteorological variables (e.g. rain, latent heat etc), as you want a resulting list of the same length as the input variable, with the first entry untouched.
Then you would write
np.ediff1d(v,to_begin=v[0])
Of course, you can also do this with the np.diff command, in this case though you need to prepend zero to the series with the prepend keyword:
np.diff(v,prepend=0.0)
All the above solutions return a vector that is the same length as the input.
the split() method takes a regular expression as an argument
table {
border-collapse:collapse;
}
You need to specify which column of the datarow you want to pull data from.
Try the following:
StringBuilder output = new StringBuilder();
foreach (DataRow rows in results.Tables[0].Rows)
{
foreach (DataColumn col in results.Tables[0].Columns)
{
output.AppendFormat("{0} ", rows[col]);
}
output.AppendLine();
}
For Swagger API 3.0, generating Html2 client code from online Swagger Editor works great for me!
More about string can be found in String Class and String Tutorials
Use this
SELECT *
FROM TableToSearch
WHERE NOT REGEXP_LIKE(ColumnToSearch, '^-?[0-9]+(\.[0-9]+)?$');
Yes, in API level 26
it's deprecated. Instead, you can use progressBar
.
To create it programmatically:
First get a reference to the root layout
RelativeLayout layout = findViewById(R.id.display); //specify here Root layout Id
or
RelativeLayout layout = findViewById(this);
Then add the progress bar
progressBar = new ProgressBar(youractivity.this, null, android.R.attr.progressBarStyleLarge);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(100, 100);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
layout.addView(progressBar, params);
To show the progress bar
progressBar.setVisibility(View.VISIBLE);
To hide the progress bar
progressBar.setVisibility(View.GONE);
To disable the user interaction you just need to add the following code
getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
To get user interaction back you just need to add the following code
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
Just for future reference, change the android.R.attr.progressBarStyleSmall
to android.R.attr.progressBarStyleHorizontal
.
The code below only works above API level 21
progressBar.setProgressTintList(ColorStateList.valueOf(Color.RED));
To create it via xml:
<ProgressBar
android:id="@+id/progressbar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:indeterminate="true"
android:max="100"
android:backgroundTint="@color/white"
android:layout_below="@+id/framelauout"
android:indeterminateTint="#1a09d6"
android:layout_marginTop="-7dp"/>
In your activity
progressBar = (ProgressBar) findViewById(R.id.progressbar);
Showing/hiding the progress bar is the same
progressBar.setVisibility(View.VISIBLE); // To show the ProgressBar
progressBar.setVisibility(View.INVISIBLE); // To hide the ProgressBar
Here is a sample image of what it would look like:
For more details:
1. Reference one
2. Reference Two
In order to represent a single digit in the form of a regular expression you can use either:
[0-9] or \d
In order to specify how many times the number appears you would add
[0-9]*: the star means there are zero or more digits
[0-9]{2}: {N} means N digits
[0-9]{0,2}: {N,M} N digits or M digits
[0-9]{0-9}: {N-M} N digits to M digits. Note: M can be left blank for an infinite representation
Lets say I want to represent a number between 1 and 99 I would express it as such:
[0-9]{1-2} or [0-9]{1,2} or \d{1-2} or \d{1,2}
Or lets say we were working with binary display, displaying a byte size, we would want our digits to be between 0 and 1 and length of a byte size, 8, so we would represent it as follows:
[0-1]{8} representation of a binary byte
Then if you want to add a , or a . symbol you would use:
\, or \. or you can use [.] or [,]
You can also state a selection between possible values as such
[.,] means either a dot or a comma symbol
And you just need to concatenate the pieces together, so in the case where you want to represent a 1 or 2 digit number followed by either a comma or a period and followed by two more digits you would express it as follows: >
[0-9]{1,2}[.,]\d{1-2}
Also note that regular expression strings inside C++ strings must be double-back-slashed so every \ becomes \\
If the set of colors is more or less fixed, the most efficient and also most readable way would be to use string constants in your app and then use MySQL's SET
type with FIND_IN_SET('red',colors)
in your queries. When using the SET
type with FIND_IN_SET, MySQL uses one integer to store all values and uses binary "and"
operation to check for presence of values which is way more efficient than scanning a comma-separated string.
In SET('red','blue','green')
, 'red'
would be stored internally as 1
, 'blue'
would be stored internally as 2
and 'green'
would be stored internally as 4
. The value 'red,blue'
would be stored as 3
(1|2
) and 'red,green'
as 5
(1|4
).
You can able to download Xcode DMG file from the
I solved this with one code line, as follow: In file index.php, at your template root, after this code line:
defined( '_JEXEC' ) or die( 'Restricted access' );
paste this line: ini_set ('display_errors', 'Off');
Don't worry, be happy...
posted by Jenio.
Try this... Worked for me and printed 10/22/2013 01:37:56 AM
Ofcourse this is your code only with little modifications.
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC")); // This line converts the given date into UTC time zone
final java.util.Date dateObj = sdf.parse("2013-10-22T01:37:56");
aRevisedDate = new SimpleDateFormat("MM/dd/yyyy KK:mm:ss a").format(dateObj);
System.out.println(aRevisedDate);
Tested below for Linux: You can directly download pip from https://pypi.org/simple/pip/ untar and use directly with your latest python.
tar -xvf pip-0.2.tar.gz
cd pip-0.2
Check for the contents.
anant$ ls
docs pip.egg-info pip-log.txt pip.py PKG-INFO regen-docs scripts setup.cfg setup.py tests
Execute directly:
anant$ python pip.py --help
Usage: pip.py COMMAND [OPTIONS]
Options:
--version show program's version number and exit
-h, --help show this help message and exit
-E DIR, --environment=DIR
virtualenv environment to run pip in (either give the
interpreter or the environment base directory)
-v, --verbose Give more output
-q, --quiet Give less output
--log=FILENAME Log file where a complete (maximum verbosity) record
will be kept
--proxy=PROXY Specify a proxy in the form
user:[email protected]:port. Note that the
user:password@ is optional and required only if you
are behind an authenticated proxy. If you provide
[email protected]:port then you will be prompted for a
password.
--timeout=SECONDS Set the socket timeout (default 15 seconds)
Concat gives the flexibility to join based on the axis( all rows or all columns)
Append is the specific case(axis=0, join='outer') of concat
Join is based on the indexes (set by set_index) on how variable =['left','right','inner','couter']
Merge is based on any particular column each of the two dataframes, this columns are variables on like 'left_on', 'right_on', 'on'
React router V4 now allows the history prop to be used as below:
this.props.history.push("/dummy",value)
The value then can be accessed wherever the location prop is available as
state:{value}
not component state.
Well, to use it i dont think matters (similar to disabled and readonly), personally i use checked="checked" but if you are trying to manipulate them with JavaScript, you use true/false
Add one more slash after file://
in the value of xsi:schemaLocation
. (You have two; you need three. Think protocol://host/path
where protocol
is 'file'
and host
is empty here, yielding three slashes in a row.) You can also eliminate the double slashes along the path
. I believe that the double slashes help with file systems that allow spaces in file and directory names, but you wisely avoided that complication in your path naming.
xsi:schemaLocation="http://www.w3schools.com file:///C:/environment/workspace/maven-ws/ProjextXmlSchema/email.xsd"
Still not working? I suggest that you carefully copy the full file specification for the XSD into the address bar of Chrome or Firefox:
file:///C:/environment/workspace/maven-ws/ProjextXmlSchema/email.xsd
If the XSD does not display in the browser, delete all but the last component of the path (email.xsd) and see if you can't display the parent directory. Continue in this manner, walking up the directory structure until you discover where the path diverges from the reality of your local filesystem.
If the XSD does displayed in the browser, state what XML processor you're using, and be prepared to hear that it's broken or that you must work around some limitation. I can tell you that the above fix will work with my Xerces-J-based validator.
John is an optional Person, meaning it can hold a value or be nil.
john.apartment = number73
is used if john is not an optional. Since john is never nil we can be sure it won't call apartment on a nil value. While
john!.apartment = number73
promises the compiler that john is not nil then unwraps the optional to get john's value and accesses john's apartment property. Use this if you know that john is not nil. If you call this on a nil optional, you'll get a runtime error.
The documentation includes a nice example for using this where convertedNumber is an optional.
if convertedNumber {
println("\(possibleNumber) has an integer value of \(convertedNumber!)")
} else {
println("\(possibleNumber) could not be converted to an integer")
}
i like this clever syntax to do async work from an entrypoint
void async function main() {
await doSomeWork()
await doMoreWork()
}()
I think buffers are e.g. useful when interfacing python to native libraries. (Guido van Rossum explains buffer
in this mailinglist post).
For example, numpy seems to use buffer for efficient data storage:
import numpy
a = numpy.ndarray(1000000)
the a.data
is a:
<read-write buffer for 0x1d7b410, size 8000000, offset 0 at 0x1e353b0>
At the beginning of your file you set raw_input
to 0. Do not do this, at it modifies the built-in raw_input()
function. Therefore, whenever you call raw_input()
, it is essentially calling 0()
, which raises the error. To remove the error, remove the first line of your code:
M = 1.6
# Miles to Kilometers
# Celsius Celsius = (var1 - 32) * 5/9
# Gallons to liters Gallons = 3.6
# Pounds to kilograms Pounds = 0.45
# Inches to centimete Inches = 2.54
def intro():
print("Welcome! This program will convert measures for you.")
main()
def main():
print("Select operation.")
print("1.Miles to Kilometers")
print("2.Fahrenheit to Celsius")
print("3.Gallons to liters")
print("4.Pounds to kilograms")
print("5.Inches to centimeters")
choice = input("Enter your choice by number: ")
if choice == '1':
convertMK()
elif choice == '2':
converCF()
elif choice == '3':
convertGL()
elif choice == '4':
convertPK()
elif choice == '5':
convertPK()
else:
print("Error")
def convertMK():
input_M = float(raw_input(("Miles: ")))
M_conv = (M) * input_M
print("Kilometers: %f\n" % M_conv)
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print("I didn't quite understand that answer. Terminating.")
main()
def converCF():
input_F = float(raw_input(("Fahrenheit: ")))
F_conv = (input_F - 32) * 5/9
print("Celcius: %f\n") % F_conv
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print("I didn't quite understand that answer. Terminating.")
main()
def convertGL():
input_G = float(raw_input(("Gallons: ")))
G_conv = input_G * 3.6
print("Centimeters: %f\n" % G_conv)
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def convertPK():
input_P = float(raw_input(("Pounds: ")))
P_conv = input_P * 0.45
print("Centimeters: %f\n" % P_conv)
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def convertIC():
input_cm = float(raw_input(("Inches: ")))
inches_conv = input_cm * 2.54
print("Centimeters: %f\n" % inches_conv)
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def end():
print("This program will close.")
exit()
intro()
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {_x000D_
var target = $(e.target).attr("href") // activated tab_x000D_
alert(target);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<ul id="myTab" class="nav nav-tabs">_x000D_
<li class="active"><a href="#home" data-toggle="tab">Home</a></li>_x000D_
<li class=""><a href="#profile" data-toggle="tab">Profile</a></li>_x000D_
</ul>_x000D_
<div id="myTabContent" class="tab-content">_x000D_
<div class="tab-pane fade active in" id="home">_x000D_
home tab!_x000D_
</div>_x000D_
<div class="tab-pane fade" id="profile">_x000D_
profile tab!_x000D_
</div>_x000D_
</div>
_x000D_
so you can use parent() to reach to the parent tr and then use find to gather the td with class two
var Something = $(this).parent().find(".two").html();
or
var Something = $(this).parent().parent().find(".two").html();
use as much as parent() what ever the depth of the clicked object according to the tr row
hope this works...
The @Profile annotation allows you to indicate that a component is eligible for registration when one or more specified profiles are active. Using our example above, we can rewrite the dataSource configuration as follows:
@Configuration
@Profile("dev")
public class StandaloneDataConfig {
@Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.HSQL)
.addScript("classpath:com/bank/config/sql/schema.sql")
.addScript("classpath:com/bank/config/sql/test-data.sql")
.build();
}
}
And other one:
@Configuration
@Profile("production")
public class JndiDataConfig {
@Bean(destroyMethod="")
public DataSource dataSource() throws Exception {
Context ctx = new InitialContext();
return (DataSource) ctx.lookup("java:comp/env/jdbc/datasource");
}
}
The following regex extract anything between the parenthesis:
PS> $prog = [regex]::match($s,'\(([^\)]+)\)').Groups[1].Value
PS> $prog
SUB RAD MSD 50R III
Explanation (created with RegexBuddy)
Match the character '(' literally «\(»
Match the regular expression below and capture its match into backreference number 1 «([^\)]+)»
Match any character that is NOT a ) character «[^\)]+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the character ')' literally «\)»
Check these links:
See the docs from django: https://docs.djangoproject.com/en/dev/ref/models/querysets/#latest
You need to specify a field in latest(). eg.
obj= Model.objects.filter(testfield=12).latest('testfield')
Or if your model’s Meta specifies get_latest_by, you can leave off the field_name
argument to earliest() or latest()
. Django will use the field specified in get_latest_by
by default.
For those still looking a solved it this way inside a class with a function sortByDate, see the code below
<?php
class ContactsController
{
public function __construct()
{
//
}
function sortByDate($key)
{
return function ($a, $b) use ($key) {
$t1 = strtotime($a[$key]);
$t2 = strtotime($b[$key]);
return $t2-$t1;
};
}
public function index()
{
$data[] = array('contact' => '434343434', 'name' => 'dickson','updated_at' =>'2020-06-11 12:38:23','created_at' =>'2020-06-11 12:38:23');
$data[] = array('contact' => '434343434', 'name' => 'dickson','updated_at' =>'2020-06-16 12:38:23','created_at' =>'2020-06-10 12:38:23');
$data[] = array('contact' => '434343434', 'name' => 'dickson','updated_at' =>'2020-06-7 12:38:23','created_at' =>'2020-06-9 12:38:23');
usort($data, $this->sortByDate('updated_at'));
//usort($data, $this->sortByDate('created_at'));
echo $data;
}
}
No one mentioned the short form of the .format
method:
Needs at least Python 3.6
f"{Decimal('40800000000.00000000000000'):.2E}"
(I believe it's the same as Cees Timmerman, just a bit shorter)
The initiale code must have borderBottomLeftRadius: 0px
$('#user_button').toggle().css('borderBottomLeftRadius','+5px');
This is a convention that programmer usually use to identify different file names for include files. So that if the other developers is working on their code, he can easily identify why this file is there and what is purpose of this file by just seeing the name of the file.
I don't know what your exact problem is, but if you're receiving XML and want to return JSON (or something) you could also look at JAX-B. This is a standard for marshalling/unmarshalling Java POJO's to XML and/or Json. There are multiple libraries that implement JAX-B, for example Apache's CXF.
As well you can use:
mysql> show status like '%onn%';
+--------------------------+-------+
| Variable_name | Value |
+--------------------------+-------+
| Aborted_connects | 0 |
| Connections | 303 |
| Max_used_connections | 127 |
| Ssl_client_connects | 0 |
| Ssl_connect_renegotiates | 0 |
| Ssl_finished_connects | 0 |
| Threads_connected | 127 |
+--------------------------+-------+
7 rows in set (0.01 sec)
Feel free to use Mysql-server-status-variables or Too-many-connections-problem
click the
ctrl+shift+/
and write anything you and evrything will be in comments
like Answers above, if you do bootstrap 4 just add few line of css to .carousel , carousel-inner ,carousel-item and img as follows
.carousel .carousel-inner{
height:500px
}
.carousel-inner .carousel-item img{
min-height:200px;
//prevent it from stretch in screen size < than 768px
object-fit:cover
}
@media(max-width:768px){
.carousel .carousel-inner{
//prevent it from adding a white space between carousel and container elements
height:auto
}
}
This thread is a little old, and I am brand new to this, but I think I found the preferred solution.
First, I assume that you are using Eclipse and the Android ADT plugin.
In Eclipse, choose Window/Android SDK Manager. In the display, expand the entry for the MOST RECENT PLATFORM, even if that is not the platform that your are developing for. As of Jan 2012, it is "Android 4.0.3 (API 15)". When expanded, the first entry is "Documentation for Android SDK" Click the checkbox next to it, and then click the "Install" button.
When done, you should have a new directory in your "android-sdks" called "doc". Look for "offline.html" in there. Since this is packaged with the most recent version, it will document the most recent platform, but it should also show the APIs for previous versions.
Try this:
git commit --amend
Then copy and paste the Change-Id: I55862204ef71f69bc88c79fe2259f7cb8365699a
at the end of the file.
Save it and push it again!
<link href="https://fonts.googleapis.com/css?family=(any font of your
choice)" rel="stylesheet" type="text/css">
To choose the font you can visit the link : https://fonts.google.com
Write the font name of your choice from the website excluding the brackets.
For example you chose Lobster as a font of your choice then,
<link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet"
type="text/css">
Then you can use this normally as a font-family in your whole HTML/CSS file.
For example
<h2 style="Lobster">Please Like This Answer</h2>
On android 2.2 you can input multiple language and switch by sliding on the spacebar. Go in the settings under "language and keyboard" and then "Android Keyboard", "Input language".
Hope this helps.
I fixed my problem with the following code:
<div style="width: 180px; overflow: hidden;">_x000D_
<select style="width: auto;" name="abc" id="10">_x000D_
<option value="-1">AAAAAAAAAAA</option>_x000D_
<option value="123">123</option>_x000D_
</select>_x000D_
</div>
_x000D_
Hope it helps!
By creating the increment table you should be aware not to delete inserted rows. reason for this is to avoid storing large dumb data in db with ID-s in it. Otherwise in case of mysql restart it would get max existing row and continue increment from that point as mention in documentation http://dev.mysql.com/doc/refman/5.0/en/innodb-auto-increment-handling.html
$(document).ready(function() {
$('#Button').click(function() {
$(this).addClass('active');
});
});
should do the trick. unless you're loading the button with ajax. In which case you could do:
$('#Button').live('click', function() {...
Also remember not to use the same id more than once in your html code.
In case that might help, I found a workaround for a similar problem, looking at the cmake doc : https://cmake.org/cmake/help/v3.0/module/FindPythonLibs.html
You must set two env vars for cmake to find coherent versions. Unfortunately this is not a generic solution...
cmake -DPYTHON_LIBRARY=${HOME}/.pyenv/versions/3.8.0/lib/libpython3.8.a -DPYTHON_INCLUDE_DIR=${HOME}/.pyenv/versions/3.8.0/include/python3.8/ cern_root/
I had a look at the above answers and honestly none of them I find satisfactory. What you want to do is essentially mimic the Perl split functionality. Why Java doesn't allow this and have a join() method somewhere is beyond me but I digress. You don't even need a class for this really. Its just a function. Run this sample program:
Some of the earlier answers have excessive null-checking, which I recently wrote a response to a question here:
https://stackoverflow.com/users/18393/cletus
Anyway, the code:
public class Split {
public static List<String> split(String s, String pattern) {
assert s != null;
assert pattern != null;
return split(s, Pattern.compile(pattern));
}
public static List<String> split(String s, Pattern pattern) {
assert s != null;
assert pattern != null;
Matcher m = pattern.matcher(s);
List<String> ret = new ArrayList<String>();
int start = 0;
while (m.find()) {
ret.add(s.substring(start, m.start()));
ret.add(m.group());
start = m.end();
}
ret.add(start >= s.length() ? "" : s.substring(start));
return ret;
}
private static void testSplit(String s, String pattern) {
System.out.printf("Splitting '%s' with pattern '%s'%n", s, pattern);
List<String> tokens = split(s, pattern);
System.out.printf("Found %d matches%n", tokens.size());
int i = 0;
for (String token : tokens) {
System.out.printf(" %d/%d: '%s'%n", ++i, tokens.size(), token);
}
System.out.println();
}
public static void main(String args[]) {
testSplit("abcdefghij", "z"); // "abcdefghij"
testSplit("abcdefghij", "f"); // "abcde", "f", "ghi"
testSplit("abcdefghij", "j"); // "abcdefghi", "j", ""
testSplit("abcdefghij", "a"); // "", "a", "bcdefghij"
testSplit("abcdefghij", "[bdfh]"); // "a", "b", "c", "d", "e", "f", "g", "h", "ij"
}
}
Some times this problem arise when Application is build in one PC and try to run another PC. And also build the application with Visual Studio 2010.I have the following problem
Problem Description
Stop Working
Problem Signature
Problem Event Name: CLR20r3
Problem Signature 01: diagnosticcentermngr.exe
Problem Signature 02: 1.0.0.0
Problem Signature 03: 4f8c1772
Problem Signature 04: System.Drawing
Problem Signature 05: 2.0.0.0
Problem Signature 06: 4a275e83
Problem Signature 07: 7af
Problem Signature 08: 6c
Problem Signature 09: System.ArgumentException
OS Version: 6.1.7600.2.0.0.256.1
Locale ID: 1033
Read our privacy statement online:
http://go.microsoft.com/fwlink/?linkid=104288&clcid=0x0409
If the online privacy statement is not available, please read our privacy statement offline:
C:\Windows\system32\en-US\erofflps.txt
Dont worry, Please check out following link and install .net framework 4.Although my application .net properties was .net framework 2.
http://www.microsoft.com/download/en/details.aspx?id=17718
restart your PC and try again.
Abramov's goal - and everyone's ideally - is simply to encapsulate complexity (and async calls) in the place where it's most appropriate.
Where's the best place to do that in the standard Redux dataflow? How about:
For me, the try_files
directive in the (currently most voted) answer https://stackoverflow.com/a/11957896/608359 led to rewrite cycles,
*173 rewrite or internal redirection cycle while internally redirecting
I had better luck with the index directive. Note that I used a forward slash before the name, which might or might not be what you want.
server {
listen 443 ssl;
server_name example.com;
root /home/dclo/example;
index /index.html;
error_page 404 /index.html;
# ... ssl configuration
}
In this case, I wanted all paths to lead to /index.html, including when returning a 404.
In Python 2 (3 has different syntax):
What if you can't instantiate your Parent class before you need to call one of its methods?
Use super(ChildClass, self).method()
to access parent methods.
class ParentClass(object):
def method_to_call(self, arg_1):
print arg_1
class ChildClass(ParentClass):
def do_thing(self):
super(ChildClass, self).method_to_call('my arg')
In my case, I had an Object-C file which was also in the same Target Membership. I fixed by adding #import "YourObjectCFileHeader.h"
inside file Bridging-Header.h
Suppose you have below String.
Our Deluxe cabins are warm, cozy & comfortable
var str = $("p").text(); // get the text from <p> tag
$('p').html(str).text(); // Now,decode html entities in your variable i.e
str and assign back to
tag.
that's it.
How about:
DELETE guide_category
WHERE id_guide_category IN (
SELECT id_guide_category
FROM guide_category AS gc
LEFT JOIN guide AS g
ON g.id_guide = gc.id_guide
WHERE g.title IS NULL
)
You should also consider using libraries to do that: they allow limiting and much more:
FineUploader. Demo using validation.itemLimit
as of 5.16.2:
var restrictedUploader = new qq.FineUploader({
validation: {
itemLimit: 3,
}
});
bluimp's jQuery File Upload Plugin. Usage: jquery file upload restricting number of files using maxNumberOfFiles
as of v9.22.0:
$('#fileuploadbasic').fileupload({
maxNumberOfFiles: 6
});
They are also available at https://cdnjs.com/
If you are using .NET 3.5 or newer you can use LINQ extension methods to achieve a "contains" check with the Any
extension method:
if(CartProducts.Any(prod => prod.ID == p.ID))
This will check for the existence of a product within CartProducts
which has an ID matching the ID of p
. You can put any boolean expression after the =>
to perform the check on.
This also has the benefit of working for LINQ-to-SQL queries as well as in-memory queries, where Contains
doesn't.
The two common approaches are to submit the form to an invisible iframe, or to use a Flash control such as YUI Uploader. You could also use Java instead of Flash, but this has a narrower install base.
(Shame about the layout table in the first example)
With Java 8:
hm.forEach((k, v) -> {
System.out.println("Key = " + k + " - " + v);
});
Since you're dealing with values that are just supposed to be boolean anyway, just use ==
and convert the logical response to as.integer
:
df <- data.frame(col = c("true", "true", "false"))
df
# col
# 1 true
# 2 true
# 3 false
df$col <- as.integer(df$col == "true")
df
# col
# 1 1
# 2 1
# 3 0
change the permission for the other user for that type setfacl -m u:username:rw filename
try this
html
<div ng-controller="MyCtrl">
Hello, {{newDate | date:'MM/dd/yyyy'}}!
</div>
JS
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
var collectionDate = '2002-04-26T09:00:00';
$scope.newDate =new Date(collectionDate);
}