The other solutions will work fine on initial page load, but calling $timeout from the controller is the only way to ensure that your function is called when the model changes. Here is a working fiddle that uses $timeout. For your example it would be:
.controller('myC', function ($scope, $timeout) {
$scope.$watch("ta", function (newValue, oldValue) {
$timeout(function () {
test();
});
});
ngRepeat will only evaluate a directive when the row content is new, so if you remove items from your list, onFinishRender will not fire. For example, try entering filter values in these fiddles emit.
The other answers here are very much correct, and valuable. But sometimes you just want simple: to get a plain old parsed value at directive instantiation, without needing updates, and without messing with isolate scope. For instance, it can be handy to provide a declarative payload into your directive as an array or hash-object in the form:
my-directive-name="['string1', 'string2']"
In that case, you can cut to the chase and just use a nice basic angular.$eval(attr.attrName)
.
element.val("value = "+angular.$eval(attr.value));
Working Fiddle.
add .change()
after setting the value.
example:('id').val.('value').change();
also don't forget to add onchange
or ng-change
tag in html
The directive can access any attribute that is defined on the same element, even if the directive itself is not the element.
Template:
<div example-directive example-number="99" example-function="exampleCallback()"></div>
Directive:
app.directive('exampleDirective ', function () {
return {
restrict: 'A', // 'A' is the default, so you could remove this line
scope: {
callback : '&exampleFunction',
},
link: function (scope, element, attrs) {
var num = scope.$eval(attrs.exampleNumber);
console.log('number=',num);
scope.callback(); // calls exampleCallback()
}
};
});
If the value of attribute example-number
will be hard-coded, I suggest using $eval
once, and storing the value. Variable num
will have the correct type (a number).
You shouldn't need a $watch. Just bind to resize event on window:
'use strict';
var app = angular.module('plunker', []);
app.directive('myDirective', ['$window', function ($window) {
return {
link: link,
restrict: 'E',
template: '<div>window size: {{width}}px</div>'
};
function link(scope, element, attrs){
scope.width = $window.innerWidth;
angular.element($window).bind('resize', function(){
scope.width = $window.innerWidth;
// manuall $digest required as resize event
// is outside of angular
scope.$digest();
});
}
}]);
You can pass arguments to your custom directive as you do with the builtin Angular-directives - by specifying an attribute on the directive-element:
angular.element(document.getElementById('wrapper'))
.append('<directive-name title="title2"></directive-name>');
What you need to do is define the scope
(including the argument(s)/parameter(s)) in the factory function of your directive. In below example the directive takes a title
-parameter. You can then use it, for example in the template
, using the regular Angular-way: {{title}}
app.directive('directiveName', function(){
return {
restrict:'E',
scope: {
title: '@'
},
template:'<div class="title"><h2>{{title}}</h2></div>'
};
});
Depending on how/what you want to bind, you have different options:
=
is two-way binding@
simply reads the value (one-way binding)&
is used to bind functionsIn some cases you may want use an "external" name which differs from the "internal" name. With external I mean the attribute name on the directive-element and with internal I mean the name of the variable which is used within the directive's scope.
For example if we look at above directive, you might not want to specify another, additional attribute for the title, even though you internally want to work with a title
-property. Instead you want to use your directive as follows:
<directive-name="title2"></directive-name>
This can be achieved by specifying a name behind the above mentioned option in the scope definition:
scope: {
title: '@directiveName'
}
Please also note following things:
data-
. Angular supports this by stripping the data-
-prefix from any attributes. So in above example you could specify the attribute on the element (data-title="title2"
) and internally everything would be the same.<div data-my-attribute="..." />
while in code (e.g. properties on scope object) they are in the form of myAttribute
. I lost lots of time before I realized this.I've no idea why this worked, but I removed the project reference that VS2015 was telling me it couldn't find, and added it again. Solved the problem. I'd tried both cleaning, building and restarting VS to no avail.
Since this must have an input element as a parent, you could just use
<input type="text" ng-model="foo" ng-change="myOnChangeFunction()">
Alternatively, you could use the ngModelController
and add a function to $formatters
, which executes functions on input change. See http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController
.directive("myDirective", function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attr, ngModel) {
ngModel.$formatters.push(function(value) {
// Do stuff here, and return the formatted value.
});
};
};
the easiest way to do that in angular or angularjs without external modules or directives is using list and datalist HTML5. You just get a json and use ng-repeat for feeding the options in datalist. The json you can fetch it from ajax.
in this example:
then you can add filters and orderby in the ng-reapet
!! list and datalist id must have the same name !!
<input type="text" list="autocompleList" ng-model="ctrl.query" placeholder={{ctrl.msg}}>
<datalist id="autocompleList">
<option ng-repeat="Ids in ctrl.dataList value={{Ids}} >
</datalist>
UPDATE : is native HTML5 but be carreful with the type browser and version. check it out : https://caniuse.com/#search=datalist.
You can also remove the line
require: 'ngModel',
if you don't need ngModel
in this directive. Removing ngModel
will allow you to make a directive without thatngModel
error.
I wouldn't set the ngmodel via an attribute, you can specify it right in the template:
template: '<div class="some"><label>{{label}}</label><input data-ng-model="ngModel"></div>',
This works for me: http://gitblit.com/setup_client.html
Eclipse/EGit/JGit
Window->Preferences->Team->Git->Configuration
Click the New Entry button
Key = http.sslVerify
Value = false
For the async Method ("ExecuteSqlCommandAsync") you can use it like this:
var sql = @"Update [User] SET FirstName = @FirstName WHERE Id = @Id";
await ctx.Database.ExecuteSqlCommandAsync(
sql,
parameters: new[]{
new SqlParameter("@FirstName", firstname),
new SqlParameter("@Id", id)
});
For what it's worth, here is my way:
List<string> list = new List<string>(new string[] { "cat", "Dog", "parrot", "dog", "parrot", "goat", "parrot", "horse", "goat" });
Dictionary<string, int> wordCount = new Dictionary<string, int>();
//count them all:
list.ForEach(word =>
{
string key = word.ToLower();
if (!wordCount.ContainsKey(key))
wordCount.Add(key, 0);
wordCount[key]++;
});
//remove words appearing only once:
wordCount.Keys.ToList().FindAll(word => wordCount[word] == 1).ForEach(key => wordCount.Remove(key));
Console.WriteLine(string.Format("Found {0} duplicates in the list:", wordCount.Count));
wordCount.Keys.ToList().ForEach(key => Console.WriteLine(string.Format("{0} appears {1} times", key, wordCount[key])));
I had a similar issue and followed all the instructions above regarding changing owners using sudo chown etc. I still had an instance of mongodb running in the background after the changes. Running
ps auxw | grep mongo
showed me other tasks using mongo running in background that weren't closed properly. I then ran kill on all the ones running and then could start my server.
I recommendo to you use TtoC from ConvUnicode.h
const CString word= "hello";
const char* myFile = TtoC(path.GetString());
It is a macro to do conversions per Unicode
\usepackage{array}
in the preamble
then this:
\begin{tabular}{| >{\centering\arraybackslash}m{1in} | >{\centering\arraybackslash}m{1in} |}
note that the "m" for fixed with column is provided by the array package, and will give you vertical centering (if you don't want this just go back to "p"
-split outputs an array, and you can save it to a variable like this:
$a = -split 'Once upon a time'
$a[0]
Once
Another cute thing, you can have arrays on both sides of an assignment statement:
$a,$b,$c = -split 'Once upon a'
$c
a
You want to get an element from an empty array. That's why the Size: 0
from the exception
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
So you cant do lstpp.get(0)
until you fill the array.
public static string textDataSource = "Data Source=localhost;Initial
Catalog=TEST_C;User ID=sa;Password=P@ssw0rd";
public static bool ExtSql(string sql) {
SqlConnection cnn;
SqlCommand cmd;
cnn = new SqlConnection(textDataSource);
cmd = new SqlCommand(sql, cnn);
try {
cnn.Open();
cmd.ExecuteNonQuery();
cnn.Close();
return true;
}
catch (Exception) {
return false;
}
finally {
cmd.Dispose();
cnn = null;
cmd = null;
}
}
You can't (usefully) compare strings using !=
or ==
, you need to use strcmp
:
while (strcmp(check,input) != 0)
The reason for this is because !=
and ==
will only compare the base addresses of those strings. Not the contents of the strings themselves.
In Windows Forms, you have the app.config
file, which is very similar to the web.config
file. But since what I see you need it for are custom values, I suggest using Settings.
To do that, open your project properties, and then go to settings. If a settings file does not exist you will have a link to create one. Then, you can add the settings to the table you see there, which would generate both the appropriate XML, and a Settings class that can be used to load and save the settings.
The settings class will be named something like DefaultNamespace.Properties.Settings
. Then, you can use code similar to:
using DefaultNamespace.Properties;
namespace DefaultNamespace {
class Class {
public int LoadMySettingValue() {
return Settings.Default.MySettingValue;
}
public void SaveMySettingValue(int value) {
Settings.Default.MySettingValue = value;
}
}
}
I m using android studio 3.0 and i upgrade the design pattern dependency from 26.0.1 to 27.1.1 and the error is gone now.
Add Following in gradle
implementation 'com.android.support:design:27.1.1'
First and foremost make sure the correct provisioning profile is selected for the configuration that you have selected before building if you have manually set the provisioning profile. If you have set automatic as your provisioning profile make sure the correct provisioning profile is being picked up by Xcode while building.
the html element break line depend of it's white-space
style property.
in the most of the elements the default white-space
is auto
, which mean break line when the text come to the width of the element.
if you want the text break by \n
you have to give to the parent element the style:
white space: pre-line
, which will read the \n
and break the line, or
white-space: pre
which will also read \t
etc.
note: to write \n
as break-line and not as a string , you have to use a double quoted string ("\n"
)
if you not wanna use a white space, you always welcome to use the HTML Element for break line, which is <br/>
The answers above are good. Adding a case that I used. Just if you don't want to use numpy and keep it as list without changing the contents.
You can run a small loop and change the dimension from 1xN to Nx1.
tmp=[]
for b in bus:
tmp.append([b])
bus=tmp
It is maybe not efficient while in case of very large numbers. But it works for a small set of numbers. Thanks
You can use:
Select
count(created_date) as counted_leads,
created_date as count_date
from
table
group by
created_date
In my case, the
fileItem.getOutputStream();
wasn't working. Thus I made it myself using IOUtils,
File file = new File("/path/to/file");
FileItem fileItem = new DiskFileItem("mainFile", Files.probeContentType(file.toPath()), false, file.getName(), (int) file.length(), file.getParentFile());
try {
InputStream input = new FileInputStream(file);
OutputStream os = fileItem.getOutputStream();
IOUtils.copy(input, os);
// Or faster..
// IOUtils.copy(new FileInputStream(file), fileItem.getOutputStream());
} catch (IOException ex) {
// do something.
}
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
It is just a collection of routines (functional programming) or class definitions(object oriented programming). The reason behind is simply code reuse, i.e. get the code that has already been written by other developers. The classes or routines normally define specific operations in a domain specific area. For example, there are some libraries of mathematics which can let developer just call the function without redo the implementation of how an algorithm works.
In framework, all the control flow is already there, and there are a bunch of predefined white spots that we should fill out with our code. A framework is normally more complex. It defines a skeleton where the application defines its own features to fill out the skeleton. In this way, your code will be called by the framework when appropriately. The benefit is that developers do not need to worry about if a design is good or not, but just about implementing domain specific functions.
The key difference between a library and a framework is “Inversion of Control”. When you call a method from a library, you are in control. But with a framework, the control is inverted: the framework calls you. Source.
Both of them defined API, which is used for programmers to use. To put those together, we can think of a library as a certain function of an application, a framework as the skeleton of the application, and an API is connector to put those together. A typical development process normally starts with a framework, and fill out functions defined in libraries through API.
As people mentioned in the comments you probably don't want to do that... The answer from mipadi is absolutely correct if you know what you're doing.
I would say:
git checkout master
git pull # to update the state to the latest remote master state
git merge develop # to bring changes to local master from your develop branch
git push origin master # push current HEAD to remote master branch
editText.setInputType(InputType.TYPE_NULL);
dir(sys)
says no. len(sys.argv)
works, but in Python it is better to ask for forgiveness than permission, so
#!/usr/bin/python
import sys
try:
in_file = open(sys.argv[1], "r")
except:
sys.exit("ERROR. Can't read supplied filename.")
text = in_file.read()
print(text)
in_file.close()
works fine and is shorter.
If you're going to exit anyway, this would be better:
#!/usr/bin/python
import sys
text = open(sys.argv[1], "r").read()
print(text)
I'm using print()
so it works in 2.7 as well as Python 3.
I have had the same problem and thanks to the posts here I have solved it. I knew that I have around a hundred files and I needed to run it for *.js files only.
find . -type f -name '*.js' -print0 | xargs -0 dos2unix
Thank you all for your help.
You might want to create a web service for your common methods.
Just add a WebMethodAttribute over the functions you want to call, and that's about it.
Having a web service with all your common stuff also makes the system easier to maintain.
If you don't want to reinvent the wheel you may try plupload.com
When creating your own library, you can can create *.d.ts
files by using the tsc
(TypeScript Compiler) command like so:
(assuming you're building your library to the dist/lib
folder)
tsc -d --declarationDir dist/lib --declarationMap --emitDeclarationOnly
-d
(--declaration
): generates the *.d.ts
files--declarationDir dist/lib
: Output directory for generated declaration files.--declarationMap
: Generates a sourcemap for each corresponding ‘.d.ts’ file.--emitDeclarationOnly
: Only emit ‘.d.ts’ declaration files. (no compiled JS)(see the docs for all command line compiler options)
Or for instance in your package.json
:
"scripts": {
"build:types": "tsc -d --declarationDir dist/lib --declarationMap --emitDeclarationOnly",
}
and then run: yarn build:types
(or npm run build:types
)
If you installed node/npm with nvm, the nvm environment configuration file has to be run before you can use either package.
This is generally found in ~/.nvm/nvm.sh.
To run this automatically, include:
source ~/.nvm/nvm.sh
in the .bash_profile file for your user
If you then want to use sudo with that user, make sure to include the -i parameter to make sudo set the user environment. eg
sudo -iu jenkins npm install grunt-cli
You are not getting the answer you are looking for, are you.
Two ways to do what you want:
You could also use a StringVar
variable, even if it's not strictly necessary:
v = StringVar()
e = Entry(master, textvariable=v)
e.pack()
v.set("a default value")
s = v.get()
For more information, see this page on effbot.org.
You are missing two closing parentheses...and I am not sure an ampersand works as a string concatenation operator. Try '+'
SELECT dbo.COL_V_Cost_GEMS_Detail.TNG_SYS_NR AS [EHP Code],
dbo.COL_TBL_VCOURSE.TNG_NA AS [Course Title],
LTRIM(RTRIM(FCT_TYP_CD)) + ') AND (' + LTRIM(RTRIM(DEP_TYP_ID)) + ')' AS [Course Owner]
The toolset on the client side would be one. And the familiarity with SOAP services the other. More and more services are going the RESTful route these days, and testing such services can be done with simple cURL examples. Although, it's not all that difficult to implement both methods and allow for the widest utilization from clients.
If you need to pick one, I'd suggest REST, it's easier.
A more generic answer that would have saved me time, and hopefully others:
Does not work (returns count of all rows):
DB::table('users')
->select('first_name')
->distinct()
->count();
The fix:
DB::table('users')
->distinct()
->count('first_name');
The static
keyword in C is used in a compiled file (.c as opposed to .h) so that the function exists only in that file.
Normally, when you create a function, the compiler generates cruft the linker can use to, well, link a function call to that function. If you use the static keyword, other functions within the same file can call this function (because it can be done without resorting to the linker), while the linker has no information letting other files access the function.
Try the JavaScriptSerializer instead of the DataContractJsonSerializer
JavaScriptSerializer serializer = new JavaScriptSerializer();
var output = serializer.Serialize(your_anon_object);
SELECT DATEADD(week, @weekNumber - 1, DATEADD(DAY, @@datefirst - DATEPART(weekday, CAST(YEAR(GETDATE()) AS VARCHAR) + '-01-01') - 6, CAST(YEAR(GETDATE()) AS VARCHAR) + '-01-01'))
The best practice is using File.separator in the paths.
Like that we can do....
int main(int argc, char *argv[]) {
int a, b, c;
*// Converting string type to integer type
// using function "atoi( argument)"*
a = atoi(argv[1]);
b = atoi(argv[2]);
c = atoi(argv[3]);
}
>>> d = {'1': 'one', '3': 'three', '2': 'two', '5': 'five', '4': 'four'}
>>> 'one' in d.values()
True
Out of curiosity, some comparative timing:
>>> T(lambda : 'one' in d.itervalues()).repeat()
[0.28107285499572754, 0.29107213020324707, 0.27941107749938965]
>>> T(lambda : 'one' in d.values()).repeat()
[0.38303399085998535, 0.37257885932922363, 0.37096405029296875]
>>> T(lambda : 'one' in d.viewvalues()).repeat()
[0.32004380226135254, 0.31716084480285645, 0.3171098232269287]
EDIT: And in case you wonder why... the reason is that each of the above returns a different type of object, which may or may not be well suited for lookup operations:
>>> type(d.viewvalues())
<type 'dict_values'>
>>> type(d.values())
<type 'list'>
>>> type(d.itervalues())
<type 'dictionary-valueiterator'>
EDIT2: As per request in comments...
>>> T(lambda : 'four' in d.itervalues()).repeat()
[0.41178202629089355, 0.3959040641784668, 0.3970959186553955]
>>> T(lambda : 'four' in d.values()).repeat()
[0.4631338119506836, 0.43541407585144043, 0.4359898567199707]
>>> T(lambda : 'four' in d.viewvalues()).repeat()
[0.43414998054504395, 0.4213531017303467, 0.41684913635253906]
All normal "calculating" instructions like adding multiplication, exclusive or set the status flags like zero, sign. If you use a complicated address, AX xor:= mem[0x333 +BX + 8*CX]
the flags are set according to the xor operation.
Now you may want to use the address multiple times. Loading such an addres into a register is never intended to set status flags and luckily it doesn't. The phrase "load effective address" makes the programmer aware of that. That is where the weird expression comes from.
It is clear that once the processor is capable of using the complicated address to process its content, it is capable of calculating it for other purposes. Indeed it can be used to perform a transformation x <- 3*x+1
in one instruction. This is a general rule in assembly programming: Use the instructions however it rocks your boat.
The only thing that counts is whether the particular transformation embodied by the instruction is useful for you.
Bottom line
MOV, X| T| AX'| R| BX|
and
LEA, AX'| [BX]
have the same effect on AX but not on the status flags. (This is ciasdis notation.)
You are not comparing dates. You are comparing strings. In the world of string comparisons, 09/17/2015
> 01/02/2016
because 09
> 01
. You need to either put your date in a comparable string format or compare DateTime
objects which are comparable.
<?php
$date_now = date("Y-m-d"); // this format is string comparable
if ($date_now > '2016-01-02') {
echo 'greater than';
}else{
echo 'Less than';
}
Or
<?php
$date_now = new DateTime();
$date2 = new DateTime("01/02/2016");
if ($date_now > $date2) {
echo 'greater than';
}else{
echo 'Less than';
}
http://docs.oracle.com/javase/7/docs/api/javax/swing/JTable.html
You will find these methods in it:
getValueAt(int row, int column)
getSelectedRow()
getSelectedColumn()
Use a mix of these to achieve your result.
I had a CASE statement with WHEN column = 'sometext & more text' THEN ....
I replaced it with WHEN column = 'sometext ' || CHR(38) || ' more text' THEN ...
you could also use WHEN column LIKE 'sometext _ more text' THEN ...
(_ is the wildcard for a single character)
aca definis los anchos
float[] anchoDeColumnas= new float[] {10f, 20f, 30f, 10f};
aca se los insertas a la tabla que tiene las columnas
table.setWidths(anchoDeColumnas);
Below command will work in command prompt:
copy c:\folder\file.ext \\dest-machine\destfolder /Z /Y
To Copy all files:
copy c:\folder\*.* \\dest-machine\destfolder /Z /Y
You can solve using Google CSE (Custom Searche Engine), which can be easily inserted into an iframe. You can create your own search engine, that search selected sites or also in entire Google's database.
The results can be styled as you prefer, also similar to Google style. Google CSE works with web and images search.
google.php
<script>
(function() {
var cx = 'xxxxxxxxxxxxxxxxxxxxxx';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
</script>
<gcse:searchresults-only></gcse:searchresults-only>
yourpage.php
<iframe src="google.php?q=<?php echo urlencode('your query'); ?>"></iframe>
It's not bad practice at all. They are usually referred as SUBQUERY, SUBSELECT or NESTED QUERY.
It's a relatively expensive operation, but it's quite common to encounter a lot of subqueries when dealing with databases since it's the only way to perform certain kind of operations on data.
Late to the party but ...
I'm new to python and come from a lisp background. This is what I came up with (check out the var names for lulz):
def flatten(lst):
if lst:
car,*cdr=lst
if isinstance(car,(list,tuple)):
if cdr: return flatten(car) + flatten(cdr)
return flatten(car)
if cdr: return [car] + flatten(cdr)
return [car]
Seems to work. Test:
flatten((1,2,3,(4,5,6,(7,8,(((1,2)))))))
returns:
[1, 2, 3, 4, 5, 6, 7, 8, 1, 2]
SWIFT 3.01
let secondViewController = self.storyboard?.instantiateViewController(withIdentifier: "Conversation_VC") as! Conversation_VC
self.navigationController?.pushViewController(secondViewController, animated: true)
Without time than try like this:
TimeSpan ts = new TimeSpan(23, 59, 59);
toDate = toDate.Add(ts);
List<AuditLog> resultLogs =
_dbContext.AuditLogs
.Where(al => al.Log_Date >= fromDate && al.Log_Date <= toDate)
.ToList();
return resultLogs;
A good article about realistic password strength estimation is:
Dropbox Tech Blog » Blog Archive » zxcvbn: realistic password strength estimation
Never try to edit to @_ variable!!!! They must be not touched.. Or you get some unsuspected effect. For example...
my $size=1234;
sub sub1{
$_[0]=500;
}
sub1 $size;
Before call sub1 $size contain 1234. But after 500(!!) So you Don't edit this value!!! You may pass two or more values and change them in subroutine and all of them will be changed! I've never seen this effect described. Programs I've seen also leave @_ array readonly. And only that you may safely pass variable don't changed internal subroutine You must always do that:
sub sub2{
my @m=@_;
....
}
assign @_ to local subroutine procedure variables and next worked with them. Also in some deep recursive algorithms that returun array you may use this approach to reduce memory used for local vars. Only if return @_ array the same.
Just drag it into the Frameworks, Libraries, and Embedded Content
of the General
section of the Target
:
Note that Xcode 11 and 10 have a very similar flow too.
List<target> targetList = new List<target>(originalList.Cast<target>());
A metaclass is a class that tells how (some) other class should be created.
This is a case where I saw metaclass as a solution to my problem: I had a really complicated problem, that probably could have been solved differently, but I chose to solve it using a metaclass. Because of the complexity, it is one of the few modules I have written where the comments in the module surpass the amount of code that has been written. Here it is...
#!/usr/bin/env python
# Copyright (C) 2013-2014 Craig Phillips. All rights reserved.
# This requires some explaining. The point of this metaclass excercise is to
# create a static abstract class that is in one way or another, dormant until
# queried. I experimented with creating a singlton on import, but that did
# not quite behave how I wanted it to. See now here, we are creating a class
# called GsyncOptions, that on import, will do nothing except state that its
# class creator is GsyncOptionsType. This means, docopt doesn't parse any
# of the help document, nor does it start processing command line options.
# So importing this module becomes really efficient. The complicated bit
# comes from requiring the GsyncOptions class to be static. By that, I mean
# any property on it, may or may not exist, since they are not statically
# defined; so I can't simply just define the class with a whole bunch of
# properties that are @property @staticmethods.
#
# So here's how it works:
#
# Executing 'from libgsync.options import GsyncOptions' does nothing more
# than load up this module, define the Type and the Class and import them
# into the callers namespace. Simple.
#
# Invoking 'GsyncOptions.debug' for the first time, or any other property
# causes the __metaclass__ __getattr__ method to be called, since the class
# is not instantiated as a class instance yet. The __getattr__ method on
# the type then initialises the class (GsyncOptions) via the __initialiseClass
# method. This is the first and only time the class will actually have its
# dictionary statically populated. The docopt module is invoked to parse the
# usage document and generate command line options from it. These are then
# paired with their defaults and what's in sys.argv. After all that, we
# setup some dynamic properties that could not be defined by their name in
# the usage, before everything is then transplanted onto the actual class
# object (or static class GsyncOptions).
#
# Another piece of magic, is to allow command line options to be set in
# in their native form and be translated into argparse style properties.
#
# Finally, the GsyncListOptions class is actually where the options are
# stored. This only acts as a mechanism for storing options as lists, to
# allow aggregation of duplicate options or options that can be specified
# multiple times. The __getattr__ call hides this by default, returning the
# last item in a property's list. However, if the entire list is required,
# calling the 'list()' method on the GsyncOptions class, returns a reference
# to the GsyncListOptions class, which contains all of the same properties
# but as lists and without the duplication of having them as both lists and
# static singlton values.
#
# So this actually means that GsyncOptions is actually a static proxy class...
#
# ...And all this is neatly hidden within a closure for safe keeping.
def GetGsyncOptionsType():
class GsyncListOptions(object):
__initialised = False
class GsyncOptionsType(type):
def __initialiseClass(cls):
if GsyncListOptions._GsyncListOptions__initialised: return
from docopt import docopt
from libgsync.options import doc
from libgsync import __version__
options = docopt(
doc.__doc__ % __version__,
version = __version__,
options_first = True
)
paths = options.pop('<path>', None)
setattr(cls, "destination_path", paths.pop() if paths else None)
setattr(cls, "source_paths", paths)
setattr(cls, "options", options)
for k, v in options.iteritems():
setattr(cls, k, v)
GsyncListOptions._GsyncListOptions__initialised = True
def list(cls):
return GsyncListOptions
def __getattr__(cls, name):
cls.__initialiseClass()
return getattr(GsyncListOptions, name)[-1]
def __setattr__(cls, name, value):
# Substitut option names: --an-option-name for an_option_name
import re
name = re.sub(r'^__', "", re.sub(r'-', "_", name))
listvalue = []
# Ensure value is converted to a list type for GsyncListOptions
if isinstance(value, list):
if value:
listvalue = [] + value
else:
listvalue = [ None ]
else:
listvalue = [ value ]
type.__setattr__(GsyncListOptions, name, listvalue)
# Cleanup this module to prevent tinkering.
import sys
module = sys.modules[__name__]
del module.__dict__['GetGsyncOptionsType']
return GsyncOptionsType
# Our singlton abstract proxy class.
class GsyncOptions(object):
__metaclass__ = GetGsyncOptionsType()
Take a look at this thread: Print ZPL codes to ZEBRA printer using PrintDocument class.
Specifically the OP pick this function from the answers to the thread:
[DllImport("kernel32.dll", SetLastError = true)]
static extern SafeFileHandle CreateFile(string lpFileName, FileAccess dwDesiredAccess,
uint dwShareMode, IntPtr lpSecurityAttributes, FileMode dwCreationDisposition,
uint dwFlagsAndAttributes, IntPtr hTemplateFile);
private void Print()
{
// Command to be sent to the printer
string command = "^XA^FO10,10,^AO,30,20^FDFDTesting^FS^FO10,30^BY3^BCN,100,Y,N,N^FDTesting^FS^XZ";
// Create a buffer with the command
Byte[] buffer = new byte[command.Length];
buffer = System.Text.Encoding.ASCII.GetBytes(command);
// Use the CreateFile external func to connect to the LPT1 port
SafeFileHandle printer = CreateFile("LPT1:", FileAccess.ReadWrite, 0, IntPtr.Zero, FileMode.Open, 0, IntPtr.Zero);
// Aqui verifico se a impressora é válida
if (printer.IsInvalid == true)
{
return;
}
// Open the filestream to the lpt1 port and send the command
FileStream lpt1 = new FileStream(printer, FileAccess.ReadWrite);
lpt1.Write(buffer, 0, buffer.Length);
// Close the FileStream connection
lpt1.Close();
}
Should be :
HTML :
<form method="post" action="">
<input id="name" name="name" type="text" size="40"/>
<input type="radio" name="radio" value="test"/>Test
<input type="submit" name="submit" value="submit"/>
</form>
PHP Code :
if(isset($_POST['submit']))
{
echo $radio_value = $_POST["radio"];
}
you make the use of the HTML Helper and have
@using(Html.BeginForm())
{
Username: <input type="text" name="username" /> <br />
Password: <input type="text" name="password" /> <br />
<input type="submit" value="Login">
<input type="submit" value="Create Account"/>
}
or use the Url helper
<form method="post" action="@Url.Action("MyAction", "MyController")" >
Html.BeginForm
has several (13) overrides where you can specify more information, for example, a normal use when uploading files is using:
@using(Html.BeginForm("myaction", "mycontroller", FormMethod.Post, new {enctype = "multipart/form-data"}))
{
< ... >
}
If you don't specify any arguments, the Html.BeginForm()
will create a POST
form that points to your current controller and current action. As an example, let's say you have a controller called Posts
and an action called Delete
public ActionResult Delete(int id)
{
var model = db.GetPostById(id);
return View(model);
}
[HttpPost]
public ActionResult Delete(int id)
{
var model = db.GetPostById(id);
if(model != null)
db.DeletePost(id);
return RedirectToView("Index");
}
and your html page would be something like:
<h2>Are you sure you want to delete?</h2>
<p>The Post named <strong>@Model.Title</strong> will be deleted.</p>
@using(Html.BeginForm())
{
<input type="submit" class="btn btn-danger" value="Delete Post"/>
<text>or</text>
@Url.ActionLink("go to list", "Index")
}
How is this different from the following?
This line of code here:
String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));
constructs a new String object (i.e. a copy of oldString
), while this line of code:
String newString = oldString;
declares a new variable of type java.lang.String
and initializes it to refer to the same String object as the variable oldString
.
Is there any scenario in which the two lines will have different outputs?
Absolutely:
String newString = oldString;
boolean isSameInstance = newString == oldString; // isSameInstance == true
vs.
String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));
// isSameInstance == false (in most cases)
boolean isSameInstance = newString == oldString;
a_horse_with_no_name (see comment) is right of course. The equivalent of
String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));
is
String newString = new String(oldString);
minus the subtle difference wrt the encoding that Peter Lawrey explains in his answer.
I know this is old but neither an <svg>
group tag nor a <g>
fixed the issue I was facing. I needed to adjust the y position of a tag which also had animation on it.
The solution was to use both the and tag together:
<svg y="1190" x="235">
<g class="light-1">
<path />
</g>
</svg>
A cursor will only accept a select statement, so if the SQL really needs to be dynamic make the declare cursor part of the statement you are executing. For the below to work your server will have to be using global cursors.
Declare @UserID varchar(100)
declare @sqlstatement nvarchar(4000)
--move declare cursor into sql to be executed
set @sqlstatement = 'Declare users_cursor CURSOR FOR SELECT userId FROM users'
exec sp_executesql @sqlstatement
OPEN users_cursor
FETCH NEXT FROM users_cursor
INTO @UserId
WHILE @@FETCH_STATUS = 0
BEGIN
Print @UserID
EXEC asp_DoSomethingStoredProc @UserId
FETCH NEXT FROM users_cursor --have to fetch again within loop
INTO @UserId
END
CLOSE users_cursor
DEALLOCATE users_cursor
If you need to avoid using the global cursors, you could also insert the results of your dynamic SQL into a temporary table, and then use that table to populate your cursor.
Declare @UserID varchar(100)
create table #users (UserID varchar(100))
declare @sqlstatement nvarchar(4000)
set @sqlstatement = 'Insert into #users (userID) SELECT userId FROM users'
exec(@sqlstatement)
declare users_cursor cursor for Select UserId from #Users
OPEN users_cursor
FETCH NEXT FROM users_cursor
INTO @UserId
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC asp_DoSomethingStoredProc @UserId
FETCH NEXT FROM users_cursor
INTO @UserId
END
CLOSE users_cursor
DEALLOCATE users_cursor
drop table #users
To solve this issue, I downgraded to JDK version 1.7.0_21. then I used this little bash script to change the version I use.
function setjdk() {
if [ $# -ne 0 ]; then
removeFromPath '/System/Library/Frameworks/JavaVM.framework/Home/bin'
if [ -n "${JAVA_HOME+x}" ]; then
removeFromPath $JAVA_HOME
fi
export JAVA_HOME=`/usr/libexec/java_home -v $@`
export PATH=$JAVA_HOME/bin:$PATH
fi
}
function removeFromPath() {
export PATH=$(echo $PATH | sed -E -e "s;:$1;;" -e "s;$1:?;;")
}
Once you have the bash script in your zshrc/bshrc file, just call setJdk 1.7.0_21
and you're good to go.
Yes, it's historical. Without it, it creates an old-style class.
If you use type()
on an old-style object, you just get "instance". On a new-style object you get its class.
Use onkeypress
. Check if the pressed key is enter (keyCode = 13). if yes, call the searching()
function.
HTML
<input name="keywords" type="text" id="keywords" size="50" onkeypress="handleKeyPress(event)">
JAVASCRIPT
function handleKeyPress(e){
var key=e.keyCode || e.which;
if (key==13){
searching();
}
}
Here is a snippet showing it in action:
document.getElementById("msg1").innerHTML = "Default";_x000D_
function handle(e){_x000D_
document.getElementById("msg1").innerHTML = "Trigger";_x000D_
var key=e.keyCode || e.which;_x000D_
if (key==13){_x000D_
document.getElementById("msg1").innerHTML = "HELLO!";_x000D_
}_x000D_
}
_x000D_
<input type="text" name="box22" value="please" onkeypress="handle(event)"/>_x000D_
<div id="msg1"></div>
_x000D_
In Angular (currently on Angular-6) .subscribe()
is a method on the Observable type. The Observable type is a utility that asynchronously or synchronously streams data to a variety of components or services that have subscribed to the observable.
The observable is an implementation/abstraction over the promise chain and will be a part of ES7 as a proposed and very supported feature. In Angular it is used internally due to rxjs being a development dependency.
An observable itself can be thought of as a stream of data coming from a source, in Angular this source is an API-endpoint, a service, a database or another observable. But the power it has is that it's not expecting a single response. It can have one or many values that are returned.
Link to rxjs for observable/subscribe docs here: https://rxjs-dev.firebaseapp.com/api/index/class/Observable#subscribe-
Subscribe takes 3 methods as parameters each are functions:
Within each of these, there is the potentional to pipe (or chain) other utilities called operators onto the results to change the form or perform some layered logic.
In the simple example above:
.subscribe(hero => this.hero = hero);
basically says on this observable take the hero being emitted and set it to this.hero
.
Adding this answer to give more context to Observables based off the documentation and my understanding.
time = Time.now.to_s
time = DateTime.parse(time).strftime("%d/%m/%Y %H:%M")
for increment decrement month use << >> operators
examples
datetime_month_before = DateTime.parse(time) << 1
datetime_month_before = DateTime.now << 1
For Sizing Icons
Both our Web Fonts + CSS and SVG + JS frameworks include some basic controls for sizing icons in the context of your page’s UI.
you can use like
<i class="fas fa-camera fa-xs"></i>
<i class="fas fa-camera fa-sm"></i>
<i class="fas fa-camera fa-lg"></i>
<i class="fas fa-camera fa-2x"></i>
<i class="fas fa-camera fa-3x"></i>
<i class="fas fa-camera fa-5x"></i>
<i class="fas fa-camera fa-7x"></i>
<i class="fas fa-camera fa-10x"></i>
https://fontawesome.com/how-to-use/on-the-web/styling/sizing-icons
In whatever (loosely-typed) language you can always cast a string to a number by adding a zero to it.
However, there is very little sense in this as PHP will do it automatically at the time of using this variable, and it will be cast to a string anyway at the time of output.
Note that you may wish to keep dotted numbers as strings, because after casting to float it may be changed unpredictably, due to float numbers' nature.
If the string is guaranteed to have one quote (or any other single character) at beginning and end which you'd like to remove:
str = str.slice(1, -1);
slice
has much less overhead than a regular expression.
Just place "javascript:void(0)", in place of "#" in href tag
<a href="javascript:void(0);" onclick="callmymethod(24)">Call</a>
@Michael Durrant's answer ably covers the shell itself, but the shell environment also includes the various commands you use in the shell and these are going to be similar -- but not identical -- between OS X and linux. In general, both will have the same core commands and features (especially those defined in the Posix standard), but a lot of extensions will be different.
For example, linux systems generally have a useradd
command to create new users, but OS X doesn't. On OS X, you generally use the GUI to create users; if you need to create them from the command line, you use dscl
(which linux doesn't have) to edit the user database (see here). (Update: starting in macOS High Sierra v10.13, you can use sysadminctl -addUser
instead.)
Also, some commands they have in common will have different features and options. For example, linuxes generally include GNU sed
, which uses the -r
option to invoke extended regular expressions; on OS X, you'd use the -E
option to get the same effect. Similarly, in linux you might use ls --color=auto
to get colorized output; on macOS, the closest equivalent is ls -G
.
EDIT: Another difference is that many linux commands allow options to be specified after their arguments (e.g. ls file1 file2 -l
), while most OS X commands require options to come strictly first (ls -l file1 file2
).
Finally, since the OS itself is different, some commands wind up behaving differently between the OSes. For example, on linux you'd probably use ifconfig
to change your network configuration. On OS X, ifconfig
will work (probably with slightly different syntax), but your changes are likely to be overwritten randomly by the system configuration daemon; instead you should edit the network preferences with networksetup
, and then let the config daemon apply them to the live network state.
I would use an asynchronous access using a completion block.
This example saves the Google logo to the document directory of the device. (iOS 5+, OSX 10.7+)
NSString *documentDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *filePath = [documentDir stringByAppendingPathComponent:@"GoogleLogo.png"];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.google.com/images/srpr/logo11w.png"]];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error) {
NSLog(@"Download Error:%@",error.description);
}
if (data) {
[data writeToFile:filePath atomically:YES];
NSLog(@"File is saved to %@",filePath);
}
}];
Use this code for find the which key pressed
from pynput import keyboard
def on_press(key):
try:
print('alphanumeric key {0} pressed'.format(
key.char))
except AttributeError:
print('special key {0} pressed'.format(
key))
def on_release(key):
print('{0} released'.format(
key))
if key == keyboard.Key.esc:
# Stop listener
return False
# Collect events until released
with keyboard.Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
use a css3 class "spinner". It's more beautiful and you don't need .gif
.spinner {
position: absolute;
left: 50%;
top: 50%;
height:60px;
width:60px;
margin:0px auto;
-webkit-animation: rotation .6s infinite linear;
-moz-animation: rotation .6s infinite linear;
-o-animation: rotation .6s infinite linear;
animation: rotation .6s infinite linear;
border-left:6px solid rgba(0,174,239,.15);
border-right:6px solid rgba(0,174,239,.15);
border-bottom:6px solid rgba(0,174,239,.15);
border-top:6px solid rgba(0,174,239,.8);
border-radius:100%;
}
@-webkit-keyframes rotation {
from {-webkit-transform: rotate(0deg);}
to {-webkit-transform: rotate(359deg);}
}
@-moz-keyframes rotation {
from {-moz-transform: rotate(0deg);}
to {-moz-transform: rotate(359deg);}
}
@-o-keyframes rotation {
from {-o-transform: rotate(0deg);}
to {-o-transform: rotate(359deg);}
}
@keyframes rotation {
from {transform: rotate(0deg);}
to {transform: rotate(359deg);}
}
Exemple of what is looks like : http://jsbin.com/roqakuxebo/1/edit
You can find a lot of css spinners like this here : http://cssload.net/en/spinners/
In Django this is trivial (and actually works, I had issues with a number of the solutions not correctly returning negatives for latitude).
For instance, let's say you are using django-geopostcodes (of which I am the author).
from django.contrib.gis.geos import MultiPoint
from django.contrib.gis.db.models.functions import Distance
from django_geopostcodes.models import Locality
qs = Locality.objects.anything_icontains('New York')
points = [locality.point for locality in qs]
multipoint = MultiPoint(*points)
point = multipoint.centroid
point
is a Django Point
instance that can then be used to do things such as retrieve all objects that are within 10km of that centre point;
Locality.objects.filter(point__distance_lte=(point, D(km=10)))\
.annotate(distance=Distance('point', point))\
.order_by('distance')
Changing this to raw Python is trivial;
from django.contrib.gis.geos import Point, MultiPoint
points = [
Point((145.137075, -37.639981)),
Point((144.137075, -39.639981)),
]
multipoint = MultiPoint(*points)
point = multipoint.centroid
Under the hood Django is using GEOS - more details at https://docs.djangoproject.com/en/1.10/ref/contrib/gis/geos/
Andy Hume pretty much gave the answer, I just want to add a few more details.
With this construct you are creating an anonymous function with its own evaluation environment or closure, and then you immediately evaluate it. The nice thing about this is that you can access the variables declared before the anonymous function, and you can use local variables inside this function without accidentally overwriting an existing variable.
The use of the var keyword is very important, because in JavaScript every variable is global by default, but with the keyword you create a new, lexically scoped variable, that is, it is visible by the code between the two braces. In your example, you are essentially creating short aliases to the objects in the YUI library, but it has more powerful uses.
I don't want to leave you without a code example, so I'll put here a simple example to illustrate a closure:
var add_gen = function(n) {
return function(x) {
return n + x;
};
};
var add2 = add_gen(2);
add2(3); // result is 5
What is going on here? In the function add_gen you are creating an another function which will simply add the number n to its argument. The trick is that in the variables defined in the function parameter list act as lexically scoped variables, like the ones defined with var.
The returned function is defined between the braces of the add_gen function so it will have access to the value of n even after add_gen function has finished executing, that is why you will get 5 when executing the last line of the example.
With the help of function parameters being lexically scoped, you can work around the "problems" arising from using loop variables in anonymous functions. Take a simple example:
for(var i=0; i<5; i++) {
setTimeout(function(){alert(i)}, 10);
}
The "expected" result could be the numbers from zero to four, but you get four instances of fives instead. This happens because the anonymous function in setTimeout and the for loop are using the very same i variable, so by the time the functions get evaluated, i will be 5.
You can get the naively expected result by using the technique in your question and the fact, that function parameters are lexically scoped. (I've used this approach in an other answer)
for(var i=0; i<5; i++) {
setTimeout(
(function(j) {
return function(){alert(j)};
})(i), 10);
}
With the immediate evaluation of the outer function you are creating a completely independent variable named j in each iteration, and the current value of i will be copied in to this variable, so you will get the result what was naively expected from the first try.
I suggest you to try to understand the excellent tutorial at http://ejohn.org/apps/learn/ to understand closures better, that is where I learnt very-very much.
Since the id
is sufficient for detecting duplicates, and the id
is hashable: run 'em through a dictionary that has the id
as the key. The value for each key is the original dictionary.
deduped_dicts = dict((item["id"], item) for item in list_of_dicts).values()
In Python 3, values()
doesn't return a list; you'll need to wrap the whole right-hand-side of that expression in list()
, and you can write the meat of the expression more economically as a dict comprehension:
deduped_dicts = list({item["id"]: item for item in list_of_dicts}.values())
Note that the result likely will not be in the same order as the original. If that's a requirement, you could use a Collections.OrderedDict
instead of a dict
.
As an aside, it may make a good deal of sense to just keep the data in a dictionary that uses the id
as key to begin with.
It is same as above answers, but is simple in steps
c:\SRC\folder1
c:\SRC\folder2
c:\SRC\folder3
c:\SRC\folder4
to copy all above folders to c:\DST\ except folder1 and folder2.
Step1: create a file c:\list.txt with below content, one folder name per one line
folder1\
folder2\
Step2: Go to command pompt and run as below xcopy c:\SRC*.* c:\DST*.* /EXCLUDE:c:\list.txt
A lazy way to do this is with the UTF-8 entity code for a half circle \25E0
(aka ◠
), which looks like ? and then keyframe animate it. It's a simple as:
.busy
{
animation: spin 1s infinite linear;
display:inline-block;
font-weight: bold;
font-family: sans-serif;
font-size: 35px;
font-style:normal;
color:#555;
}
.busy::before
{
content:"\25E0";
}
@keyframes spin
{
0% {transform: rotate(0deg);}
100% {transform: rotate(359deg);}
}
_x000D_
<i class="busy"></i>
_x000D_
Yes. Internally it is implemented as open hashing based on a primitive polynomial over Z/2 (source).
Assuming you actually mean timestamp
because there is no datetime
in Postgres
Cast the timestamp column to a date, that will remove the time part:
select *
from the_table
where the_timestamp_column::date = date '2015-07-15';
This will return all rows from July, 15th.
Note that the above will not use an index on the_timestamp_column
. If performance is critical, you need to either create an index on that expression or use a range condition:
select *
from the_table
where the_timestamp_column >= timestamp '2015-07-15 00:00:00'
and the_timestamp_column < timestamp '2015-07-16 00:00:00';
I am taking an example of date given below and print two different format of dates according to your requirements.
String date="01/10/2014 05:54:00 PM";
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("dd/MM/yyyy hh:mm:ss aa",Locale.getDefault());
try {
Log.i("",""+new SimpleDateFormat("ddMMyyyyHHmmss",Locale.getDefault()).format(simpleDateFormat.parse(date)));
Log.i("",""+new SimpleDateFormat("dd/MM/yyyy HH:mm:ss",Locale.getDefault()).format(simpleDateFormat.parse(date)));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
If you still have any query, Please respond. Thanks.
Convert String to Data
extension String {
func toData() -> Data {
return Data(self.utf8)
}
}
Convert Data to String
extension Data {
func toString() -> String {
return String(decoding: self, as: UTF8.self)
}
}
Depending on what you need each child for (if you're looking to post it somewhere via AJAX) you can just do...
$("#formID").serialize()
It creates a string for you with all of the values automatically.
As for looping through objects, you can also do this.
$.each($("input, select, textarea"), function(i,v) {
var theTag = v.tagName;
var theElement = $(v);
var theValue = theElement.val();
});
Use ctags. Generate a tags file, and tell vim where it is using the :tags command. Then you can just jump to the function definition using Ctrl-]
There are more tags tricks and tips in this question.
I have written a batch file CompileCS.cmd
which allows to compile (and optionally run) a C# file, you can find the complete answer including the batch program 'CompileCS' here.
Its usage is simple:
CompileCS /run GetDotNetVersion.cs
[arg1] ... [arg9]
will compile and run GetDotNetVersion.cs - if you just want to compile it, omit the /run
parameter.
The console application GetDotNetVersion.cs
is taken from this answer.
inside the Form, You can use this code. Replace your variable name (i use $variable)
<input type="text" value="<?php echo (isset($variable))?$variable:'';?>">
Colin is correct that a profile should be used. However, his answer hard-codes the target directory in the profile. An alternate solution would be to add a profile like this:
<profile>
<id>alternateBuildDir</id>
<activation>
<property>
<name>alt.build.dir</name>
</property>
</activation>
<build>
<directory>${alt.build.dir}</directory>
</build>
</profile>
Doing so would have the effect of changing the build directory to whatever is given by the alt.build.dir property, which can be given in a POM, in the user's settings, or on the command line. If the property is not present, the compilation will happen in the normal target directory.
table tr td:nth-child(2) {
background: #ccc;
}
Working example: http://jsfiddle.net/gqr3J/
You can use the LocalForward
directive in your host yam
section of ~/.ssh/config
:
LocalForward 5901 computer.myHost.edu:5901
I believe this would be the simplest solution:
<configuration>
<contextName>selenium-plugin</contextName>
<!-- Logging configuration -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<Target>System.out</Target>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>INFO</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<encoder>
<pattern>[%d{yyyy-MM-dd HH:mm:ss.SSS}] [%level] %msg%n</pattern>
</encoder>
</appender>
<appender name="STDERR" class="ch.qos.logback.core.ConsoleAppender">
<Target>System.err</Target>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<encoder>
<pattern>[%d{yyyy-MM-dd HH:mm:ss.SSS}] [%level] [%thread] %logger{10} [%file:%line] %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT"/>
<appender-ref ref="STDERR" />
</root>
</configuration>
Given a list of dates dates
:
Max date is max(dates)
Min date is min(dates)
CATALINA_BASE is optional.
However, in the following scenarios it helps to setup CATALINA_BASE that is separate from CATALINA_HOME.
When more than 1 instances of tomcat are running on same host
Separation of concern (Single responsibility)
They are simply showed like this:
_______________________
| <<enumeration>> |
| DaysOfTheWeek |
|_____________________|
| Sunday |
| Monday |
| Tuesday |
| ... |
|_____________________|
And then just have an association between that and your class.
Quoting part of @Jatin answer with some modifications,
use this in your where
statement:
SELECT * FROM .... etc.
Where
REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE (Name, '0', ''),
'1', ''),
'2', ''),
'3', ''),
'4', ''),
'5', ''),
'6', ''),
'7', ''),
'8', ''),
'9', '') = P_SEARCH_KEY
For those that comfortable with Python, https://github.com/Russell91/pythonpy is a nice choice to solve this problem.
$ echo "a:b:c:d:e" | py -x 'x.split(":")[-1]'
From the pythonpy help: -x treat each row of stdin as x
.
With that tool, it is easy to write python code that gets applied to the input.
Edit (Dec 2020): Pythonpy is no longer online. Here is an alternative:
$ echo "a:b:c:d:e" | python -c 'import sys; sys.stdout.write(sys.stdin.read().split(":")[-1])'
it contains more boilerplate code (i.e. sys.stdout.read/write
) but requires only std libraries from python.
myTest.js
module.exports.get = function () {};
exports.put = function () {};
console.log(module.exports)
// output: { get: [Function], put: [Function] }
exports
and module.exports
are the same and a reference to the same object. You can add properties by both ways as per your convenience.
You could do:
brew reinstall php55-imagick
Where php55 is your PHP version.
If it happens that you don't need this htm characte  
shile using str.replace(/(\r\n|\n|\r)/gm, "")
you can use this str.split('\n').join('');
cheers
def n_arr(n, default=0, size=1):
if n is 0:
return default
return [n_arr(n-1, default, size) for _ in range(size)]
arr = n_arr(3, 42, 3)
assert arr[2][2][2], 42
You could also use PyAutoGui to send a virtual key presses.
Here's the documentation: https://pyautogui.readthedocs.org/en/latest/
import pyautogui
pyautogui.press('Any key combination')
You can also send keys like the shift key or enter key with:
import pyautogui
pyautogui.press('shift')
Pyautogui can also send straight text like so:
import pyautogui
pyautogui.typewrite('any text you want to type')
As for pressing the "A" key 1000 times, it would look something like this:
import pyautogui
for i in range(999):
pyautogui.press("a")
alt-tab or other tasks that require more than one key to be pressed at the same time:
import pyautogui
# Holds down the alt key
pyautogui.keyDown("alt")
# Presses the tab key once
pyautogui.press("tab")
# Lets go of the alt key
pyautogui.keyUp("alt")
Depending on the database engine you are using, there can be limits on the length of an instruction.
SQL Server has a very large limit:
http://msdn.microsoft.com/en-us/library/ms143432.aspx
ORACLE has a very easy to reach limit on the other side.
So, for large IN clauses, it's better to create a temp table, insert the values and do a JOIN. It works faster also.
You can reference Microsoft.VisualBasic.dll
.
Then using the code below.
Microsoft.VisualBasic.Interaction.InputBox("Question?","Title","Default Text");
Alternatively, by adding a using
directive allowing for a shorter syntax in your code (which I'd personally prefer).
using Microsoft.VisualBasic;
...
Interaction.InputBox("Question?","Title","Default Text");
Or you can do what Pranay Rana suggests, that's what I would've done too...
You can try using the following code to solve your problem:
<activity
android:name=".DonateNow"
android:label="@string/title_activity_donate_now"
android:screenOrientation="portrait"
android:theme="@style/AppTheme"
android:windowSoftInputMode="stateVisible|adjustPan">
</activity>
Also you can use .prop() and it should be better because
Since jQuery 1.6, these properties can no longer be set with the .attr() method. They do not have corresponding attributes and are only properties.
$(elem).prop('width', '100%');
$(elem).prop('height', '100%');
function parseMinutes(x) {
hours = Math.floor(x / 60);
minutes = x % 60;
}
function parseHours(H, M) {
x = M + H * 60;
}
In Visual Studio Code open 'user settings': ctrl + p
and type >sett
press enter
This will open default settings on left side and User settings on right side.
Just add path to git.exe in user settings
"git.path": "C:\\Users\\[WINDOWS_USER]\\AppData\\Local\\Programs\\Git\\bin\\git.exe"
Replace [WINDOWS_USER] with your user name.
Restart Visual Studio Code
Just for those that are trying to do this on Jira
. Just add \\
at the end of each line and a new line will be created:
|Something|Something else \\ that's rather long|Something else|
Will render this:
Source: Text breaks on Jira
here's what six is:
pip search six
six - Python 2 and 3 compatibility utilities
to install:
pip install six
though if you did install python-dateutil
from pip six should have been set as a dependency.
N.B.: to install pip run easy_install pip
from command line.
You need to include inttypes.h
if you want all those nifty new format specifiers for the intN_t
types and their brethren, and that is the correct (ie, portable) way to do it, provided your compiler complies with C99. You shouldn't use the standard ones like %d
or %u
in case the sizes are different to what you think.
It includes stdint.h
and extends it with quite a few other things, such as the macros that can be used for the printf/scanf
family of calls. This is covered in section 7.8 of the ISO C99 standard.
For example, the following program:
#include <stdio.h>
#include <inttypes.h>
int main (void) {
uint32_t a=1234;
uint16_t b=5678;
printf("%" PRIu32 "\n",a);
printf("%" PRIu16 "\n",b);
return 0;
}
outputs:
1234
5678
xxdiff is lightweight if that's what you're after.
Session storage cannot support an arbitrary object because it may contain function literals (read closures) which cannot be reconstructed after a page reload.
Just to complement Mr @potatosalad answer.
You don't actually need to access the function scope to get the result on the onload callback, you can freely do the following on the event parameter:
var arrayBuffer;
var fileReader = new FileReader();
fileReader.onload = function(event) {
arrayBuffer = event.target.result;
};
fileReader.readAsArrayBuffer(blob);
Why this is better? Because then we may use arrow function without losing the context
var fileReader = new FileReader();
fileReader.onload = (event) => {
this.externalScopeVariable = event.target.result;
};
fileReader.readAsArrayBuffer(blob);
All the answers so far are mathematically wrong. Returning rand() % N
does not uniformly give a number in the range [0, N)
unless N
divides the length of the interval into which rand()
returns (i.e. is a power of 2). Furthermore, one has no idea whether the moduli of rand()
are independent: it's possible that they go 0, 1, 2, ...
, which is uniform but not very random. The only assumption it seems reasonable to make is that rand()
puts out a Poisson distribution: any two nonoverlapping subintervals of the same size are equally likely and independent. For a finite set of values, this implies a uniform distribution and also ensures that the values of rand()
are nicely scattered.
This means that the only correct way of changing the range of rand()
is to divide it into boxes; for example, if RAND_MAX == 11
and you want a range of 1..6
, you should assign {0,1}
to 1, {2,3}
to 2, and so on. These are disjoint, equally-sized intervals and thus are uniformly and independently distributed.
The suggestion to use floating-point division is mathematically plausible but suffers from rounding issues in principle. Perhaps double
is high-enough precision to make it work; perhaps not. I don't know and I don't want to have to figure it out; in any case, the answer is system-dependent.
The correct way is to use integer arithmetic. That is, you want something like the following:
#include <stdlib.h> // For random(), RAND_MAX
// Assumes 0 <= max <= RAND_MAX
// Returns in the closed interval [0, max]
long random_at_most(long max) {
unsigned long
// max <= RAND_MAX < ULONG_MAX, so this is okay.
num_bins = (unsigned long) max + 1,
num_rand = (unsigned long) RAND_MAX + 1,
bin_size = num_rand / num_bins,
defect = num_rand % num_bins;
long x;
do {
x = random();
}
// This is carefully written not to overflow
while (num_rand - defect <= (unsigned long)x);
// Truncated division is intentional
return x/bin_size;
}
The loop is necessary to get a perfectly uniform distribution. For example, if you are given random numbers from 0 to 2 and you want only ones from 0 to 1, you just keep pulling until you don't get a 2; it's not hard to check that this gives 0 or 1 with equal probability. This method is also described in the link that nos gave in their answer, though coded differently. I'm using random()
rather than rand()
as it has a better distribution (as noted by the man page for rand()
).
If you want to get random values outside the default range [0, RAND_MAX]
, then you have to do something tricky. Perhaps the most expedient is to define a function random_extended()
that pulls n
bits (using random_at_most()
) and returns in [0, 2**n)
, and then apply random_at_most()
with random_extended()
in place of random()
(and 2**n - 1
in place of RAND_MAX
) to pull a random value less than 2**n
, assuming you have a numerical type that can hold such a value. Finally, of course, you can get values in [min, max]
using min + random_at_most(max - min)
, including negative values.
I mostly use following code to scroll down
$('html, body').animate({ scrollTop: $(SELECTOR).offset().top - 50 }, 'slow');
I've been thinking over this and experimenting with height of the elements: html, body and div. Finally I came up with the code:
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8" />_x000D_
<title>Height question</title>_x000D_
<style>_x000D_
html {height: 50%; border: solid red 3px; }_x000D_
body {height: 70vh; border: solid green 3px; padding: 12pt; }_x000D_
div {height: 90vh; border: solid blue 3px; padding: 24pt; }_x000D_
_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div id="container">_x000D_
<p><html> is red</p>_x000D_
<p><body> is green</p>_x000D_
<p><div> is blue</p>_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
With my browser (Firefox 65@mint 64), all three elements are of 1) different height, 2) every one is longer, than the previous (html is 50%, body is 70vh, and div 90vh). I also checked the styles without the height with respect to the html and body tags. Worked fine, too.
About CSS units: w3schools: CSS units
A note about the viewport: " Viewport = the browser window size. If the viewport is 50cm wide, 1vw = 0.5cm."
If you're using Windows it will not let you create a file without a filename in Windows Explorer. It will give you the error "You must type a file name" if you try to rename a text file as .gitignore
To get around this I used the following steps
ren gitignore.txt .gitignore
Alternatively @HenningCash suggests in the comments
You can get around this Windows Explorer error by appending a dot to the filename without extension: .gitignore. will be automatically changed to .gitignore
I found the problem and am post hete if anyone followed some blog post out there to create the sort of enviromment I have (win 7 host with ubuntu and zend server ce on virtual box).
The thing is that MySQL is running on Lighttpd, not under Apache. So I had to change the php.ini file under that webserver as well which is in the path:
/usr/local/zend/gui/lighttpd/etc/php-fcgi.ini
In the end, you were right about the files, of course, but I was wrong on what file I had to change :)
I met the same problems and has solved.
Due to my situation, I guess your build.gradle
file for app project contains snippets below:
android {
...
buildTypes {
debug {...}
release {...}
dexOptions {...}
}
}
but actually, dexOptions
is not a build type, you should move dexOptions
section out buildTypes
, like this:
android {
...
dexOptions {
...
}
buildTypes {
debug {...}
release {...}
}
}
Hope that can help someone.
The -B
switch to make, whose long form is --always-make
, tells make
to disregard timestamps and make the specified targets. This may defeat the purpose of using make, but it may be what you need.
Set a system variable named http_proxy
with the value of ProxyServer:Port
.
That is the simplest solution. Respectively, use https_proxy
as daefu pointed out in the comments.
Setting gitproxy (as sleske mentions) is another option, but that requires a "command", which is not as straightforward as the above solution.
References: http://bardofschool.blogspot.com/2008/11/use-git-behind-proxy.html
String currentDateandTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
Toast.makeText(getApplicationContext(), currentDateandTime, Toast.LENGTH_SHORT).show();
If you need the full url (for instance to send by email) consider using one of the following built-in methods:
With this you create the route to use to build the url:
Url.RouteUrl("OpinionByCompany", new RouteValueDictionary(new{cid=newop.CompanyID,oid=newop.ID}), HttpContext.Request.Url.Scheme, HttpContext.Request.Url.Authority)
Here the url is built after the route engine determine the correct one:
Url.Action("Detail","Opinion",new RouteValueDictionary(new{cid=newop.CompanyID,oid=newop.ID}),HttpContext.Request.Url.Scheme, HttpContext.Request.Url.Authority)
In both methods, the last 2 parameters specifies the protocol and hostname.
Regards.
This was pretty well answered over here: How to make a YouTube embedded video a full page width one?
If you add '?rel=0&autoplay=1' to the end of the url in the embed code (like this)
<iframe id="video" src="//www.youtube.com/embed/5iiPC-VGFLU?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>
of the video it should play on load. Here's a demo over at jsfiddle.
You cannot. Facebook API has read_mailbox but no write_mailbox extended permission. I'm guessing this is done to prevent spammy apps from flooding friend's inboxes.
You first have to 'dot' source the script, so for you :
. .\Get-NetworkStatistics.ps1
The first 'dot' asks PowerShell to load the script file into your PowerShell environment, not to start it. You should also use set-ExecutionPolicy Unrestricted
or set-ExecutionPolicy AllSigned
see(the Execution Policy instructions).
You need to run pip install in the command prompt, outside from a python interpreter ! Try to exit python and re try :)
It also happens when you have not give enough permissions(read and write) to your sock file!
Just add expected permission to your sock contained folder and your sock file:
chmod ug+rw /path/to/your/
chmod ug+rw /path/to/your/file.sock
Then have fun!
In newer versions of Git for Windows, Bash is started with --login
which causes Bash to not read .bashrc
directly. Instead it reads .bash_profile
.
If this file does not exist, create it with the following content:
if [ -f ~/.bashrc ]; then . ~/.bashrc; fi
This will cause Bash to read the .bashrc
file. From my understanding of this issue, Git for Windows should do this automatically. However, I just installed version 2.5.1, and it did not.
This particular question gave me a lot of trouble then i found a very simple solution for this problem which i'm posting here.
file.getName().toLowerCase().endsWith(".txt");
That's it.
shopt -s nocasematch
if [[ sed-4.2.2.$LINE =~ (yes|y)$ ]]
then exit 0
fi
Define a helper function like this
function checkWhitespace(inputString){
let stringArray = inputString.split(' ');
let output = true;
for (let el of stringArray){
if (el!=''){
output=false;
}
}
return output;
}
Then check your input field value by passing through as an argument. If function returns true, that means value is only white space.
As an example
let inputValue = $('#firstName').val();
if(checkWhitespace(inputValue)) {
// Show Warnings or return warnings
}else {
// // Block of code-probably store input value into database
}
[Range(0.01,100000000,ErrorMessage = "Price must be greter than zero !")]
Another solution:
(function () {
var make_rotated_text = function (text)
{
var can = document.createElement ('canvas');
can.width = 10;
can.height = 10;
var ctx=can.getContext ("2d");
ctx.font="20px Verdana";
var m = ctx.measureText(text);
can.width = 20;
can.height = m.width;
ctx.font="20px Verdana";
ctx.fillStyle = "#000000";
ctx.rotate(90 * (Math.PI / 180));
ctx.fillText (text, 0, -2);
return can;
};
var canvas = make_rotated_text ("Hellooooo :D");
var body = document.getElementsByTagName ('body')[0];
body.appendChild (canvas);
}) ();
I do absolutely admit that this is quite hackish, but it's a simple solution if you want to avoid bloating your css.
There can be a problem with "\00a0" in pseudo-elements because it takes the text-decoration of its defining element, so that, for example, if the defining element is underlined, then the white space of the pseudo-element is also underlined.
The easiest way to deal with this is to define the opacity of the pseudo-element to be zero, eg:
element:before{
content: "_";
opacity: 0;
}
If you paste the string in server-side into the html don't need to do nothing:
For plain java in jsp:
var jsonObj=<%=jsonStringInJavaServlet%>;
For jsp width struts:
var jsonObj=<s:property value="jsonStringInJavaServlet" escape="false" escapeHtml="false"/>;
you can use the collector like this
Stream<String> io = Stream.of("foo" , "lan" , "mql");
io.collect(Collectors.toCollection(ArrayList<String>::new));
Here is the solution I found: On the project tree "app", right click mouse button to get the context menu. Select "open module setting", on the tree "app" - "properties" tab, select the existing "build tools version" you have. The gradle will start to build.
Here is a small snippet to demonstrate the date modifications:
$date = date("Y-m-d");
//increment 2 days
$mod_date = strtotime($date."+ 2 days");
echo date("Y-m-d",$mod_date) . "\n";
//decrement 2 days
$mod_date = strtotime($date."- 2 days");
echo date("Y-m-d",$mod_date) . "\n";
//increment 1 month
$mod_date = strtotime($date."+ 1 months");
echo date("Y-m-d",$mod_date) . "\n";
//increment 1 year
$mod_date = strtotime($date."+ 1 years");
echo date("Y-m-d",$mod_date) . "\n";
You're comparing the message with the empty string using ==
.
First, your comparison is wrong because the message will be null (and not the empty string).
Second, it's wrong because Objects must be compared with equals()
and not with ==
.
Third, it's wrong because you should avoid scriptlets in JSP, and use the JSP EL, the JSTL, and other custom tags instead:
<c:id test="${!empty message}">
<c:out value="${message}"/>
</c:if>
Yes, it is possible to write and call a function nested in another function.
Try this:
function A(){
B(); //call should be B();
function B(){
}
}
If you are using androidx AppCompact. Use below code.
androidx.appcompat.app.ActionBar actionBar = getSupportActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable("Color"));
To convert your JSON string to hashmap you can make use of this :
HashMap<String, Object> hashMap = new HashMap<>(Utility.jsonToMap(response)) ;
Use this class :) (handles even lists , nested lists and json)
public class Utility {
public static Map<String, Object> jsonToMap(Object json) throws JSONException {
if(json instanceof JSONObject)
return _jsonToMap_((JSONObject)json) ;
else if (json instanceof String)
{
JSONObject jsonObject = new JSONObject((String)json) ;
return _jsonToMap_(jsonObject) ;
}
return null ;
}
private static Map<String, Object> _jsonToMap_(JSONObject json) throws JSONException {
Map<String, Object> retMap = new HashMap<String, Object>();
if(json != JSONObject.NULL) {
retMap = toMap(json);
}
return retMap;
}
private static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keysItr = object.keys();
while(keysItr.hasNext()) {
String key = keysItr.next();
Object value = object.get(key);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
map.put(key, value);
}
return map;
}
public static List<Object> toList(JSONArray array) throws JSONException {
List<Object> list = new ArrayList<Object>();
for(int i = 0; i < array.length(); i++) {
Object value = array.get(i);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
list.add(value);
}
return list;
}
}
if the database is maintained by you then simply create a new database and import the data from the old one. the collation problem is solved!!!!!
Collapsing is now supported in release 1.0:
Source Code Folding Shortcuts
There are new folding actions to collapse source code regions based on their folding level.
There are actions to fold level 1 (Ctrl+K Ctrl+1) to level 5 (Ctrl+K Ctrl+5). To unfold, use Unfold All (Ctrl+Shift+Alt+]).
The level folding actions do not apply to region containing the current cursor.
I had a problem finding the ]
button on my keyboard (Norwegian layout), and in my case it was the Å
button. (Or two buttons left and one down starting from the backspace button.)
This project on github may be your solution
It took me some hours to get this working. The code it's almost a copy-paste from developer.android.com, with a minor difference.
Request this permission on the AndroidManifest.xml
:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
On your Activity
, start by defining this:
static final int REQUEST_IMAGE_CAPTURE = 1;
private Bitmap mImageBitmap;
private String mCurrentPhotoPath;
private ImageView mImageView;
Then fire this Intent
in an onClick
:
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Log.i(TAG, "IOException");
}
// Continue only if the File was successfully created
if (photoFile != null) {
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
}
}
Add the following support method:
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, // prefix
".jpg", // suffix
storageDir // directory
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
Then receive the result:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
try {
mImageBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath));
mImageView.setImageBitmap(mImageBitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
What made it work is the MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath))
, which is different from the code from developer.android.com. The original code gave me a FileNotFoundException
.
For me it turned out that I had a @JsonManagedReferece
in one entity without a @JsonBackReference
in the other referenced entity. This caused the marshaller to throw an error.
From java specification :
The floating-point types are float and double, which are conceptually associated with the single-precision 32-bit and double-precision 64-bit format IEEE 754 values and operations as specified in IEEE Standard for Binary Floating-Point Arithmetic, ANSI/IEEE Standard 754-1985 (IEEE, New York).
As it's hard to do anything with numbers without understanding IEEE754 basics, here's another link.
It's important to understand that the precision isn't uniform and that this isn't an exact storage of the numbers as is done for integers.
An example :
double a = 0.3 - 0.1;
System.out.println(a);
prints
0.19999999999999998
If you need arbitrary precision (for example for financial purposes) you may need Big Decimal.
Here is very simple javascript. It works fine for me :
// JavaScript:
function sFocus (field) {
if(field.value == 'Enter your search') {
field.value = '';
}
field.className = "darkinput";
}
function sBlur (field) {
if (field.value == '') {
field.value = 'Enter your search';
field.className = "lightinput";
}
else {
field.className = "darkinput";
}
}
// HTML
<form>
<label class="screen-reader-text" for="s">Search for</label>
<input
type="text"
class="lightinput"
onfocus="sFocus(this)"
onblur="sBlur(this)"
value="Enter your search" name="s" id="s"
/>
</form>
You can add a class declaration to the submit button of a form by doing the following:
<%= f.submit class: 'btn btn-default' %>
<-- Note: there is no comma!
If you are altering a _form.html.erb partial of a scaffold and you want to keep
the dynamic change of the button name between controller actions, DO NOT specify a name 'name'
.
Without specifying a name and depending on the action the form is rendered the button will get the .class = "btn btn-default"
(Bootstrap class)(or whatever .class
you specify) with the following names:
Update model_name
Create model_name
(where model_name the name of the scaffold's model)
All of these answers are turned off the logging at creation time.
But what if we need to turn off the logging on runtime ?
By runtime i mean after initializing the sequelize
object using new Sequelize(..
function.
I peeked into the github source, found a way to turn off logging in runtime.
// Somewhere your code, turn off the logging
sequelize.options.logging = false
// Somewhere your code, turn on the logging
sequelize.options.logging = true
We have experienced the same issue when moving the sql server in-house.
A good solution that we ended up using is splitting the sql file into chunks. There are several ways to do that. Use
http://www.ozerov.de/bigdump/ seems good (but never used it)
http://www.rusiczki.net/2007/01/24/sql-dump-file-splitter/ used it and it was very useful to get structure out of the mess and you can take it from there.
Hope this helps :)
Embed is not a standard tag, though object is. Here's an article that looks like it will help you, since it seems the situation is not so simple. An example for PDF is included.
var example = $('#exampleTable').DataTable({
"columnDefs": [
{
"targets": [0],
"visible": false,
"searchable": false
}
]
});
Target attribute defines the position of the column.Visible attribute responsible for visibility of the column.Searchable attribute responsible for searching facility.If it set to false that column doesn't function with searching.
I think Nokogiri gem is also a good choice. It is very stable and has a huge contributing community.
Samples:
a = Nokogiri::HTML.parse "foo bär"
a.text
=> "foo bär"
or
a = Nokogiri::HTML.parse "¡I'm highly annoyed with character references!"
a.text
=> "¡I'm highly annoyed with character references!"
You need ImageMagick
and GhostScript
<?php
$im = new imagick('file.pdf[0]');
$im->setImageFormat('jpg');
header('Content-Type: image/jpeg');
echo $im;
?>
The [0]
means page 1
.
Just install libpq-dev
$ sudo apt-get install libpq-dev
Get the field value through the id and send with ajax
var field = $("#field").val();
$.ajax({
type: "POST",
url: "db.php",
data: {variable_name:field},
async:false,
dataType:"json",
success: function(response) {
alert(response);
}
});
At db.php file get the variable name
$variable_name = $_GET['variable_name'];
mysql_query("SELECT password FROM table_name WHERE password='".md5($variable_name)."'");
var new_row = document.createElement('div');
new_row.setAttribute("class", "YOUR_CLASS");
This will work ;-)
for a complete offline android studio 3.5.0 installation - you need to download all these below components
android studio, gradle, android gradle plugin and sdk.
here is a detailed step by step Stackoverflow answer for the question
Another way to do this problem besides using ASCII conversions is the following:
String input = "abc".toLowerCase();
final static String alphabet = "abcdefghijklmnopqrstuvwxyz";
for(int i=0; i < input.length(); i++){
System.out.print(alphabet.indexOf(input.charAt(i))+1);
}
Another way that does the trick by using import/export wizard, first create an empty database, then choose the source which is your server with the source database, and then in the destination choose the same server with the destination database (using the empty database you created at first), then hit finish
It will create all tables and transfer all the data into the new database,
I was faced with this same problem today but since our daylight saving starts and stops at differing times from the USA (at least from my understanding), I used a slightly different route..
var arr = [];
for (var i = 0; i < 365; i++) {
var d = new Date();
d.setDate(i);
newoffset = d.getTimezoneOffset();
arr.push(newoffset);
}
DST = Math.min.apply(null, arr);
nonDST = Math.max.apply(null, arr);
Then you simply compare the current timezone offset with DST and nonDST to see which one matches.
If you can edit the class containing that object, I usually just add the annotation
import com.fasterxml.jackson.annotation.JsonIgnore;
@JsonIgnore
NonSerializeableClass obj;
Your stored procedure is designed to accept a single parameter, Arg1List. You can't pass 4 parameters to a procedure that only accepts one.
To make it work, the code that calls your procedure will need to concatenate your parameters into a single string of no more than 3000 characters and pass it in as a single parameter.
If you want to save your numpy array (e.g. your_array = np.array([[1,2],[3,4]])
) to one cell, you could convert it first with your_array.tolist()
.
Then save it the normal way to one cell, with delimiter=';'
and the cell in the csv-file will look like this [[1, 2], [2, 4]]
Then you could restore your array like this:
your_array = np.array(ast.literal_eval(cell_string))
There are three ways to add your filter,
@Component
@Bean
with Filter
type in Spring @Configuration
@Bean
with FilterRegistrationBean
type in Spring @Configuration
Either #1 or #2 will do if you want your filter applies to all requests without customization, use #3 otherwise. You don't need to specify component scan for #1 to work as long as you place your filter class in the same or sub-package of your SpringApplication
class. For #3, use along with #2 is only necessary when you want Spring to manage your filter class such as have it auto wired dependencies. It works just fine for me to new my filter which doesn't need any dependency autowiring/injection.
Although combining #2 and #3 works fine, I was surprised it doesn't end up with two filters applying twice. My guess is that Spring combines the two beans as one when it calls the same method to create both of them. In case you want to use #3 alone with authowiring, you can AutowireCapableBeanFactory
. The following is an example,
private @Autowired AutowireCapableBeanFactory beanFactory;
@Bean
public FilterRegistrationBean myFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
Filter myFilter = new MyFilter();
beanFactory.autowireBean(myFilter);
registration.setFilter(myFilter);
registration.addUrlPatterns("/myfilterpath/*");
return registration;
}
select translate(description,'\\t','') from myTable;
Translates the input string by replacing the characters present in the from string with the corresponding characters in the to string. This is similar to the translate function in PostgreSQL. If any of the parameters to this UDF are NULL, the result is NULL as well. (Available as of Hive 0.10.0, for string types)
Char/varchar support added as of Hive 0.14.0
You didn't do what you're being asked to do.
What is asked:
I have to execute ../gradlew build
What you do
cd ..
gradlew build
That's not the same thing.
The first one will use the gradlew command found in the ..
directory (mdeinum...
), and look for the build file to execute in the current directory, which is (for example) chapter1-bookstore
.
The second one will execute the gradlew command found in the current directory (mdeinum...
), and look for the build file to execute in the current directory, which is mdeinum...
.
So the build file executed is not the same.
Assuming that you have a form that is huge or simply you do not want to reset each form field one by one, you can reset all the fields of the form by iterating through the fields one by one
var self = this;
Object.keys(this.data.form).forEach(function(key,index) {
self.data.form[key] = '';
});
The above will reset all fields of the given this.data.form
object to empty string. Let's say there are one or two fields that you selectively want to set to a specific value in that case inside the above block you can easily put a condition based on field name
if(key === "country")
self.data.form[key] = 'Canada';
else
self.data.form[key] = '';
Or if you want to reset the field based on type and you have boolean and other field types in that case
if(typeof self.data.form[key] === "string")
self.data.form[key] = '';
else if (typeof self.data.form[key] === "boolean")
self.data.form[key] = false;
For more type info see here
A basic vuejs
template and script sample would look as follow
<template>
<div>
<form @submit.prevent="onSubmit">
<input type="text" class="input" placeholder="User first name" v-model="data.form.firstName">
<input type="text" class="input" placeholder="User last name" v-model="data.form.lastName">
<input type="text" class="input" placeholder="User phone" v-model="data.form.phone">
<input type="submit" class="button is-info" value="Add">
<input type="button" class="button is-warning" @click="resetForm()" value="Reset Form">
</form>
</div>
</template>
See ow the @submit.prevent="onSubmit"
is used in the form element. That would by default, prevent the form submission and call the onSubmit
function.
Let's assume we have the following for the above
<script>
export default {
data() {
return {
data: {
form: {
firstName: '',
lastName: '',
phone: ''
}
}
}
},
methods: {
onSubmit: function() {
console.log('Make API request.')
this.resetForm(); //clear form automatically after successful request
},
resetForm() {
console.log('Reseting the form')
var self = this; //you need this because *this* will refer to Object.keys below`
//Iterate through each object field, key is name of the object field`
Object.keys(this.data.form).forEach(function(key,index) {
self.data.form[key] = '';
});
}
}
}
</script>
You can call the resetForm
from anywhere and it will reset your form fields.
String newString = originalString.substring(originalString.length()-3);
It is correct that rm –rf .
will remove everything in the current directly including any subdirectories and their content. The single dot (.
) means the current directory. be carefull not to do rm -rf ..
since the double dot (..
) means the previous directory.
This being said, if you are like me and have multiple terminal windows open at the same time, you'd better be safe and use rm -ir .
Lets look at the command arguments to understand why.
First, if you look at the rm
command man page (man rm
under most Unix) you notice that –r
means "remove the contents of directories recursively". So, doing rm -r .
alone would delete everything in the current directory and everything bellow it.
In rm –rf .
the added -f means "ignore nonexistent files, never prompt". That command deletes all the files and directories in the current directory and never prompts you to confirm you really want to do that. -f
is particularly dangerous if you run the command under a privilege user since you could delete the content of any directory without getting a chance to make sure that's really what you want.
On the otherhand, in rm -ri .
the -i
that replaces the -f
means "prompt before any removal". This means you'll get a chance to say "oups! that's not what I want" before rm goes happily delete all your files.
In my early sysadmin days I did an rm -rf /
on a system while logged with full privileges (root). The result was two days passed a restoring the system from backups. That's why I now employ rm -ri
now.
I'd recommend you to create a shortcut to eclipse.exe with the -data
command line option. This way you can create a separate shortcut to each workspace you use, and avoid unnecessary dialogs and mouse clicks.
Windows: Just create an Eclipse shortcut on your desktop, then right-click to open Properties
and under Shortcut
set something like this as Target
: C:\eclipse\eclipse.exe -data C:\Path\to\your\workspace1
. This will launch Eclipse and automatically open workspace1
.
Repeat the steps for all the workspaces you use often.
import org.springframework.core.Ordered;
public class MyFilter implements Filter, Ordered {
@Override
public void init(FilterConfig filterConfig) {
// do something
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
// do something
}
@Override
public void destroy() {
// do something
}
@Override
public int getOrder() {
return -100;
}
}
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan
public class MyAutoConfiguration {
@Bean
public MyFilter myFilter() {
return new MyFilter();
}
}
df.T.iloc[-1]
df.T.tail(1)
pd.Series(df.values[:, -1], name=df.columns[-1])
If you can use an array, do use an array, the length and order of an array are half its worth.
function reducer(obj, fun, temp){
if(typeof fun=== 'function'){
if(temp== undefined) temp= '';
for(var p in obj){
if(obj.hasOwnProperty(p)){
temp= fun(obj[p], temp, p, obj);
}
}
}
return temp;
}
var O={a:{value:1},b:{value:2},c:{value:3}}
reducer(O, function(a, b){return a.value+b;},0);
/* returned value: (Number) 6 */
Try details: use any option..
MessageBox.Show("your message",
"window title",
MessageBoxButtons.OK,
MessageBoxIcon.Warning // for Warning
//MessageBoxIcon.Error // for Error
//MessageBoxIcon.Information // for Information
//MessageBoxIcon.Question // for Question
);
To animate the transition between fragments, or to animate the process of showing or hiding a fragment you use the Fragment Manager
to create a Fragment Transaction
.
Within each Fragment Transaction you can specify in and out animations that will be used for show and hide respectively (or both when replace is used).
The following code shows how you would replace a fragment by sliding out one fragment and sliding the other one in it's place.
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right);
DetailsFragment newFragment = DetailsFragment.newInstance();
ft.replace(R.id.details_fragment_container, newFragment, "detailFragment");
// Start the animated transition.
ft.commit();
To achieve the same thing with hiding or showing a fragment you'd simply call ft.show
or ft.hide
, passing in the Fragment you wish to show or hide respectively.
For reference, the XML animation definitions would use the objectAnimator
tag. An example of slide_in_left might look something like this:
<?xml version="1.0" encoding="utf-8"?>
<set>
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
android:propertyName="x"
android:valueType="floatType"
android:valueFrom="-1280"
android:valueTo="0"
android:duration="500"/>
</set>
there's an interesting way to achive another goal which is to have a strongly type class base on json with a very powerfull tools that i used few days ago for first time to translate tradedoubler json result into classes
Is a simple tool: copy your json source paste and in few second you will have a strongly typed class json oriented . In this manner you will use these classes which is more powerful and simply to use.
Well, it looks like Access can't do aggregates in UPDATE queries. But it can do aggregates in SELECT queries. So create a query with a definition like:
SELECT func_id, min(tax_code) as MinOfTax_Code
FROM Functions
INNER JOIN Tax
ON (Functions.Func_Year = Tax.Tax_Year)
AND (Functions.Func_Pure <= Tax.Tax_ToPrice)
GROUP BY Func_Id
And save it as YourQuery. Now we have to work around another Access restriction. UPDATE queries can't operate on queries, but they can operate on multiple tables. So let's turn the query into a table with a Make Table query:
SELECT YourQuery.*
INTO MinOfTax_Code
FROM YourQuery
This stores the content of the view in a table called MinOfTax_Code. Now you can do an UPDATE query:
UPDATE MinOfTax_Code
INNER JOIN Functions ON MinOfTax_Code.func_id = Functions.Func_ID
SET Functions.Func_TaxRef = [MinOfTax_Code].[MinOfTax_Code]
Doing SQL in Access is a bit of a stretch, I'd look into Sql Server Express Edition for your project!
This solution is working with Android Studio 4.0.1.
Apart from creating a new module as suggested in above solution, you can try this solution.
If you have multiple modules in your application and want to add aar to just one of the module then this solution come handy.
In your root project build.gradle
add
repositories {
mavenCentral()
flatDir {
dirs 'libs'
}
Then in the module where you want to add the .aar file locally. simply add below lines of code.
dependencies {
api fileTree(include: ['*.aar'], dir: 'libs')
implementation files('libs/<yourAarName>.aar')
}
Happy Coding :)
On windows it is easy to interact with your webcam with pygame:
from VideoCapture import Device
cam = Device()
cam.saveSnapshot('image.jpg')
I haven't tried using pygame on linux (all my linux boxen are servers without X), but this link might be helpful http://www.jperla.com/blog/post/capturing-frames-from-a-webcam-on-linux
Typescript: How to define type for a function callback used in a method parameter?
You can declare the callback as 1) function property or 2) method:
interface ParamFnProp {
callback: (a: Animal) => void; // function property
}
interface ParamMethod {
callback(a: Animal): void; // method
}
There is an important typing difference since TS 2.6:
You get stronger ("sound") types in --strict
or --strictFunctionTypes
mode, when a function property is declared. Let's take an example:
const animalCallback = (a: Animal): void => { } // Animal is the base type for Dog
const dogCallback = (d: Dog): void => { }
// function property variant
const param11: ParamFnProp = { callback: dogCallback } // error: not assignable
const param12: ParamFnProp = { callback: animalCallback } // works
// method variant
const param2: ParamMethod = { callback: dogCallback } // now it works again ...
Technically spoken, methods are bivariant and function properties contravariant in their arguments under strictFunctionTypes
. Methods are still checked more permissively (even if not sound) to be a bit more practical in combination with built-in types like Array
.
You can also try this approach save the keys and values in different list and then use dict method
data=['test1', '1', 'test2', '2', 'test3', '3', 'test4', '4']
keys=[]
values=[]
for i,j in enumerate(data):
if i%2==0:
keys.append(j)
else:
values.append(j)
print(dict(zip(keys,values)))
output:
{'test3': '3', 'test1': '1', 'test2': '2', 'test4': '4'}
Alternatively, you could try the following,
resp.setStatus(301);
resp.setHeader("Location", "index.jsp");
resp.setHeader("Connection", "close");
Why not using indexOf
from array like bellow?
if ([foo, bar].indexOf(foobar) !== -1) {
// do something
}
Just plain Javascript, no frameworks or libraries but it will not work on IE < 9.
Note that this problem usually occure for two reasons:
1-Port 80 is busy.
2-Port 443 is busy.
For number one as the others said, you can kill Skype and SQL Serever Reporter from
Windows Task Manager>"Services" Tab>"Services..." Button.
But if it dosen't worked, it's probably because of port 443, so try this one:
If you use VMware, go to
Windows Task Manager>"Services" Tab>"Services..." Button, and find "VMware Workstation Server" service, double click on it and press "Stop" button.
There is no need to stop other VMware's services.
Then again try to run Apache
function sum(){
var x,y,z;
x = Number(document.getElementById("input1").value);
y = Number(document.getElementById("input2").value);
z = x + y;
document.getElementById("result").innerHTML = z ;
}
You can get the comments of a particular method by using the ReflectionMethod class and calling ->getDocComment().
http://www.php.net/manual/en/reflectionclass.getdoccomment.php
For Windows
In case anyone looking for shortcut / batch script - Gist - Download batch file.
@echo off
IF [%1]==[] (GOTO ExitWithPrompt)
set i=1
FOR /F "delims=" %%i IN ('emulator -list-avds') DO (
set /A i=i+1
set em=%%i
if %i% == %1 (
echo Starting %em%
emulator -avd %em%
EXIT /B 0
)
)
GOTO :Exit
:ExitWithPrompt
emulator -list-avds
echo Please enter the emulator number to start
:Exit
EXIT /B 0
Usage
D:\>start-emulator
Nexus_5_API_26
Please enter the emulator number to start
D:\>start-emulator 1
Starting Nexus_5_API_26
HAX is working and emulator runs in fast virt mode.
Use a UIWebView on iOS 5-.
On iOS 6+ you can use UITextView.attributedString
, see https://stackoverflow.com/a/20996085 for how.
There's also an undocumented -[UITextView setContentToHTMLString:]
method. Do not use this if you want to submit to AppStore.
we can directly use this to see all the pythons installed both by current user and the root by the following:
whereis python
It is dramatically more efficient to use IndexedOrderedDict from the indexed
package.
Following Niklas's comment, I have done a benchmark on OrderedDict and IndexedOrderedDict with 1000 entries.
In [1]: from numpy import *
In [2]: from indexed import IndexedOrderedDict
In [3]: id=IndexedOrderedDict(zip(arange(1000),random.random(1000)))
In [4]: timeit id.keys()[56]
1000000 loops, best of 3: 969 ns per loop
In [8]: from collections import OrderedDict
In [9]: od=OrderedDict(zip(arange(1000),random.random(1000)))
In [10]: timeit od.keys()[56]
10000 loops, best of 3: 104 µs per loop
IndexedOrderedDict is ~100 times faster in indexing elements at specific position in this specific case.
string testString = "o1 1232.5467 1232.5467.........";
string secondItem = testString.Split(new char[]{' '}, 3)[1];
Stored procedure support is not yet (as of 7.0.0-beta3) implemented in EF7. You can track the progress of this feature using issue #245.
For now, you can do it the old fashioned way using ADO.NET.
var connection = (SqlConnection)context.Database.AsSqlServer().Connection.DbConnection;
var command = connection.CreateCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "MySproc";
command.Parameters.AddWithValue("@MyParameter", 42);
command.ExecuteNonQuery();
You cannot do this with a fully functional cross browser support.
Try taking a div of 50 pixels suppose and float a desired drop-down icon of your choice at the right of this
Now within that div, add the select tag with a width of 55 pixels maybe (something more than the container's width)
I think you'll get what you want.
In case you do not want any drop icon at the right, just do all the steps except for floating the image at the right. Set outline:0 on focus for the select tag. that's it
I had this problem in a unit test which opened a lot of connections to the DB via a connection pool and then "stopped" the connection pool (ManagedDataSource actually) to release the connections at the end of the each test. I always ran out of connections at some point in the suite of tests.
Added a Thread.sleep(500) in the teardown() of my tests and this resolved the issue. I think that what was happening was that the connection pool stop() releases the active connections in another thread so that if the main thread keeps running tests the cleanup thread(s) got so far behind that the Oracle server ran out of connections. Adding the sleep allows the background threads to release the pooled connections.
This is much less of an issue in the real world because the DB servers are much bigger and there is a healthy mix of operations (not just endless DB connect/disconnect operations).