TTFB is something that happens behind the scenes. Your browser knows nothing about what happens behind the scenes.
You need to look into what queries are being run and how the website connects to the server.
This article might help understand TTFB, but otherwise you need to dig deeper into your application.
Try (maybe as root)
lsof -i -P
and grep the output for the port you are looking for.
For example to check for port 80 do
lsof -i -P | grep :80
window.location
also affects to the frame,
the best form i found is:
parent.window.location.href
And the worse is:
parent.document.URL
I did a massive browser test, and some rare IE with several plugins get undefined with the second form.
If you are planning to use the code in a production web application code,
using any web framework like Django/Flask, use projects like envparse, using it you can read the value as your defined type.
from envparse import env
# will read WHITE_LIST=hello,world,hi to white_list = ["hello", "world", "hi"]
white_list = env.list("WHITE_LIST", default=[])
# Perfect for reading boolean
DEBUG = env.bool("DEBUG", default=False)
NOTE: kennethreitz's autoenv is a recommended tool for making project specific environment variables, please note that those who are using autoenv
please keep the .env
file private (inaccessible to public)
This is a very common question seen on Stackoverflow.
The important part here is not the command displayed in the error, but what the actual error tells you instead.
a Quick breakdown on why this error is received.
cmd.exe
Being a terminal window relies on input and system Environment variables, in order to perform what you request it to do. it does NOT know the location of everything and it also does not know when to distinguish between commands or executable names which are separated by whitespace like space and tab or commands with whitespace as switch variables.
How do I fix this:
When Actual Command/executable fails
First we make sure, is the executable actually installed? If yes, continue with the rest, if not, install it first.
If you have any executable which you are attempting to run from cmd.exe
then you need to tell cmd.exe
where this file is located. There are 2 ways of doing this.
specify the full path to the file.
"C:\My_Files\mycommand.exe"
Add the location of the file to your environment Variables.
Goto:
------> Control Panel-> System-> Advanced System Settings->Environment Variables
In the System Variables
Window, locate path
and select edit
Now simply add your path to the end of the string, seperated by a semicolon ;
as:
;C:\My_Files\
Save the changes and exit. You need to make sure that ANY cmd.exe
windows you had open are then closed and re-opened to allow it to re-import the environment variables.
Now you should be able to run mycommand.exe from any path, within cmd.exe
as the environment is aware of the path to it.
When C:\Program
or Similar fails
This is a very simple error. Each string after a white space is seen as a different command in cmd.exe
terminal, you simply have to enclose the entire path in double quotes in order for cmd.exe
to see it as a single string, and not separate commands.
So to execute C:\Program Files\My-App\Mobile.exe
simply run as:
"C:\Program Files\My-App\Mobile.exe"
For classes that you create (ie. are not part of the Android) its possible to avoid the crash completely.
Any class that implements finalize()
has some unavoidable probability of crashing as explained by @oba. So instead of using finalizers to perform cleanup, use a PhantomReferenceQueue
.
For an example check out the implementation in React Native: https://github.com/facebook/react-native/blob/master/ReactAndroid/src/main/java/com/facebook/jni/DestructorThread.java
If you know the dimensions of your image, then adding a border to the UIImageView's layer is the best solution AFAIK. Infact, you can simply setFrame your imageView to x,y,image.size.width,image.size.height
In case you have an ImageView of a fixed size with dynamically loaded images which are getting resized (or scaled to AspectFit), then your aim is to resize the imageview to the new resized image.
The shortest way to do this:
// containerView is my UIImageView
containerView.layer.borderWidth = 7;
containerView.layer.borderColor = [UIColor colorWithRed:0.22 green:0.22 blue:0.22 alpha:1.0].CGColor;
// this is the key command
[containerView setFrame:AVMakeRectWithAspectRatioInsideRect(image.size, containerView.frame)];
But to use the AVMakeRectWithAspectRatioInsideRect, you need to add this
#import <AVFoundation/AVFoundation.h>
import statement to your file and also include the AVFoundation framework in your project (comes bundled with the SDK).
Take below reference to convert a JSON into POJO and vice-versa
Let's suppose your JSON schema looks like:
{
"type":"object",
"properties": {
"dataOne": {
"type": "string"
},
"dataTwo": {
"type": "integer"
},
"dataThree": {
"type": "boolean"
}
}
}
Then to covert into POJO, your need to decleare some classes as explained in below style:
==================================
package ;
public class DataOne
{
private String type;
public void setType(String type){
this.type = type;
}
public String getType(){
return this.type;
}
}
==================================
package ;
public class DataTwo
{
private String type;
public void setType(String type){
this.type = type;
}
public String getType(){
return this.type;
}
}
==================================
package ;
public class DataThree
{
private String type;
public void setType(String type){
this.type = type;
}
public String getType(){
return this.type;
}
}
==================================
package ;
public class Properties
{
private DataOne dataOne;
private DataTwo dataTwo;
private DataThree dataThree;
public void setDataOne(DataOne dataOne){
this.dataOne = dataOne;
}
public DataOne getDataOne(){
return this.dataOne;
}
public void setDataTwo(DataTwo dataTwo){
this.dataTwo = dataTwo;
}
public DataTwo getDataTwo(){
return this.dataTwo;
}
public void setDataThree(DataThree dataThree){
this.dataThree = dataThree;
}
public DataThree getDataThree(){
return this.dataThree;
}
}
==================================
package ;
public class Root
{
private String type;
private Properties properties;
public void setType(String type){
this.type = type;
}
public String getType(){
return this.type;
}
public void setProperties(Properties properties){
this.properties = properties;
}
public Properties getProperties(){
return this.properties;
}
}
Another alternative is to use ssh-ident, to manage your ssh identities.
It automatically loads and uses different keys based on your current working directory, ssh options, and so on... which means you can easily have a work/ directory and private/ directory that transparently end up using different keys and identities with ssh.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
if #available(iOS 10, *) {
//Notifications get posted to the function (delegate): func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: () -> Void)"
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
guard error == nil else {
//Display Error.. Handle Error.. etc..
return
}
if granted {
//Do stuff here..
//Register for RemoteNotifications. Your Remote Notifications can display alerts now :)
DispatchQueue.main.async {
application.registerForRemoteNotifications()
}
}
else {
//Handle user denying permissions..
}
}
//Register for remote notifications.. If permission above is NOT granted, all notifications are delivered silently to AppDelegate.
application.registerForRemoteNotifications()
}
else {
let settings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
}
return true
}
The m2e plugin generate project configuration every time when you update project (Maven->Update Project ... That action overrides facets setting configured manually in Eclipse. Therefore you have to configure it on pom level. By setting properties in pom file you can tell m2e plugin what to do.
Enable/Disable the JAX-RS/JPA/JSF Configurators at the pom.xml level The optional JAX-RS, JPA and JSF configurators can be enabled or disabled at a workspace level from Window > Preferences > Maven > Java EE Integration. Now, you can have a finer grain control on these configurators directly from your pom.xml properties :
Adding false in your pom properties section will disable the JAX-RS configurator Adding false in your pom properties section will disable the JPA configurator Adding false in your pom properties section will disable the JSF configurator The pom settings always override the workspace preferences. So if you have, for instance the JPA configurator disabled at the workspace level, using true will enable it on your project anyway. (http://wiki.eclipse.org/M2E-WTP/New_and_Noteworthy/1.0.0)
Hey there, this works for me (I couldn't get this working with the Google API links you were using):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Beef Burrito</title>
<script src="http://code.jquery.com/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="jquery-ui-1.8.1.custom.min.js" type="text/javascript"></script>
</head>
<body>
<div class="draggable" style="border: 1px solid black; width: 50px; height: 50px; position: absolute; top: 0px; left: 0px;">asdasd</div>
<script type="text/javascript">
$(".draggable").draggable();
</script>
</body>
</html>
Install Firebug and then you can use console.log(...)
and console.debug(...)
, etc. (see the documentation for more).
Just for the record:
>>> int('55063.000000')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '55063.000000'
Got me here...
>>> int(float('55063.000000'))
55063.0
Has to be used!
Looking at above, I modified to:
CSS
.divider {
font: 33px sans-serif;
margin-top: 30px;
text-align:center;
text-transform: uppercase;
}
.divider span {
position:relative;
}
.divider span:before, .divider span:after {
border-top: 2px solid #000;
content:"";
position: absolute;
top: 15px;
right: 10em;
bottom: 0;
width: 80%;
}
.divider span:after {
position: absolute;
top: 15px;
left:10em;
right:0;
bottom: 0;
}
HTML
<div class="divider">
<span>This is your title</span></div>
Seems to work fine.
Try below code if you want to use php loop to display
<span>
<select name="birth_month">
<?php for( $m=1; $m<=12; ++$m ) {
$month_label = date('F', mktime(0, 0, 0, $m, 1));
?>
<option value="<?php echo $month_label; ?>"><?php echo $month_label; ?></option>
<?php } ?>
</select>
</span>
<span>
<select name="birth_day">
<?php
$start_date = 1;
$end_date = 31;
for( $j=$start_date; $j<=$end_date; $j++ ) {
echo '<option value='.$j.'>'.$j.'</option>';
}
?>
</select>
</span>
<span>
<select name="birth_year">
<?php
$year = date('Y');
$min = $year - 60;
$max = $year;
for( $i=$max; $i>=$min; $i-- ) {
echo '<option value='.$i.'>'.$i.'</option>';
}
?>
</select>
</span>
There is an alternative - you can provide a member of type XmlSerializerNamespaces in the type to be serialized. Decorate it with the XmlNamespaceDeclarations attribute. Add the namespace prefixes and URIs to that member. Then, any serialization that does not explicitly provide an XmlSerializerNamespaces will use the namespace prefix+URI pairs you have put into your type.
Example code, suppose this is your type:
[XmlRoot(Namespace = "urn:mycompany.2009")]
public class Person {
[XmlAttribute]
public bool Known;
[XmlElement]
public string Name;
[XmlNamespaceDeclarations]
public XmlSerializerNamespaces xmlns;
}
You can do this:
var p = new Person
{
Name = "Charley",
Known = false,
xmlns = new XmlSerializerNamespaces()
}
p.xmlns.Add("",""); // default namespace is emoty
p.xmlns.Add("c", "urn:mycompany.2009");
And that will mean that any serialization of that instance that does not specify its own set of prefix+URI pairs will use the "p" prefix for the "urn:mycompany.2009" namespace. It will also omit the xsi and xsd namespaces.
The difference here is that you are adding the XmlSerializerNamespaces to the type itself, rather than employing it explicitly on a call to XmlSerializer.Serialize(). This means that if an instance of your type is serialized by code you do not own (for example in a webservices stack), and that code does not explicitly provide a XmlSerializerNamespaces, that serializer will use the namespaces provided in the instance.
var dialogName = '#dialog_XYZ';
$.ajax({
url: "/ajax_pages/my_page.ext",
data: {....},
success: function(data) {
$(dialogName ).remove();
$('BODY').append(data);
$(dialogName )
.dialog(options.dialogOptions);
}
});
The Ajax-Request load the Dialog, add them to the Body of the current page and open the Dialog.
If you only whant to load the content you can do:
var dialogName = '#dialog_XYZ';
$.ajax({
url: "/ajax_pages/my_page.ext",
data: {....},
success: function(data) {
$(dialogName).append(data);
$(dialogName )
.dialog(options.dialogOptions);
}
});
How to set a textbox format as 8 digit number(00000019)
string i = TextBox1.Text;
string Key = i.ToString().PadLeft(8, '0');
Response.Write(Key);
It looks like you want to convert the list to a list of numbers
>>> foo = ['-1.2', '0.0', '1']
>>> bar = map(float, foo)
>>> bar
[-1.2, 0.0, 1.0]
>>> min(bar)
-1.2
or if it really is strings you want, that you want to use min
's key
argument
>>> foo = ['-1.2', '0.0', '1']
>>> min(foo, key=float)
'-1.2'
In case you use jQuery you need to wait for $(window).load
, because the embedded SVG document might not be yet loaded at $(document).ready
$(window).load(function () {
//alert("Document loaded, including graphics and embedded documents (like SVG)");
var a = document.getElementById("alphasvg");
//get the inner DOM of alpha.svg
var svgDoc = a.contentDocument;
//get the inner element by id
var delta = svgDoc.getElementById("delta");
delta.addEventListener("mousedown", function(){ alert('hello world!')}, false);
});
using System.Linq;
list.Where(x=> x.Name == nameToExtract);
Edit: misread question (now all matches)
names = [];
$('input[name=text], textarea').each(
function(index){
var input = $(this);
names.push( input.attr('name') );
//input.attr('id');
}
);
it select all textboxes and textarea in your DOM, where $.each function iterates to provide name of ecah element.
EF codefirst will look at your DbContext, and discover all the entity collections declared in it(and also look at entities related to those entities via navigation properties). It will then look at the database you gave it a connection string to, and make sure all of the tables there match the structure of your entities in model. If they do not match, then it cannot read/write to those tables. Anytime you create a new database, or if you change something about the entity class declarations, such as adding properties or changing data types, then it will detect that the model and the database are not in sync. By default it will simply give you the above error. Usually during development what you want to happen is for the database to be recreated(wiping any data) and generated again from your new model structure.
To do that, see "RecreateDatabaseIfModelChanges Feature" in this article: http://weblogs.asp.net/scottgu/archive/2010/07/16/code-first-development-with-entity-framework-4.aspx
You basically need to provide a database initializer that inherits from DropCreateDatabaseIfModelChanges (RecreateDatabaseIfModelChanges is now deprecated). To do this, simply add this line to the Application_Start
method of your Global.asax
file.
Database.SetInitializer<NameOfDbContext>(new DropCreateDatabaseIfModelChanges<NameOfDbContext>());
Once you go to production and no longer want to lose data, then you'd remove this initializer and instead use Database Migrations so that you can deploy changes without losing data.
The function eat
of my package safejoin has such feature, if you give
it a list of data.frames as a second input it will join them
recursively to the first input.
Borrowing and extending the accepted answer's data :
x <- data_frame(i = c("a","b","c"), j = 1:3)
y <- data_frame(i = c("b","c","d"), k = 4:6)
z <- data_frame(i = c("c","d","a"), l = 7:9)
z2 <- data_frame(i = c("a","b","c"), l = rep(100L,3),l2 = rep(100L,3)) # for later
# devtools::install_github("moodymudskipper/safejoin")
library(safejoin)
eat(x, list(y,z), .by = "i")
# # A tibble: 3 x 4
# i j k l
# <chr> <int> <int> <int>
# 1 a 1 NA 9
# 2 b 2 4 NA
# 3 c 3 5 7
We don't have to take all columns, we can use select helpers from tidyselect and
choose (as we start from .x
all .x
columns are kept):
eat(x, list(y,z), starts_with("l") ,.by = "i")
# # A tibble: 3 x 3
# i j l
# <chr> <int> <int>
# 1 a 1 9
# 2 b 2 NA
# 3 c 3 7
or remove specific ones:
eat(x, list(y,z), -starts_with("l") ,.by = "i")
# # A tibble: 3 x 3
# i j k
# <chr> <int> <int>
# 1 a 1 NA
# 2 b 2 4
# 3 c 3 5
If the list is named the names will be used as prefixes :
eat(x, dplyr::lst(y,z), .by = "i")
# # A tibble: 3 x 4
# i j y_k z_l
# <chr> <int> <int> <int>
# 1 a 1 NA 9
# 2 b 2 4 NA
# 3 c 3 5 7
If there are column conflicts the .conflict
argument allows you to resolve it,
for example by taking the first/second one, adding them, coalescing them,
or nesting them.
keep first :
eat(x, list(y, z, z2), .by = "i", .conflict = ~.x)
# # A tibble: 3 x 4
# i j k l
# <chr> <int> <int> <int>
# 1 a 1 NA 9
# 2 b 2 4 NA
# 3 c 3 5 7
keep last:
eat(x, list(y, z, z2), .by = "i", .conflict = ~.y)
# # A tibble: 3 x 4
# i j k l
# <chr> <int> <int> <dbl>
# 1 a 1 NA 100
# 2 b 2 4 100
# 3 c 3 5 100
add:
eat(x, list(y, z, z2), .by = "i", .conflict = `+`)
# # A tibble: 3 x 4
# i j k l
# <chr> <int> <int> <dbl>
# 1 a 1 NA 109
# 2 b 2 4 NA
# 3 c 3 5 107
coalesce:
eat(x, list(y, z, z2), .by = "i", .conflict = dplyr::coalesce)
# # A tibble: 3 x 4
# i j k l
# <chr> <int> <int> <dbl>
# 1 a 1 NA 9
# 2 b 2 4 100
# 3 c 3 5 7
nest:
eat(x, list(y, z, z2), .by = "i", .conflict = ~tibble(first=.x, second=.y))
# # A tibble: 3 x 4
# i j k l$first $second
# <chr> <int> <int> <int> <int>
# 1 a 1 NA 9 100
# 2 b 2 4 NA 100
# 3 c 3 5 7 100
NA
values can be replaced by using the .fill
argument.
eat(x, list(y, z), .by = "i", .fill = 0)
# # A tibble: 3 x 4
# i j k l
# <chr> <int> <dbl> <dbl>
# 1 a 1 0 9
# 2 b 2 4 0
# 3 c 3 5 7
By default it's an enhanced left_join
but all dplyr joins are supported through
the .mode
argument, fuzzy joins are also supported through the match_fun
argument (it's wrapped around the package fuzzyjoin
) or
giving a formula such as ~ X("var1") > Y("var2") & X("var3") < Y("var4")
to the
by
argument.
foo.GetColumnValues(dm.mainColumn, typeof(string))
Alternatively, you could use a generic method:
public void GetColumnValues<T>(object mainColumn)
{
GetColumnValues(mainColumn, typeof(T));
}
and you could then use it like:
foo.GetColumnValues<string>(dm.mainColumn);
div {
border-style: solid;
position: fixed;
width: 80%;
height: 80%;
left: 10%;
top: 10%;
}
Adjust left and top with respect to width and height, that is (100% - 80%) / 2 = 10%
Query to add column with comment are :
alter table table_name
add( "NISFLAG" NUMBER(1,0) )
comment on column "ELIXIR"."PRD_INFO_1"."NISPRODGSTAPPL" is 'comment here'
commit;
is an inline element ..but in css you can change it simply by:- img{display:inline-block;} or img{display:inline-block;} or img{display:inliblock;}
In my case i restart php for and it become ok.
From Prepared statements and stored procedures
Use bindParam
to insert multiple rows with one time binding:
<?php
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
$stmt->bindParam(1, $name);
$stmt->bindParam(2, $value);
// insert one row
$name = 'one';
$value = 1;
$stmt->execute();
// insert another row with different values
$name = 'two';
$value = 2;
$stmt->execute();
If you want to avoid the problem that David Meister posted and you are sure about the number of decimal places, you can replace all dots and commas and divide by 100, ex.:
var value = "2,299.00";
var amount = parseFloat(value.replace(/"|\,|\./g, ''))/100;
or if you have 3 decimals
var value = "2,299.001";
var amount = parseFloat(value.replace(/"|\,|\./g, ''))/1000;
It's up to you if you want to use parseInt, parseFloat or Number. Also If you want to keep the number of decimal places you can use the function .toFixed(...).
In my environment, I just added the two files to class path. And is work fine.
slf4j-jdk14-1.7.25.jar
slf4j-api-1.7.25.jar
see http://editorconfig.org and https://docs.microsoft.com/en-us/visualstudio/ide/create-portable-custom-editor-options?view=vs-2017
If it does not exist, add a new file called .editorconfig for your project
manipulate editor config to use your preferred behaviour.
I prefer spaces over tabs, and CRLF for all code files.
Here's my .editorconfig
# http://editorconfig.org
root = true
[*]
indent_style = space
indent_size = 4
end_of_line = crlf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false
[*.tmpl.html]
indent_size = 4
[*.scss]
indent_size = 2
Mathematically, to get percentage from two numbers:
percentage = (yourNumber / totalNumber) * 100;
And also, to calculate from a percentage :
number = (percentage / 100) * totalNumber;
I too was looking for a fast way to convert decimal number to another base in the range of [2..36] so I developed the following code. Its simple to follow and uses a Stringbuilder object as a proxy for a character buffer that we can index character by character. The code appears to be very fast compared to alternatives and a lot faster than initialising individual characters in a character array.
For your own use you might prefer to: 1/ Return a blank string rather than throw an exception. 2/ remove the radix check to make the method run even faster 3/ Initialise the Stringbuilder object with 32 '0's and remove the the line result.Remove( 0, i );. This will cause the string to be returned with leading zeros and further increase the speed. 4/ Make the Stringbuilder object a static field within the class so no matter how many times the DecimalToBase method is called the Stringbuilder object is only initialised the once. If you do this change 3 above would no longer work.
I hope someone finds this useful :)
AtomicParadox
static string DecimalToBase(int number, int radix)
{
// Check that the radix is between 2 and 36 inclusive
if ( radix < 2 || radix > 36 )
throw new ArgumentException("ConvertToBase(int number, int radix) - Radix must be between 2 and 36.");
// Create a buffer large enough to hold the largest int value represented in binary digits
StringBuilder result = new StringBuilder(" "); // 32 spaces
// The base conversion calculates the digits in reverse order so use
// an index to point to the last unused space in our buffer
int i = 32;
// Convert the number to the new base
do
{
int remainder = number % radix;
number = number / radix;
if(remainder <= 9)
result[--i] = (char)(remainder + '0'); // Converts [0..9] to ASCII ['0'..'9']
else
result[--i] = (char)(remainder + '7'); // Converts [10..36] to ASCII ['A'..'Z']
} while ( number > 0 );
// Remove the unwanted padding from the front of our buffer and return the result
// Note i points to the last unused character in our buffer
result.Remove( 0, i );
return (result.ToString());
}
Bootstrap 4 has two dependencies: jQuery 1.9.1 and popper.js 1.12.3. When you install Bootstrap 4, you need to install these two dependencies.
npm install popper.js@^1.12.3 --save
npm install [email protected] --save
npm install [email protected] --save
For Bootstrap 4.1
npm install popper.js@^1.14.3 --save
npm install [email protected] --save
npm install [email protected] --save
sys.exit()
raises a SystemExit
exception which you are probably assuming as some error. If you want your program not to raise SystemExit but return gracefully, you can wrap your functionality in a function and return from places you are planning to use sys.exit
Update:
Improved and simplified version of previous directive (one instead of two) with same functionality:
.directive('myTestExpression', ['$parse', function ($parse) {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ctrl) {
var expr = attrs.myTestExpression;
var watches = attrs.myTestExpressionWatch;
ctrl.$validators.mytestexpression = function (modelValue, viewValue) {
return expr == undefined || (angular.isString(expr) && expr.length < 1) || $parse(expr)(scope, { $model: modelValue, $view: viewValue }) === true;
};
if (angular.isString(watches)) {
angular.forEach(watches.split(",").filter(function (n) { return !!n; }), function (n) {
scope.$watch(n, function () {
ctrl.$validate();
});
});
}
}
};
}])
Example usage:
<input ng-model="price1"
my-test-expression="$model > 0"
my-test-expression-watch="price2,someOtherWatchedPrice" />
<input ng-model="price2"
my-test-expression="$model > 10"
my-test-expression-watch="price1"
required />
Result: Mutually dependent test expressions where validators are executed on change of other's directive model and current model.
Test expression has local $model
variable which you should use to compare it to other variables.
Previously:
I've made an attempt to improve @Plantface code by adding extra directive. This extra directive very useful if our expression needs to be executed when changes are made in more than one ngModel variables.
.directive('ensureExpression', ['$parse', function($parse) {
return {
restrict: 'A',
require: 'ngModel',
controller: function () { },
scope: true,
link: function (scope, element, attrs, ngModelCtrl) {
scope.validate = function () {
var booleanResult = $parse(attrs.ensureExpression)(scope);
ngModelCtrl.$setValidity('expression', booleanResult);
};
scope.$watch(attrs.ngModel, function(value) {
scope.validate();
});
}
};
}])
.directive('ensureWatch', ['$parse', function ($parse) {
return {
restrict: 'A',
require: 'ensureExpression',
link: function (scope, element, attrs, ctrl) {
angular.forEach(attrs.ensureWatch.split(",").filter(function (n) { return !!n; }), function (n) {
scope.$watch(n, function () {
scope.validate();
});
});
}
};
}])
Example how to use it to make cross validated fields:
<input name="price1"
ng-model="price1"
ensure-expression="price1 > price2"
ensure-watch="price2" />
<input name="price2"
ng-model="price2"
ensure-expression="price2 > price3"
ensure-watch="price3" />
<input name="price3"
ng-model="price3"
ensure-expression="price3 > price1 && price3 > price2"
ensure-watch="price1,price2" />
ensure-expression
is executed to validate model when ng-model
or any of ensure-watch
variables is changed.
I know this is really old, but I'm posting my solution anyways since google finds this thread.
background-image: url('./imagefolder/image.jpg');
That is what I do. Two dots means drill back one directory closer to root ".." while one "." should mean start where you are at as if it were root. I was having similar issues but adding that fixed it for me. You can even leave the "." in it when uploading to your host because it should work fine so long as your directory setup is exactly the same.
You can use printf
:
System.out.printf("string %c\n", 0x63);
You can as well create a String with such formatting, using String#format
:
String s = String.format("string %c", 0x63);
if ("one" !== 1 )
would evaluate as true
, the string "one"
is not equal to the number 1
Just delete key:
HKEY_CURRENT_USER/Software/Microsoft/VCExpress/9.0/Registration
Or run in command line:
reg delete HKCU\Software\Microsoft\VCExpress\9.0\Registration /f
BEGIN
-END
blocks are the building blocks of PL/SQL, and each PL/SQL unit is contained within at least one such block. Nesting BEGIN
-END
blocks within PL/SQL blocks is usually done to trap certain exceptions and handle that special exception and then raise unrelated exceptions. Nevertheless, in PL/SQL you (the client) must always issue a commit or rollback for the transaction.
If you wish to have atomic transactions within a PL/SQL containing transaction, you need to declare a PRAGMA AUTONOMOUS_TRANSACTION
in the declaration block. This will ensure that any DML within that block can be committed or rolledback independently of the containing transaction.
However, you cannot declare this pragma for nested blocks. You can only declare this for:
Reference: Oracle
HQL is much easier to read, easier to debug using tools like the Eclipse Hibernate plugin, and easier to log. Criteria queries are better for building dynamic queries where a lot of the behavior is determined at runtime. If you don't know SQL, I could understand using Criteria queries, but overall I prefer HQL if I know what I want upfront.
On Linux, just run below command at terminal:
$ curl --compressed -o- -L https://yarnpkg.com/install.sh | bash
After do this, close the current terminal and open it again. And then, run below command to check yarn current version:
$ yarn --version
It is a little difficult to answer your specific question without a full, reproducible example. However something like this should work:
#Turn your 'treatment' column into a character vector
data$Treatment <- as.character(data$Treatment)
#Then turn it back into a factor with the levels in the correct order
data$Treatment <- factor(data$Treatment, levels=unique(data$Treatment))
In this example, the order of the factor will be the same as in the data.csv
file.
If you prefer a different order, you can order them by hand:
data$Treatment <- factor(data$Treatment, levels=c("Y", "X", "Z"))
However this is dangerous if you have a lot of levels: if you get any of them wrong, that will cause problems.
Here is a snippet from me in testing... obviously passing via get to the script may not be the best... should post or just send an id and grab guid from db... anyhow.. this worked. I take the URL and convert it to a path.
// Initialize a file URL to the variable
$file = $_GET['url'];
$file = str_replace(Polepluginforrvms_Plugin::$install_url, $DOC_ROOT.'/pole-permitter/', $file );
$quoted = sprintf('"%s"', addcslashes(basename($file), '"\\'));
$size = filesize($file);
header( "Content-type: application/octet-stream" );
header( "Content-Disposition: attachment; filename={$quoted}" );
header( "Content-length: " . $size );
header( "Pragma: no-cache" );
header( "Expires: 0" );
readfile( "{$file}" );
This is the code I ended up using:
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email import Encoders
SUBJECT = "Email Data"
msg = MIMEMultipart()
msg['Subject'] = SUBJECT
msg['From'] = self.EMAIL_FROM
msg['To'] = ', '.join(self.EMAIL_TO)
part = MIMEBase('application', "octet-stream")
part.set_payload(open("text.txt", "rb").read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="text.txt"')
msg.attach(part)
server = smtplib.SMTP(self.EMAIL_SERVER)
server.sendmail(self.EMAIL_FROM, self.EMAIL_TO, msg.as_string())
Code is much the same as Oli's post.
Code based from Binary file email attachment problem post.
An utility method like the following can be used to solve this.
import (
"os"
"path/filepath"
"log"
)
func ensureDir(fileName string) {
dirName := filepath.Dir(fileName)
if _, serr := os.Stat(dirName); serr != nil {
merr := os.MkdirAll(dirName, os.ModePerm)
if merr != nil {
panic(merr)
}
}
}
func main() {
_, cerr := os.Create("a/b/c/d.txt")
if cerr != nil {
log.Fatal("error creating a/b/c", cerr)
}
log.Println("created file in a sub-directory.")
}
Yarn supports this feature:
# .yarnrc file in project root
--modules-folder /node_modules
But your experience can vary depending on which packages you use. I'm not sure you'd want to go into that rabbit hole.
Fields in interfaces are implicitly public static final
. (Also methods are implicitly public, so you can drop the public
keyword.) Even if you use an abstract class instead of an interface, I strongly suggest making all non-constant (public static final
of a primitive or immutable object reference) private
. More generally "prefer composition to inheritance" - a Tile
is-not-a Rectangle
(of course, you can play word games with "is-a" and "has-a").
You don't want a "temporary default Python"
You want the 2.7 scripts to start with
/usr/bin/env python2.7
And you want the 3.2 scripts to begin with
/usr/bin/env python3.2
There's really no use for a "default" Python. And the idea of a "temporary default" is just a road to absolute confusion.
Remember.
Explicit is better than Implicit.
It will work for both iphone and ipad
func showImagePicker() {
var alertStyle = UIAlertController.Style.actionSheet
if (UIDevice.current.userInterfaceIdiom == .pad) {
alertStyle = UIAlertController.Style.alert
}
let alert = UIAlertController(title: "", message: "Upload Attachment", preferredStyle: alertStyle)
alert.addAction(UIAlertAction(title: "Choose from gallery", style: .default , handler:{ (UIAlertAction) in
self.pickPhoto(sourceType: .photoLibrary)
}))
alert.addAction(UIAlertAction(title: "Take Photo", style: .default, handler:{ (UIAlertAction) in
self.pickPhoto(sourceType: .camera)
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler:{ (UIAlertAction) in
}))
present(alert, animated: true, completion: nil)
}
There's no built-in way, you'll have to loop over all of them:
function setAll(a, v) {
var i, n = a.length;
for (i = 0; i < n; ++i) {
a[i] = v;
}
}
http://jsfiddle.net/alnitak/xG88A/
If you really want, do this:
Array.prototype.setAll = function(v) {
var i, n = this.length;
for (i = 0; i < n; ++i) {
this[i] = v;
}
};
and then you could actually do cool.setAll(42)
(see http://jsfiddle.net/alnitak/ee3hb/).
Some people frown upon extending the prototype of built-in types, though.
EDIT ES5 introduced a way to safely extend both Object.prototype
and Array.prototype
without breaking for ... in ...
enumeration:
Object.defineProperty(Array.prototype, 'setAll', {
value: function(v) {
...
}
});
EDIT 2 In ES6 draft there's also now Array.prototype.fill
, usage cool.fill(42)
Android Studio 3.5.3
I use this for my libraries and projects and it covers most of the files that generate by android studio and other famous tools:
# Built application files
*.apk
*.ap_
*.aab
# Files for the ART/Dalvik VM
*.dex
# Generated files
bin/
gen/
out/
app/release/
# Gradle files
.gradle/
build/
# Local configuration file (sdk path, etc)
local.properties
# Log Files
*.log
# Android Studio Navigation editor temp files
.navigation/
# Android Studio captures folder
captures/
# IntelliJ
*.iml
.idea/workspace.xml
.idea/tasks.xml
.idea/gradle.xml
.idea/assetWizardSettings.xml
.idea/dictionaries
.idea/libraries
.idea/caches
# Keystore files
# Uncomment the following lines if you do not want to check your keystore files in.
#*.jks
#*.keystore
# External native build folder generated in Android Studio 2.2 and later
.externalNativeBuild
# Freeline
freeline.py
freeline/
freeline_project_description.json
# fastlane
fastlane/report.xml
fastlane/Preview.html
fastlane/screenshots
fastlane/test_output
fastlane/readme.md
#NDK
*.so
SELECT IDENT_CURRENT('Table')
You can use one of these examples:
SELECT * FROM Table
WHERE ID = (
SELECT IDENT_CURRENT('Table'))
SELECT * FROM Table
WHERE ID = (
SELECT MAX(ID) FROM Table)
SELECT TOP 1 * FROM Table
ORDER BY ID DESC
But the first one will be more efficient because no index scan is needed (if you have index on Id column).
The second one solution is equivalent to the third (both of them need to scan table to get max id).
Using a pipelined table function:
SQL> CREATE OR REPLACE TYPE test_type
2 AS
3 TABLE OF VARCHAR2(100)
4 /
Type created.
SQL> CREATE OR REPLACE FUNCTION comma_to_table(
2 p_list IN VARCHAR2)
3 RETURN test_type PIPELINED
4 AS
5 l_string LONG := p_list || ',';
6 l_comma_index PLS_INTEGER;
7 l_index PLS_INTEGER := 1;
8 BEGIN
9 LOOP
10 l_comma_index := INSTR(l_string, ',', l_index);
11 EXIT
12 WHEN l_comma_index = 0;
13 PIPE ROW ( TRIM(SUBSTR(l_string, l_index, l_comma_index - l_index)));
14 l_index := l_comma_index + 1;
15 END LOOP;
16 RETURN;
17 END comma_to_table;
18 /
Function created.
Let's see the output:
SQL> SELECT *
2 FROM TABLE(comma_to_table('12 3,456,,,,,abc,def'))
3 /
COLUMN_VALUE
------------------------------------------------------------------------------
12 3
456
abc
def
8 rows selected.
SQL>
Here's a simple example that waits for a tread to finish, within the same class. It also makes a call to another class in the same namespace. I included the "using" statements so it can execute as a Windows Forms form as long as you create button1.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
namespace ClassCrossCall
{
public partial class Form1 : Form
{
int number = 0; // This is an intentional problem, included
// for demonstration purposes
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
button1.Text = "Initialized";
}
private void button1_Click(object sender, EventArgs e)
{
button1.Text = "Clicked";
button1.Refresh();
Thread.Sleep(400);
List<Task> taskList = new List<Task>();
taskList.Add(Task.Factory.StartNew(() => update_thread(2000)));
taskList.Add(Task.Factory.StartNew(() => update_thread(4000)));
Task.WaitAll(taskList.ToArray());
worker.update_button(this, number);
}
public void update_thread(int ms)
{
// It's important to check the scope of all variables
number = ms; // This could be either 2000 or 4000. Race condition.
Thread.Sleep(ms);
}
}
class worker
{
public static void update_button(Form1 form, int number)
{
form.button1.Text = $"{number}";
}
}
}
Specifying CV_THRESH_OTSU
causes the threshold value to be ignored. From the documentation:
Also, the special value THRESH_OTSU may be combined with one of the above values. In this case, the function determines the optimal threshold value using the Otsu’s algorithm and uses it instead of the specified thresh . The function returns the computed threshold value. Currently, the Otsu’s method is implemented only for 8-bit images.
This code reads frames from the camera and performs the binary threshold at the value 20.
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
using namespace cv;
int main(int argc, const char * argv[]) {
VideoCapture cap;
if(argc > 1)
cap.open(string(argv[1]));
else
cap.open(0);
Mat frame;
namedWindow("video", 1);
for(;;) {
cap >> frame;
if(!frame.data)
break;
cvtColor(frame, frame, CV_BGR2GRAY);
threshold(frame, frame, 20, 255, THRESH_BINARY);
imshow("video", frame);
if(waitKey(30) >= 0)
break;
}
return 0;
}
Use the std::getline()
from <string>
.
istream & getline(istream & is,std::string& str)
So, for your case it would be:
std::getline(read,x);
both your conditions are the same:
if(s < f) { calc = f - s; n = s; }else if(f > s){ calc = s - f; n = f; }
so
if(s < f)
and
}else if(f > s){
are the same
change to
}else if(f < s){
Two ways come to mind:
Using a command-line tool like the popular ffmpeg, however you will almost always need an own server (or a very nice server administrator / hosting company) to get that
Using the "screenshoot" plugin for the LongTail Video player that allows the creation of manual screenshots that are then sent to a server-side script.
jQuery 3.3.1
if (typeof $("input[name='yourRadioName']:checked").val() === "undefined") {
alert('is not selected');
}else{
alert('is selected');
}
To install a specific package:
conda install <pkg>=<version>
eg:
conda install matplotlib=1.4.3
select format(convert(float,@your_column),'0.0#########')
Advantage: This solution is irrespective of the source datatype (float, scientific, varchar, date etc)
String
is limited to 10 digits, bigInt
gets rid of decimal values
As per Do a "git export" (like "svn export")?
You can use git checkout-index
for that, this is a low level command, if you want to export everything, you can use -a
,
git checkout-index -a -f --prefix=/destination/path/
To quote the man pages:
The final "/" [on the prefix] is important. The exported name is literally just prefixed with the specified string.
If you want to export a certain directory, there are some tricks involved. The command only takes files, not directories. To apply it to directories, use the 'find' command and pipe the output to git.
find dirname -print0 | git checkout-index --prefix=/path-to/dest/ -f -z --stdin
Also from the man pages:
Intuitiveness is not the goal here. Repeatability is.
Another fancy way to do it in Laravel 6.x (Unsure but must work for 5.x aswell) :
DB::table('your_table')->get()->last();
You can access fields too :
DB::table('your_table')->get()->last()->id;
Here is the code for the short version of if-then-else statement:
( [ $a -eq 1 ] || [ $b -eq 2 ] ) && echo "ok" || echo "nok"
Pay attention to the following:
||
and &&
operands inside if condition (i.e. between round parentheses) are logical operands (or/and)
||
and &&
operands outside if condition mean then/else
Practically the statement says:
if (a=1 or b=2) then "ok" else "nok"
Pass in the straight XML instead of a dictionary.
import pandas as pd
csv_file = pd.read_csv("file.csv")
column_val_list = csv_file.column_name._ndarray_values
Unfortunately, setTimeout()
is the only reliable way (not the only way, but the only reliable way) to pause the execution of the script without blocking the UI.
It's not that hard to use actually, instead of writing this:
var x = 1;
// Place mysterious code that blocks the thread for 100 ms.
x = x * 3 + 2;
var y = x / 2;
you use setTimeout()
to rewrite it this way:
var x = 1;
var y = null; // To keep under proper scope
setTimeout(function() {
x = x * 3 + 2;
y = x / 2;
}, 100);
I understand that using setTimeout()
involves more thought than a desirable sleep()
function, but unfortunately the later doesn't exist. Many workarounds are there to try to implement such functions. Some using busy loops:
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
Unfortunately, those are workarounds and are likely to cause other problems (such as freezing browsers). It is recommended to simply stick with the recommended way, which is setTimeout()
).
For what it's worth adding to the discussion... what I did that ended up helping me... Since the pipeline is run within a workspace within a docker image that is cleaned up each time it runs. I grabbed the credentials needed to perform necessary operations on the repo within my pipeline and stored them in a .netrc file. this allowed me to authorize the git repo operations successfully.
withCredentials([usernamePassword(credentialsId: '<credentials-id>', passwordVariable: 'GIT_PASSWORD', usernameVariable: 'GIT_USERNAME')]) {
sh '''
printf "machine github.com\nlogin $GIT_USERNAME\n password $GIT_PASSWORD" >> ~/.netrc
// continue script as necessary working with git repo...
'''
}
In Java side, the date is usually represented by the (poorly designed, but that aside) java.util.Date
. It is basically backed by the Epoch time in flavor of a long
, also known as a timestamp. It contains information about both the date and time parts. In Java, the precision is in milliseconds.
In SQL side, there are several standard date and time types, DATE
, TIME
and TIMESTAMP
(at some DB's also called DATETIME
), which are represented in JDBC as java.sql.Date
, java.sql.Time
and java.sql.Timestamp
, all subclasses of java.util.Date
. The precision is DB dependent, often in milliseconds like Java, but it can also be in seconds.
In contrary to java.util.Date
, the java.sql.Date
contains only information about the date part (year, month, day). The Time
contains only information about the time part (hours, minutes, seconds) and the Timestamp
contains information about the both parts, like as java.util.Date
does.
The normal practice to store a timestamp in the DB (thus, java.util.Date
in Java side and java.sql.Timestamp
in JDBC side) is to use PreparedStatement#setTimestamp()
.
java.util.Date date = getItSomehow();
Timestamp timestamp = new Timestamp(date.getTime());
preparedStatement = connection.prepareStatement("SELECT * FROM tbl WHERE ts > ?");
preparedStatement.setTimestamp(1, timestamp);
The normal practice to obtain a timestamp from the DB is to use ResultSet#getTimestamp()
.
Timestamp timestamp = resultSet.getTimestamp("ts");
java.util.Date date = timestamp; // You can just upcast.
You need to add:
#include <cstdlib>
in order for the compiler to see the prototype for system()
.
Are you sure you want to use __getattribute__
? What are you actually trying to achieve?
The easiest way to do what you ask is:
class D(object):
def __init__(self):
self.test = 20
self.test2 = 21
test = 0
or:
class D(object):
def __init__(self):
self.test = 20
self.test2 = 21
@property
def test(self):
return 0
Edit:
Note that an instance of D
would have different values of test
in each case. In the first case d.test
would be 20, in the second it would be 0. I'll leave it to you to work out why.
Edit2:
Greg pointed out that example 2 will fail because the property is read only and the __init__
method tried to set it to 20. A more complete example for that would be:
class D(object):
def __init__(self):
self.test = 20
self.test2 = 21
_test = 0
def get_test(self):
return self._test
def set_test(self, value):
self._test = value
test = property(get_test, set_test)
Obviously, as a class this is almost entirely useless, but it gives you an idea to move on from.
You can use function closures as data in larger expressions as well, as in this method of determining browser support for some of the html5 objects.
navigator.html5={
canvas: (function(){
var dc= document.createElement('canvas');
if(!dc.getContext) return 0;
var c= dc.getContext('2d');
return typeof c.fillText== 'function'? 2: 1;
})(),
localStorage: (function(){
return !!window.localStorage;
})(),
webworkers: (function(){
return !!window.Worker;
})(),
offline: (function(){
return !!window.applicationCache;
})()
}
Open the CSV file with a decent text editor like Notepad++ and add the following text in the first line:
sep=,
Now open it with excel again.
This will set the separator as a comma, or you can change it to whatever you need.
On windows 10 (client) you can also script this using
Enable-WindowsOptionalFeature -Online -NoRestart -FeatureName WCF-HTTP-Activation45 -All
Note that this is a different command from the server skus
"dev" is not a string
it is a const char *
like var1
. Thus you are indeed comparing the memory adresses. Being that var1
is a char pointer, *var1
is a single char (the first character of the pointed to character sequence to be precise). You can't compare a char against a char pointer, which is why that did not work.
Being that this is tagged as c++, it would be sensible to use std::string
instead of char pointers, which would make == work as expected. (You would just need to do const std::string var1
instead of const char *var1
.
var date = new Date("2012-01-18T16:03");
console.log( (date.getMinutes()<10?'0':'') + date.getMinutes() );
you can try using this
System.Web.HttpContext.Current.Server.MapPath(path);
or use HostingEnvironment.MapPath
System.Web.Hosting.HostingEnvironment.MapPath(path);
/*You might be looking something like this?
grep -vn "gloom" `grep -l "loom" ~/projects/**/trunk/src/**/*.@(h|cpp)`
The BACKQUOTES are used like brackets for commands, so in this case with -l
enabled,
the code in the BACKQUOTES will return you the file names, then with -vn to do what you wanted: have filenames, linenumbers, and also the actual lines.
UPDATE Or with xargs
grep -l "loom" ~/projects/**/trunk/src/**/*.@(h|cpp) | xargs grep -vn "gloom"
Hope that helps.*/
Please ignore what I've written above, it's rubbish.
grep -n "loom" `grep -l "loom" tt4.txt` | grep -v "gloom"
#this part gets the filenames with "loom"
#this part gets the lines with "loom"
#this part gets the linenumber,
#filename and actual line
All you have to do is,
make sure your parent DIV has position:relative
and the element you want center, set it a height and width. use the following CSS
.layer {
width: 600px; height: 500px;
display: block;
position:absolute;
top:0;
left: 0;
right:0;
bottom: 0;
margin:auto;
}
http://jsbin.com/aXEZUgEJ/1/
Check out jasypt, which is a library offering basic encryption capabilities with minimum effort.
Even better, use DEFAULT instead of NULL. You want to store the default value, not a NULL that might trigger a default value.
But you'd better name all columns, with a piece of SQL you can create all the INSERT, UPDATE and DELETE's you need. Just check the information_schema and construct the queries you need. There is no need to do it all by hand, SQL can help you out.
You need nunique
:
df = df.groupby('domain')['ID'].nunique()
print (df)
domain
'facebook.com' 1
'google.com' 1
'twitter.com' 2
'vk.com' 3
Name: ID, dtype: int64
If you need to strip
'
characters:
df = df.ID.groupby([df.domain.str.strip("'")]).nunique()
print (df)
domain
facebook.com 1
google.com 1
twitter.com 2
vk.com 3
Name: ID, dtype: int64
Or as Jon Clements commented:
df.groupby(df.domain.str.strip("'"))['ID'].nunique()
You can retain the column name like this:
df = df.groupby(by='domain', as_index=False).agg({'ID': pd.Series.nunique})
print(df)
domain ID
0 fb 1
1 ggl 1
2 twitter 2
3 vk 3
The difference is that nunique()
returns a Series and agg()
returns a DataFrame.
public static bool HasProperty(dynamic obj, string name)
{
Type objType = obj.GetType();
if (objType == typeof(ExpandoObject))
{
return ((IDictionary<string, object>)obj).ContainsKey(name);
}
return objType.GetProperty(name) != null;
}
If you want decompress without software better use this code. Other code with pdf files sends error on manually decompress
byte[] buffer = new byte[1024];
try
{
FileOutputStream fos = new FileOutputStream("123.zip");
ZipOutputStream zos = new ZipOutputStream(fos);
ZipEntry ze= new ZipEntry("file.pdf");
zos.putNextEntry(ze);
FileInputStream in = new FileInputStream("file.pdf");
int len;
while ((len = in.read(buffer)) > 0)
{
zos.write(buffer, 0, len);
}
in.close();
zos.closeEntry();
zos.close();
}
catch(IOException ex)
{
ex.printStackTrace();
}
Here is a code to draw a fill elipse, you can use the same method but replacing de xcenter and y center with radius
void drawFilledelipse(GLfloat x, GLfloat y, GLfloat xcenter,GLfloat ycenter) {
int i;
int triangleAmount = 20; //# of triangles used to draw circle
//GLfloat radius = 0.8f; //radius
GLfloat twicePi = 2.0f * PI;
glBegin(GL_TRIANGLE_FAN);
glVertex2f(x, y); // center of circle
for (i = 0; i <= triangleAmount; i++) {
glVertex2f(
x + ((xcenter+1)* cos(i * twicePi / triangleAmount)),
y + ((ycenter-1)* sin(i * twicePi / triangleAmount))
);
}
glEnd();
}
When you access resultFrame through document.all it only pulls it as an HTML element, not a window frame. You get the same issue if you have a frame fire an event using a "this" self-reference.
Replace:
document.all.resultFrame.Reset();
With:
window.frames.resultFrame.Reset();
Or:
document.all.resultFrame.contentWindow.Reset();
For me when that usually starts happening, I have to remote desktop into the service and at the minimum restart IIS. It usually starts popping up right after I deploy code. On a few rare occasions I have had to restart the SQL services and IIS. I wrote a batch script to take a param (1 or 2) and have it setup to either do a restart of IIS ( i.e. 1), or go full nuclear (i.e. 2).
I've just experienced this issue. For me it appeared when some erroneous code was trying to redirect to HTTPS on port 80.
e.g.
by removing the port 80 from the url, the redirect works.
HTTPS by default runs over port 443.
What I did, is having a TextView
and a CheckBox
inside a (Relative)Layout
. The TextView
displays the text that I want the user to see, and the CheckBox
doesn't have any text. That way, I can set the position / padding of the CheckBox
wherever I want.
If you have setup.py
in your project and you use find_packages()
within it, it is necessary to have an __init__.py
file in every directory for packages to be automatically found.
Packages are only recognized if they include an
__init__.py
file
UPD: If you want to use implicit namespace packages without __init__.py
you just have to use find_namespace_packages()
instead
Use:
function getdatabetween($string, $start, $end){
$sp = strpos($string, $start)+strlen($start);
$ep = strpos($string, $end)-strlen($start);
$data = trim(substr($string, $sp, $ep));
return trim($data);
}
$dt = "Find string between two strings in PHP";
echo getdatabetween($dt, 'Find', 'in PHP');
I have faced issue like my main page index.jsp contains the below line but eventhough rendering was not proper in IE. Found the issue and I have added the code in all the files which I included in index.jsp. Hurray! it worked.
So You need to add below code in all the files which you include into the page otherwise it wont work.
<!doctype html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
</head>
since basestring
isn't defined in Python3, this little trick might help to make the code compatible:
try: # check whether python knows about 'basestring'
basestring
except NameError: # no, it doesn't (it's Python3); use 'str' instead
basestring=str
after that you can run the following test on both Python2 and Python3
isinstance(myvar, basestring)
It checks if the modulo of the division. For example, in the case you are iterating over all numbers from 2 to n and checking if n is divisible by any of the numbers in between. Simply put, you are checking if a given number n is prime. (Hint: You could check up to n/2).
There are two branches to this question (Rolling back a commit does not mean I want to lose all my local changes):
1. To revert the latest commit and discard changes in the committed file do:
git reset --hard HEAD~1
2. To revert the latest commit but retain the local changes (on disk) do:
git reset --soft HEAD~1
This (the later command) will take you to the state you would have been if you did git add
.
If you want to unstage the files after that, do
git reset
Now you can make more changes before adding and then committing again.
First of all, you can't import fonts to CSS that way.
You can add this code in HTML head:
<link href='http://fonts.googleapis.com/css?family=Oswald:400,300,700' rel='stylesheet' type='text/css'>
or to import it in CSS file like this:
@import url("http://fonts.googleapis.com/css?family=Oswald:400,300,700");
Then, in your css, you can edit the body's font-family:
body {
font-family: 'Oswald', sans-serif !important;
}
I'm not much of a php programmer, but I can say that in C# you cannot modify an array while iterating through it. You may want to try using your foreach loop to identify the index of the element, or elements to remove, then delete the elements after the loop.
Here's what I used to get information on an undocumented (3rd-party) intent:
Bundle bundle = intent.getExtras();
if (bundle != null) {
for (String key : bundle.keySet()) {
Log.e(TAG, key + " : " + (bundle.get(key) != null ? bundle.get(key) : "NULL"));
}
}
Make sure to check if bundle
is null before the loop.
Use include_once();
- with this, your codes will be included only one time.
The -maxdepth
option should be before the -name
option, like below.,
find . -maxdepth 1 -name "string" -print
Kind of an anonymous lookup table rather than a long switch statement:
return (const char *[]) {
"bananas & monkeys",
"Round and orange",
"APPLE",
}[enumVal];
You can simply use shell commands. If you want to suppress echoing the output, use the "@" sign. For example:
clean:
@if [ "test" = "test" ]; then\
echo "Hello world";\
fi
Note that the closing ";" and "\" are necessary.
Nowadays you can use
try {
String s = CompletableFuture.supplyAsync(() -> br.readLine())
.get(1, TimeUnit.SECONDS);
} catch (TimeoutException e) {
System.out.println("Time out has occurred");
} catch (InterruptedException | ExecutionException e) {
// Handle
}
The query below works only when searching for dependencies on a table and not those on a column:
EXEC sp_depends @objname = N'TableName';
However, the following query is the best option if you want to search for all sorts of dependencies, it does not miss any thing. It actually gives more information than required.
select distinct
so.name
--, text
from
sysobjects so,
syscomments sc
where
so.id = sc.id
and lower(text) like '%organizationtypeid%'
order by so.name
Another succinct way of doing this is pandas.DataFrame.clip.
For example:
import pandas as pd
In [20]: df = pd.DataFrame({'a': [-1, 100, -2]})
In [21]: df
Out[21]:
a
0 -1
1 100
2 -2
In [22]: df.clip(lower=0)
Out[22]:
a
0 0
1 100
2 0
There's also df.clip_lower(0)
.
It seem like your Resort
method doesn't declare a compareTo
method. This method typically belongs to the Comparable
interface. Make sure your class implements it.
Additionally, the compareTo
method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String
argument, but rather a Resort
.
Alternatively, you can compare the names of the resorts. For example
if (resortList[mid].getResortName().compareTo(resortName)>0)
Starting in SQL Server 2017 the STRING_AGG
function is available which simplifies the logic considerably:
select FieldA, string_agg(FieldB, '') as data
from yourtable
group by FieldA
In SQL Server you can use FOR XML PATH
to get the result:
select distinct t1.FieldA,
STUFF((SELECT distinct '' + t2.FieldB
from yourtable t2
where t1.FieldA = t2.FieldA
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,0,'') data
from yourtable t1;
exec does not execute a command in your shell
try
Process p = Runtime.getRuntime().exec(new String[]{"csh","-c","cat /home/narek/pk.txt"});
instead.
EDIT:: I don't have csh on my system so I used bash instead. The following worked for me
Process p = Runtime.getRuntime().exec(new String[]{"bash","-c","ls /home/XXX"});
A better one using explode()
function is as follows...
Don't forget to replace your URL variable in the hyperlink href
.
<?php
if($url != ''){
$b = '';
$links = explode('/',rtrim($url,'/'));
foreach($links as $l){
$b .= $l;
if($url == $b){
echo $l;
}else{
echo "<a href='URL?url=".$b."'>".$l."/</a>";
}
$b .= '/';
}
}
?>
Unfortunately, all the good answers here didn't work for me. So after installing composer on windows 10, I just had to set system variable
in environment variables
and it worked.
if ([imageForCheckMark.image isEqual:[UIImage imageNamed:@"crossCheckMark.png"]]||[imageForCheckMark.image isEqual:[UIImage imageNamed:@"checkMark.png"]])
{
}
I read some answers here a while back and created some code I use for div's that function as popup bubbles.
$('#openPopupBubble').click(function(){
$('#popupBubble').toggle();
if($('#popupBubble').css('display') === 'block'){
$(document).bind('mousedown touchstart', function(e){
if($('#openPopupBubble').is(e.target) || $('#openPopupBubble').find('*').is(e.target)){
$(this).unbind(e);
}
else if(!$('#popupBubble').find('*').is(e.target)){
$('#popupBubble').hide();
$(this).unbind(e);
}
});
}
});
You can also make this more abstract using classes and select the correct popup bubble based on the button that triggered the click event.
$('body').on('click', '.openPopupBubble', function(){
$(this).next('.popupBubble').toggle();
if($(this).next('.popupBubble').css('display') === 'block'){
$(document).bind('mousedown touchstart', function(e){
if($(this).is(e.target) || $(this).find('*').is(e.target)){
$(this).unbind(e);
}
else if(!$(this).next('.popupBubble').find('*').is(e.target)){
$(this).next('.popupBubble').hide();
$(this).unbind(e);
}
});
}
});
If you really want an iterator-free solution, you can use numpy and its array round function.
import numpy as np
myList = list(np.around(np.array(myList),2))
If using reactive forms, you can also disable the entire form or any sub-set of controls in a FormGroup with myFormGroup.disable()
.
GROUP BY DATEADD(day, DATEDIFF(day, 0, MyDateTimeColumn), 0)
Or in SQL Server 2008 onwards you could simply cast to Date
as @Oded suggested:
GROUP BY CAST(orderDate AS DATE)
It may be easier. Try to think like this:
:
// 'www.dev.yyy.com'
// 'xxx.foo.pl'
var url = "xxx.foo.pl";
switch (url.match(/\..*.\./)[0]){
case ".dev.yyy." :
console.log("xxx.dev.yyy.com");break;
case ".some.":
console.log("xxx.foo.pl");break;
} //end switch
A procedure can't return a table as such. However you can select from a table in a procedure and direct it into a table (or table variable) like this:
create procedure p_x
as
begin
declare @t table(col1 varchar(10), col2 float, col3 float, col4 float)
insert @t values('a', 1,1,1)
insert @t values('b', 2,2,2)
select * from @t
end
go
declare @t table(col1 varchar(10), col2 float, col3 float, col4 float)
insert @t
exec p_x
select * from @t
$('select>option:eq(3)').attr('selected', 'selected');
One caveat here is if you have javascript watching for select/option's change event you need to add .trigger('change')
so the code become.
$('select>option:eq(3)').attr('selected', 'selected').trigger('change');
because only calling .attr('selected', 'selected')
does not trigger the event
I thought I would add this because the a
in the example you gave is sorted:
import numpy as np
a = [1, 3, 5, 6, 9, 10, 14, 15, 56]
start = np.searchsorted(a, 6, 'left')
end = np.searchsorted(a, 10, 'right')
rng = np.arange(start, end)
rng
# array([3, 4, 5])
I ran into a similar problem. It works on one server and does not on another server with same Nginx configuration. Found the the solution which is answered by Igor here http://forum.nginx.org/read.php?2,1612,1627#msg-1627
Yes. Or you may combine SSL/non-SSL servers in one server:
server {
listen 80;
listen 443 default ssl;
# ssl on - remember to comment this out
}
Responded to a similar question with a potentially simple solution to this if anyone is still after an answer, the catch is it involves the use of redux-sagas:
https://stackoverflow.com/a/38701184/978306
Or just skip straight to the article I wrote on the topic:
WITH UPD AS (UPDATE TEST_TABLE SET SOME_DATA = 'Joe' WHERE ID = 2
RETURNING ID),
INS AS (SELECT '2', 'Joe' WHERE NOT EXISTS (SELECT * FROM UPD))
INSERT INTO TEST_TABLE(ID, SOME_DATA) SELECT * FROM INS
Tested on Postgresql 9.3
I would like to correct the @Neal answer which was pretty good for integers, but the number 1 would return a length of 0 in the previous case.
function Longueur(numberlen)
{
var length = 0, i; //define `i` with `var` as not to clutter the global scope
numberlen = parseInt(numberlen);
for(i = numberlen; i >= 1; i)
{
++length;
i = Math.floor(i/10);
}
return length;
}
Use Where-Object
, like:
Get-ChildItem 'PATH' -recurse -include @("*.tif*","*.jp2","*.pdf") |
Where-Object { $_.CreationTime -gt "03/01/2013" -and $_.CreationTime -lt "03/31/2013" }
Select-Object FullName, CreationTime, @{Name="Mbytes";Expression={$_.Length/1Kb}}, @{Name="Age";Expression={(((Get-Date) - $_.CreationTime).Days)}} |
Export-Csv 'PATH\scans.csv'
Mine was not having @Entity
on the many side entity
@Entity // this was commented
@Table(name = "some_table")
public class ChildEntity {
@JoinColumn(name = "parent", referencedColumnName = "id")
@ManyToOne
private ParentEntity parentEntity;
}
I discover very simple way to redirect Login Page When session end in MVC. I have already tested it and this works without problems.
In short, I catch session end in _Layout 1 minute before and make redirection.
I try to explain everything step by step.
If we want to session end 30 minute after and redirect to loginPage see this steps:
Change the web config like this (set 31 minute):
<system.web>
<sessionState timeout="31"></sessionState>
</system.web>
Add this JavaScript in _Layout
(when session end 1 minute before this code makes redirect, it makes count time after user last action, not first visit on site)
<script>
//session end
var sessionTimeoutWarning = @Session.Timeout- 1;
var sTimeout = parseInt(sessionTimeoutWarning) * 60 * 1000;
setTimeout('SessionEnd()', sTimeout);
function SessionEnd() {
window.location = "/Account/LogOff";
}
</script>
Here is my LogOff Action, which makes only LogOff and redirect LoginIn Page
public ActionResult LogOff()
{
Session["User"] = null; //it's my session variable
Session.Clear();
Session.Abandon();
FormsAuthentication.SignOut(); //you write this when you use FormsAuthentication
return RedirectToAction("Login", "Account");
}
I hope this is a very useful code for you.
I believe you can loop through the properties of the object using for/in, so you could do something like this:
function getKeys(h) {
Array keys = new Array();
for (var key in h)
keys.push(key);
return keys;
}
Run this command:
rvm get stable --auto-dotfiles
and make sure to read all the output. RVM
will tell you if something is wrong, which in your case might be because GEM_HOME
is set to something different then PATH
.
Another way using jQuery:
var exists = false;
$('#yourSelect option').each(function(){
if (this.value == yourValue) {
exists = true;
}
});
Try switching the order of your code. You must create the worksheet first in order to name it.
Private Sub CreateSheet()
Dim ws As Worksheet
Set ws = Sheets.Add(After:=Sheets(Sheets.Count))
ws.Name = "Tempo"
End Sub
thanks,
I experienced that when downgrading (i.e. uninstalling and reinstalling) from VS 2015 Ultimate to VS 2015 Professional, the IDE was very sluggish and constantly froze.
Doing a new clone of the repository, or - as one of my collegues tried - cleaning out all files not in source control (in the case of Git git clean -xfd
), helped me get rid of the this problem. The IDE is now running smoothly again.
The assumption is that Ultimate leaves some files behind that cause this behaviour in Professional, but I have not been able to track down which.
Split Method
data = input_string
df = pd.DataFrame([x.split(';') for x in data.split('\n')])
print(df)
Given a choice between the solution advocated by IServiceOriented.com and the solution advocated by David Barret's blog, I prefer the simplicity offered by overriding the client's Dispose() method. This allows me to continue to use the using() statement as one would expect with a disposable object. However, as @Brian pointed out, this solution contains a race condition in that the State might not be faulted when it is checked but could be by the time Close() is called, in which case the CommunicationException still occurs.
So, to get around this, I've employed a solution that mixes the best of both worlds.
void IDisposable.Dispose()
{
bool success = false;
try
{
if (State != CommunicationState.Faulted)
{
Close();
success = true;
}
}
finally
{
if (!success)
Abort();
}
}
The guy above who put this: "I experienced this problem too, but none of the answers helped. What I did, I removed the last backslash from the JAVA_HOME variable and it started working. Also, remember not to include the bin folder in the path." This was in fact the correct answer.
For this SDK to install this is what I did. I am running the latest Microsoft OS Windows 8.
User Variables:
Path
C:\Program Files\Java\jdk1.7.0_07\bin
Environment Variables
Create these two:
CLASSPATH
%HOME_JAVA%\jre\lib
HOME_JAVA
C:\Program Files\Java\jdk1.7.0_09
This one already exists so just edit:
Path At this end of
WindowsPowerShell\v1.0\
simply add ";C:\Program
Files\Java\jdk1.7.0_09"
This is what I did and it worked for me. =)
If you are experiencing the OP's problem where your cookies have been set using JavaScript - for example:
document.cookie = "my_cookie_name=my_cookie_value; expires=Thu, 11 Jun 2070 11:11:11 UTC; path=/";
you could instead use:
document.cookie = "my_cookie_name=my_cookie_value; expires=Thu, 11 Jun 2070 11:11:11 UTC; path=/; SameSite=None; Secure";
It worked for me. More info here.
You can use System.Web.Script.Serialization.JavaScriptSerializer
:
Dictionary<string, object> dictss = new Dictionary<string, object>(){
{"User", "Mr.Joshua"},
{"Pass", "4324"},
};
string jsonString = (new JavaScriptSerializer()).Serialize((object)dictss);
my solution:
MOVE:
jQuery("#NodesToMove").detach().appendTo('#DestinationContainerNode')
COPY:
jQuery("#NodesToMove").appendTo('#DestinationContainerNode')
Note the usage of .detach(). When copying, be careful that you are not duplicating IDs.
Just check JSON option from the drop down next to binary; when you click raw. This should do
The Android plugin 0.8.x doesn't support Gradle 1.11, you need to use 1.10.
You can read the proper error message in the "Gradle Console" tab.
EDIT
You need to change gradle/wrapper/gradle-wrapper.properties
file in this way:
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=http\://services.gradle.org/distributions/gradle-1.10-all.zip
The problem is that if you include fun.cpp in two places in your program, you will end up defining it twice, which isn't valid.
You don't want to include cpp
files. You want to include header files.
The header file should just have the class definition. The corresponding cpp
file, which you will compile separately, will have the function definition.
fun.hpp:
#include <iostream>
class classA {
friend void funct();
public:
classA(int a=1,int b=2):propa(a),propb(b){std::cout<<"constructor\n";}
private:
int propa;
int propb;
void outfun(){
std::cout<<"propa="<<propa<<endl<<"propb="<<propb<< std::endl;
}
};
fun.cpp:
#include "fun.hpp"
using namespace std;
void funct(){
cout<<"enter funct"<<endl;
classA tmp(1,2);
tmp.outfun();
cout<<"exit funct"<<endl;
}
mainfile.cpp:
#include <iostream>
#include "fun.hpp"
using namespace std;
int main(int nargin,char* varargin[]) {
cout<<"call funct"<<endl;
funct();
cout<<"exit main"<<endl;
return 0;
}
Note that it is generally recommended to avoid using namespace std
in header files.
You just need to make the siprimo and volteado methods static.
private static bool siprimo(long a)
and
private static long volteado(long a)
May be you could use jquery serialize() method so that everything will be at one go.
var data=$('#myForm').serialize();
//this way you could get the hidden value as well in the server side.
I found a solution that works excellently and can scroll the ListView
without problems:
ListView lv = (ListView)findViewById(R.id.myListView); // your listview inside scrollview
lv.setOnTouchListener(new ListView.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
// Disallow ScrollView to intercept touch events.
v.getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_UP:
// Allow ScrollView to intercept touch events.
v.getParent().requestDisallowInterceptTouchEvent(false);
break;
}
// Handle ListView touch events.
v.onTouchEvent(event);
return true;
}
});
What this does is disable the TouchEvent
s on the ScrollView
and make the ListView
intercept them. It is simple and works all the time.
I had the same issue with angular RC.6 for some reason it doesn't allow passing component to other component using directives as component decorator to the parent component
But it if you import the child component via app module and add it in the declaration array the error goes away. There are no much explanation to why this is an issue with angular rc.6
If you're using SSMS (or old school Enterprise Manager) to edit the table directly, press CTRL+0 to add a null.
As other answers pointed out in a more complicated way already, you did already create a list of lists! It's just the odd output of R that confuses (everybody?). Try this:
> str(list_all)
List of 2
$ :List of 2
..$ : num 1
..$ : num 2
$ :List of 2
..$ : chr "a"
..$ : chr "b"
And the most simple construction would be this:
> str(list(list(1, 2), list("a", "b")))
List of 2
$ :List of 2
..$ : num 1
..$ : num 2
$ :List of 2
..$ : chr "a"
..$ : chr "b"
If "website" can be empty than new_field
should also be set to be empty.
Now if you want to add logic on save where if new_field
is empty to grab the value from "website" all you need to do is override the save function for your Model
like this:
class UserProfile(models.Model):
user = models.OneToOneField(User)
website = models.URLField(blank=True, default='DEFAULT VALUE')
new_field = models.CharField(max_length=140, blank=True, default='DEFAULT VALUE')
def save(self, *args, **kwargs):
if not self.new_field:
# Setting the value of new_field with website's value
self.new_field = self.website
# Saving the object with the default save() function
super(UserProfile, self).save(*args, **kwargs)
There will be so many instances where the service will go in to "stop pending".The Operating system will complain that it was "Not able to stop the service xyz." In case you want to make absolutely sure the service is restarted you should kill the process instead. You can do that by doing the following in a bat file
taskkill /F /IM processname.exe
timeout 20
sc start servicename
To find out which process is associated with your service, go to task manager--> Services tab-->Right Click on your Service--> Go to process.
Note that this should be a work around until you figure out why your service had to be restarted in the first place. You should look for memory leaks, infinite loops and other such conditions for your service to have become unresponsive.
For more general boolean functions that you would like to use as a filter and that depend on more than one column, you can use:
df = df[df[['col_1','col_2']].apply(lambda x: f(*x), axis=1)]
where f is a function that is applied to every pair of elements (x1, x2) from col_1 and col_2 and returns True or False depending on any condition you want on (x1, x2).
> grepl("^[^_]+_1",s)
[1] FALSE
> grepl("^[^_]+_2",s)
[1] TRUE
basically, look for everything at the beginning except _
, and then the _2
.
+1 to @Ananda_Mahto for suggesting grepl
instead of grep
.
As @wirey said appendTo
should work, if not then you can try this:
$("#tblEntAttributes tbody").append(newRowContent);
The Heap is divided into young and old generations as follows :
Young Generation : It is place where lived for short period and divided into two spaces:
Old Generation : This pool basically contains tenured and virtual (reserved) space and will be holding those objects which survived after garbage collection from Young Generation.
Permanent Generation : This memory pool as name also says contain permanent class metadata and descriptors information so PermGen space always reserved for classes and those that is tied to the classes for example static members.
Java8 Update: PermGen is replaced with Metaspace which is very similar.
Main difference is that Metaspace re-sizes dynamically i.e., It can expand at runtime.
Java Metaspace space: unbounded (default)
Code Cache (Virtual or reserved) : If you are using HotSpot Java VM this includes code cache area that containing memory which will be used for compilation and storage of native code.
Just delete module-info.java at your Project Explorer tab.
print self.id.__str__()
would work for you, although not that useful for you.
Your __str__
method will be more useful when you say want to print out a grid or struct representation as your program develops.
print self._grid.__str__()
def __str__(self):
"""
Return a string representation of the grid for debugging.
"""
grid_str = ""
for row in range(self._rows):
grid_str += str( self._grid[row] )
grid_str += '\n'
return grid_str
The most simple way that should work in any database is to do following:
SELECT * FROM `employee` ORDER BY `salary` DESC LIMIT 1 OFFSET 2;
Which orders employees by salary and then tells db to return a single result (1 in LIMIT) counting from third row in result set (2 in OFFSET). It may be OFFSET 3
if your DB counts result rows from 1 and not from 0.
This example should work in MySQL and PostgreSQL.
You can use the ROWLOCK hint, but AFAIK SQL may decide to escalate it if it runs low on resources
ROWLOCK Specifies that row locks are taken when page or table locks are ordinarily taken. When specified in transactions operating at the SNAPSHOT isolation level, row locks are not taken unless ROWLOCK is combined with other table hints that require locks, such as UPDLOCK and HOLDLOCK.
and
Lock hints ROWLOCK, UPDLOCK, AND XLOCK that acquire row-level locks may place locks on index keys rather than the actual data rows. For example, if a table has a nonclustered index, and a SELECT statement using a lock hint is handled by a covering index, a lock is acquired on the index key in the covering index rather than on the data row in the base table.
And finally this gives a pretty in-depth explanation about lock escalation in SQL Server 2005 which was changed in SQL Server 2008.
There is also, the very in depth: Locking in The Database Engine (in books online)
So, in general
UPDATE
Employees WITH (ROWLOCK)
SET Name='Mr Bean'
WHERE Age>93
Should be ok, but depending on the indexes and load on the server it may end up escalating to a page lock.
Here's what I don't like about git:
First of all, I think the distributed idea flies in the face of reality. Everybody who's actually using git is doing so in a centralised way, even Linus Torvalds. If the kernel was managed in a distributed way, that would mean I couldn't actually download the "official" kernel sources - there wouldn't be one - I'd have to decide whether I want Linus' version, or Joe's version, or Bill's version. That would obviously be ridiculous, and that's why there is an official definition which Linus controls using a centralised workflow.
If you accept that you want a centralised definition of your stuff, then it becomes clear that the server and client roles are completely different, so the dogma that the client and server softwares should be the same becomes purely limiting. The dogma that the client and server data should be the same becomes patently ridiculous, especially in a codebase that's got fifteen years of history that nobody cares about but everybody would have to clone.
What we actually want to do with all that old stuff is bung it in a cupboard and forget that it's there, just like any normal VCS does. The fact that git hauls it all back and forth over the network every day is very dangerous, because it nags you to prune it. That pruning involves a lot of tedious decisions and it can go wrong. So people will probably keep a whole series of snapshot repos from various points in history, but wasn't that what source control was for in the first place? This problem didn't exist until somebody invented the distributed model.
Git actively encourages people to rewrite history, and the above is probably one reason for that. Every normal VCS makes rewriting history impossible for all but the admins, and makes sure the admins have no reason to consider it. Correct me if I'm wrong, but as far as I know, git provides no way to grant normal users write access but ban them from rewriting history. That means any developer with a grudge (or who was still struggling with the learning curve) could trash the whole codebase. How do we tighten that one? Well, either you make regular backups of the entire history, i.e. you keep history squared, or you ban write access to all except some poor sod who would receive all the diffs by email and merge them by hand.
Let's take an example of a well-funded, large project and see how git is working for them: Android. I once decided to have a play with the android system itself. I found out that I was supposed to use a bunch of scripts called repo to get at their git. Some of repo runs on the client and some on the server, but both, by their very existence, are illustrating the fact that git is incomplete in either capacity. What happened is that I was unable to pull the sources for about a week and then gave up altogether. I would have had to pull a truly vast amount of data from several different repositories, but the server was completely overloaded with people like me. Repo was timing out and was unable to resume from where it had timed out. If git is so distributable, you'd have thought that they'd have done some kind of peer-to-peer thing to relieve the load on that one server. Git is distributable, but it's not a server. Git+repo is a server, but repo is not distributable cos it's just an ad-hoc collection of hacks.
A similar illustration of git's inadequacy is gitolite (and its ancestor which apparently didn't work out so well.) Gitolite describes its job as easing the deployment of a git server. Again, the very existence of this thing proves that git is not a server, any more than it is a client. What's more, it never will be, because if it grew into either it would be betraying it's founding principles.
Even if you did believe in the distributed thing, git would still be a mess. What, for instance, is a branch? They say that you implicitly make a branch every time you clone a repository, but that can't be the same thing as a branch in a single repository. So that's at least two different things being referred to as branches. But then, you can also rewind in a repo and just start editing. Is that like the second type of branch, or something different again? Maybe it depends what type of repo you've got - oh yes - apparently the repo is not a very clear concept either. There are normal ones and bare ones. You can't push to a normal one because the bare part might get out of sync with its source tree. But you can't cvsimport to a bare one cos they didn't think of that. So you have to cvsimport to a normal one, clone that to a bare one which developers hit, and cvsexport that to a cvs working copy which still has to be checked into cvs. Who can be bothered? Where did all these complications come from? From the distributed idea itself. I ditched gitolite in the end because it was imposing even more of these restrictions on me.
Git says that branching should be light, but many companies already have a serious rogue branch problem so I'd have thought that branching should be a momentous decision with strict policing. This is where perforce really shines...
In perforce you rarely need branches because you can juggle changesets in a very agile way. For instance, the usual workflow is that you sync to the last known good version on mainline, then write your feature. Whenever you attempt to modify a file, the diff of that file gets added to your "default changeset". When you attempt to check in the changeset, it automatically tries to merge the news from mainline into your changeset (effectively rebasing it) and then commits. This workflow is enforced without you even needing to understand it. Mainline thus collects a history of changes which you can quite easily cherry pick your way through later. For instance, suppose you want to revert an old one, say, the one before the one before last. You sync to the moment before the offending change, mark the affected files as part of the changeset, sync to the moment after and merge with "always mine". (There was something very interesting there: syncing doesn't mean having the same thing - if a file is editable (i.e. in an active changeset) it won't be clobbered by the sync but marked as due for resolving.) Now you have a changelist that undoes the offending one. Merge in the subsequent news and you have a changelist that you can plop on top of mainline to have the desired effect. At no point did we rewrite any history.
Now, supposing half way through this process, somebody runs up to you and tells you to drop everything and fix some bug. You just give your default changelist a name (a number actually) then "suspend" it, fix the bug in the now empty default changelist, commit it, and resume the named changelist. It's typical to have several changelists suspended at a time where you try different things out. It's easy and private. You get what you really want from a branch regime without the temptation to procrastinate or chicken out of merging to mainline.
I suppose it would be theoretically possible to do something similar in git, but git makes practically anything possible rather than asserting a workflow we approve of. The centralised model is a bunch of valid simplifications relative to the distributed model which is an invalid generalisation. It's so overgeneralised that it basically expects you to implement source control on top of it, as repo does.
The other thing is replication. In git, anything is possible so you have to figure it out for yourself. In perforce, you get an effectively stateless cache. The only configuration it needs to know is where the master is, and the clients can point at either the master or the cache at their discretion. That's a five minute job and it can't go wrong.
You've also got triggers and customisable forms for asserting code reviews, bugzilla references etc, and of course, you have branches for when you actually need them. It's not clearcase, but it's close, and it's dead easy to set up and maintain.
All in all, I think that if you know you're going to work in a centralised way, which everybody does, you might as well use a tool that was designed with that in mind. Git is overrated because of Linus' fearsome wit together with peoples' tendency to follow each other around like sheep, but its main raison d'etre doesn't actually stand up to common sense, and by following it, git ties its own hands with the two huge dogmas that (a) the software and (b) the data have to be the same at both client and server, and that will always make it complicated and lame at the centralised job.
This is an old post, but I was looking for answer to this same question,
Why not try something like:
scale_color_manual(values = c("foo" = "#999999", "bar" = "#E69F00"))
If you have categorical values, I don't see a reason why this should not work.
const int* ptr;
declares ptr
a pointer to const int
type. You can modify ptr
itself but the object pointed to by ptr
shall not be modified.
const int a = 10;
const int* ptr = &a;
*ptr = 5; // wrong
ptr++; // right
While
int * const ptr;
declares ptr
a const
pointer to int
type. You are not allowed to modify ptr
but the object pointed to by ptr
can be modified.
int a = 10;
int *const ptr = &a;
*ptr = 5; // right
ptr++; // wrong
Generally I would prefer the declaration like this which make it easy to read and understand (read from right to left):
int const *ptr; // ptr is a pointer to constant int
int *const ptr; // ptr is a constant pointer to int
You can use Keras, one-line answer will be to use eval
method like so:
import keras.backend as K
print(K.eval(your_tensor))
Assuming you've created your certificates and private keys with Let's Encrypt in /etc/letsencrypt/live/you.com
:
openssl pkcs12 -export -in fullchain.pem -inkey privkey.pem -out pkcs.p12 \
-name letsencrypt
This combines your SSL certificate fullchain.pem
and your private key privkey.pem
into a single file, pkcs.p12
.
You'll be prompted for a password for pkcs.p12
.
The export
option specifies that a PKCS #12 file will be created rather than parsed (according to the manual).
keytool -importkeystore -destkeystore keystore.jks -srckeystore pkcs.p12 \
-srcstoretype PKCS12 -alias letsencrypt
If keystore.jks
doesn't exist, it will be created containing the pkcs.12
file created above. Otherwise, you'll import pkcs.12
into the existing keystore.
These instructions are derived from the post "Create a Java Keystore (.JKS) from Let's Encrypt Certificates" on this blog.
Here's more on the different kind of files in /etc/letsencrypt/live/you.com/
.
To anyone who doesn't want to use DATE_SUB
, use CURRENT_DATE
:
SELECT CURRENT_DATE - INTERVAL 30 DAY
When you build your assembly, you can call AssemblyBuilder.SetEntryPoint
, and then get it back from the Assembly.EntryPoint
property to invoke it.
Keep in mind you'll want to use this signature, and note that it doesn't have to be named Main
:
static void Run(string[] args)
Adding a space before the EOF delimiter allows to avoid cmd:
- shell: |
cat <<' EOF'
This is a test.
EOF
Here is an example to fully programmatically:
I am using the following class vars:
Spinner varSpinner;
List<String> varSpinnerData;
float varScaleX;
float varScaleY;
A - Init and render the Spinner (varRoot is a pointer to my main Activity):
public void renderSpinner() {
List<String> myArraySpinner = new ArrayList<String>();
myArraySpinner.add("red");
myArraySpinner.add("green");
myArraySpinner.add("blue");
varSpinnerData = myArraySpinner;
Spinner mySpinner = new Spinner(varRoot);
varSpinner = mySpinner;
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(varRoot, android.R.layout.simple_spinner_item, myArraySpinner);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down vieww
mySpinner.setAdapter(spinnerArrayAdapter);
B - Resize and Add the Spinner to my View:
FrameLayout.LayoutParams myParamsLayout = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.WRAP_CONTENT);
myParamsLayout.gravity = Gravity.NO_GRAVITY;
myParamsLayout.leftMargin = (int) (100 * varScaleX);
myParamsLayout.topMargin = (int) (350 * varScaleY);
myParamsLayout.width = (int) (300 * varScaleX);;
myParamsLayout.height = (int) (60 * varScaleY);;
varLayoutECommerce_Dialogue.addView(mySpinner, myParamsLayout);
C - Make the Click handler and use this to set the font.
mySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int myPosition, long myID) {
Log.i("renderSpinner -> ", "onItemSelected: " + myPosition + "/" + myID);
((TextView) parentView.getChildAt(0)).setTextColor(Color.GREEN);
((TextView) parentView.getChildAt(0)).setTextSize(TypedValue.COMPLEX_UNIT_PX, (int) (varScaleY * 22.0f) );
((TextView) parentView.getChildAt(0)).setPadding(1,1,1,1);
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
}
D - Update the Spinner with new data:
private void updateInitSpinners(){
String mySelected = varSpinner.getSelectedItem().toString();
Log.i("TPRenderECommerce_Dialogue -> ", "updateInitSpinners -> mySelected: " + mySelected);
varSpinnerData.clear();
varSpinnerData.add("Hello World");
varSpinnerData.add("Hello World 2");
((BaseAdapter) varSpinner.getAdapter()).notifyDataSetChanged();
varSpinner.invalidate();
varSpinner.setSelection(1);
}
}
What I have not been able to solve in the updateInitSpinners, is to do varSpinner.setSelection(0); and have the custom font settings activated automatically.
UPDATE:
This "ugly" solution solves the varSpinner.setSelection(0); issue, but I am not very happy with it:
private void updateInitSpinners(){
String mySelected = varSpinner.getSelectedItem().toString();
Log.i("TPRenderECommerce_Dialogue -> ", "updateInitSpinners -> mySelected: " + mySelected);
varSpinnerData.clear();
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(varRoot, android.R.layout.simple_spinner_item, varSpinnerData);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
varSpinner.setAdapter(spinnerArrayAdapter);
varSpinnerData.add("Hello World");
varSpinnerData.add("Hello World 2");
((BaseAdapter) varSpinner.getAdapter()).notifyDataSetChanged();
varSpinner.invalidate();
varSpinner.setSelection(0);
}
}
Hope this helps......
A possible solution is the following; precondition is, that there are not conflicts in the used enum values. (e.g. when removing an enum value, be sure that this value is not used anymore.)
-- rename the old enum
alter type my_enum rename to my_enum__;
-- create the new enum
create type my_enum as enum ('value1', 'value2', 'value3');
-- alter all you enum columns
alter table my_table
alter column my_column type my_enum using my_column::text::my_enum;
-- drop the old enum
drop type my_enum__;
Also in this way the column order will not be changed.
Your quotes only need to surround the value part of the attribute-equals selector, [attr='val']
, like this:
$('a#check_var').click(function() {
alert($("input:radio[name='r']:checked").val()+ ' '+
$("input:radio[name='s']:checked").val());
});?
Cors change the request method before it's done, from POST to OPTIONS, so, your post data will not be sent. The way that worked to handle this cors issue, is performing the request with ajax, which does not support the OPTIONS method. example code:
$.ajax({
type: "POST",
crossdomain: true,
url: "http://localhost:1415/anything",
dataType: "json",
data: JSON.stringify({
anydata1: "any1",
anydata2: "any2",
}),
success: function (result) {
console.log(result)
},
error: function (xhr, status, err) {
console.error(xhr, status, err);
}
});
with this headers on c# server:
if (request.HttpMethod == "OPTIONS")
{
response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With");
response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
response.AddHeader("Access-Control-Max-Age", "1728000");
}
response.AppendHeader("Access-Control-Allow-Origin", "*");
You can attempt to use the PHP header
function to do the redirect. You will want to set the output buffer so your browser doesn't throw a redirect warning to the screen.
ob_start();
header("Location: " . $website);
ob_end_flush();
I used this for radio's:
if (element.prop("type") === "checkbox" || element.prop("type") === "radio") {
error.appendTo(element.parent().parent());
}
else if (element.parent(".input-group").length) {
error.insertAfter(element.parent());
}
else {
error.insertAfter(element);
}
this way the error is displayed under last radio option.
foreach (DataTable table in dataSet.Tables)
{
foreach (DataRow row in table.Rows)
{
foreach (object item in row.ItemArray)
{
// read item
}
}
}
Or, if you need the column info:
foreach (DataTable table in dataSet.Tables)
{
foreach (DataRow row in table.Rows)
{
foreach (DataColumn column in table.Columns)
{
object item = row[column];
// read column and item
}
}
}
try by Adding following onClientClick event.
OnClientClick="aspnetForm.target ='_blank';"
so on click it will call Javascript function an will open respective link in News tab.
<asp:LinkButton id="lbnkVidTtile1" OnClientClick="aspnetForm.target ='_blank';" runat="Server" CssClass="bodytext" Text='<%# Eval("newvideotitle") %>' />
Remove the z-index value.
I would also recommend this approach.
HTML:
<header class="main-header" role="banner">
<img src="mybannerimage.gif" alt="Banner Image"/>
</header>
CSS:
.main-header {
text-align: center;
}
This will center your image with out stretching it out. You can adjust the padding as needed to give it some space around your image. Since this is at the top of your page you don't need to force it there with position absolute unless you want your other elements to go underneath it. In that case you'd probably want position:fixed; anyway.
Change the window name in your two different calls:
function popitup(url,windowName) {
newwindow=window.open(url,windowName,'height=200,width=150');
if (window.focus) {newwindow.focus()}
return false;
}
windowName must be unique when you open a new window with same url otherwise the same window will be refreshed.
Why use GROUP BY at all?
SELECT player_name, player_salary, player_salary*1.1 AS NewSalary
FROM players
ORDER BY player_salary DESC
If you want to update items with a Where
clause, using a .Where(...) will truncate your results if you do:
mylist = mylist.Where(n => n.Id == ID).Select(n => { n.Property = ""; return n; }).ToList();
You can do updates to specific item(s) in the list like so:
mylist = mylist.Select(n => { if (n.Id == ID) { n.Property = ""; } return n; }).ToList();
Always return item even if you don't make any changes. This way it will be kept in the list.
Old question, new answer (C#).
Another use of underscores for C# is with ASP NET Core's DI (dependency injection). Private readonly
variables of a class which got assigned to the injected interface during construction should start with an underscore. I guess it's a debate whether to use underscore for every private member of a class (although Microsoft itself follows it) but this one is certain.
private readonly ILogger<MyDependency> _logger;
public MyDependency(ILogger<MyDependency> logger)
{
_logger = logger;
}
This Works For me !!!
Call a Function without Parameter
$("#CourseSelect").change(function(e1) {
loadTeachers();
});
Call a Function with Parameter
$("#CourseSelect").change(function(e1) {
loadTeachers($(e1.target).val());
});
$("#test").hide(100, function() {
$(this).html("......").show(100);
});
Updated:
Another easy way:
$("#test").fadeOut(400, function() {
$(this).html("......").fadeIn(400);
});
This is how you should be using mysql_fetch_assoc():
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
// Do stuff with $row
}
$result should be a resource. Even if the query returns no rows, $result is still a resource. The only time $result is a boolean value, is if there was an error when querying the database. In which case, you should find out what that error is by using mysql_error() and ensure that it can't happen. Then you don't have to hide from any errors.
You should always cover the base that errors may happen by doing:
if (!$result) {
die(mysql_error());
}
At least then you'll be more likely to actually fix the error, rather than leave the users with a glaring ugly error in their face.
s = "BINGO"
print(s.replace("", " ")[1: -1])
Timings below
$ python -m timeit -s's = "BINGO"' 's.replace(""," ")[1:-1]'
1000000 loops, best of 3: 0.584 usec per loop
$ python -m timeit -s's = "BINGO"' '" ".join(s)'
100000 loops, best of 3: 1.54 usec per loop
Given an object which I suspect to be some kind of IList<>
, how can I determine of what it's an IList<>
?
Here's the gutsy solution. It assumes you have the actual object to test (rather than a Type
).
public static Type ListOfWhat(Object list)
{
return ListOfWhat2((dynamic)list);
}
private static Type ListOfWhat2<T>(IList<T> list)
{
return typeof(T);
}
Example usage:
object value = new ObservableCollection<DateTime>();
ListOfWhat(value).Dump();
Prints
typeof(DateTime)
This will literally list (that is, print) all subdirectories. It basically is a loop kind of where you don’t need to store the items in between to a list. This is what one most likely needs, so I leave it here.
Path directory = Paths.get("D:\\directory\\to\\list");
Files.walk(directory, 1).filter(entry -> !entry.equals(directory))
.filter(Files::isDirectory).forEach(subdirectory ->
{
// do whatever you want with the subdirectories
System.out.println(subdirectory.getFileName());
});
If it isn't I could see things heading that way.
I'm working on redoing the website for the company I work for and the designer they hired used a 960px width layout. There is also a 960px grid system that seems to be getting quite popular (http://960.gs/).
I've been out of web stuff for a few years but from what I've read catching up on things it seems 960/980 is about right. For mobile ~320px sticks in my mind, by which 960 is divisible. 960 is also evenly divisible by 2, 3, 4, 5, and 6.
In the Object Explorer, drill-down to: Server -> Management -> Activity Monitor. This will allow you to see all connections on to the current server.
The postition:absolute;
tag positions the element relative to it's immediate parent.
I noticed that even in the examples, there isn't room for scrolling, and when i tried it out, it didn't work.
Therefore, to pull off the facebook floating menu, the position:fixed;
tag should be used instead. It displaces/keeps the element at the given/specified location, and the rest of the page can scroll smoothly - even with the responsive ones.
Please see CSS postion attribute documentation when you can :)
Using realpath from GNU coreutils 8.23 is the simplest, I think:
$ realpath --relative-to="$file1" "$file2"
For example:
$ realpath --relative-to=/usr/bin/nmap /tmp/testing
../../../tmp/testing
There are several options. You can use the WebMethod attribute, for your purpose.
Edited at @user3832931 's answer to include server port..
to form URLs like 'https://localhost:8000/folder/'
$base_url="http://".$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].dirname($_SERVER["REQUEST_URI"].'?').'/';
There is the latest techniques to communicate fragment to activity without any interface follow the steps Step 1- Add the dependency in gradle
implementation 'androidx.fragment:fragment:1.3.0-rc01'
I was able to achieve this by using the webkit-line-clamp
and the following css:
div {
display: -webkit-box;
-webkit-line-clamp: 1;
-webkit-box-orient: vertical;
overflow: hidden;
}
Just use the below formation###
rules_id = ["9","10"]
sql2 = "SELECT * FROM attendance_rules_staff WHERE id in"+str(tuple(rules_id))
note the str(tuple(rules_id))
.