ActiveRecord::Base.connection
has a quote
method that takes a string value (and optionally the column object). So you can say this:
ActiveRecord::Base.connection.execute(<<-EOQ)
UPDATE foo
SET bar = #{ActiveRecord::Base.connection.quote(baz)}
EOQ
Note if you're in a Rails migration or an ActiveRecord object you can shorten that to:
connection.execute(<<-EOQ)
UPDATE foo
SET bar = #{connection.quote(baz)}
EOQ
UPDATE: As @kolen points out, you should use exec_update
instead. This will handle the quoting for you and also avoid leaking memory. The signature works a bit differently though:
connection.exec_update(<<-EOQ, "SQL", [[nil, baz]])
UPDATE foo
SET bar = $1
EOQ
Here the last param is a array of tuples representing bind parameters. In each tuple, the first entry is the column type and the second is the value. You can give nil
for the column type and Rails will usually do the right thing though.
There are also exec_query
, exec_insert
, and exec_delete
, depending on what you need.
To describe model I use following snippet
Model.columns.collect { |c| "#{c.name} (#{c.type})" }
Again this is if you are looking pretty print to describe you ActiveRecord
without you going trough migrations or hopping that developer before you was nice enough to comment in attributes.
if you want to upgrade only a single column of a table row then you can use as following:
$this->db->set('column_header', $value); //value that used to update column
$this->db->where('column_id', $column_id_value); //which row want to upgrade
$this->db->update('table_name'); //table name
Generates a WHERE field IN (‘item’, ‘item’) SQL query joined with AND if appropriate,
$this->db->where_in()
ex : $this->db->where_in('id', array('1','2','3'));
Generates a WHERE field IN (‘item’, ‘item’) SQL query joined with OR if appropriate
$this->db->or_where_in()
ex : $this->db->where_in('id', array('1','2','3'));
Try This:
$this->db->where('sell_date BETWEEN "'. date('Y-m-d', strtotime($start_date)). '" and "'. date('Y-m-d', strtotime($end_date)).'"');
Hope this will work
If you do not want to use the wildcard (%) you can pass to the optional third argument the option 'none'.
$this->db->like('title', 'match', 'none');
// Produces: WHERE title LIKE 'match'
You should use as_json
method which converts ActiveRecord objects to Ruby Hashes despite its name
tasks_records = TaskStoreStatus.all
tasks_records = tasks_records.as_json
# You can now add new records and return the result as json by calling `to_json`
tasks_records << TaskStoreStatus.last.as_json
tasks_records << { :task_id => 10, :store_name => "Koramanagala", :store_region => "India" }
tasks_records.to_json
You can also convert any ActiveRecord objects to a Hash with serializable_hash
and you can convert any ActiveRecord results to an Array with to_a
, so for your example :
tasks_records = TaskStoreStatus.all
tasks_records.to_a.map(&:serializable_hash)
And if you want an ugly solution for Rails prior to v2.3
JSON.parse(tasks_records.to_json) # please don't do it
I think you should count the results with FOUND_ROWS() and SQL_CALC_FOUND_ROWS. You'll need two queries: select
, group_by
, etc. You'll add a plus select: SQL_CALC_FOUND_ROWS user_id
. After this query run a query: SELECT FOUND_ROWS()
. This will return the desired number.
For readability purposes i use query scope, makes my code more declarative.
namespace App\Models;
use Illuminate\Support\Carbon;
use Illuminate\Database\Eloquent\Model;
class MyModel extends Model
{
// ...
/**
* Scope a query to only include today's entries.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeCreatedToday($query)
{
return $query->where('created_at', '>=', Carbon::today());
}
// ...
}
MyModel::createdToday()->get()
Sql : select * from "my_models" where "created_at" >= ?
Bindings : ["2019-10-22T00:00:00.000000Z"]
delete_all is a single SQL DELETE statement and nothing more. destroy_all calls destroy() on all matching results of :conditions (if you have one) which could be at least NUM_OF_RESULTS SQL statements.
If you have to do something drastic such as destroy_all() on large dataset, I would probably not do it from the app and handle it manually with care. If the dataset is small enough, you wouldn't hurt as much.
I'd go about this slightly differently. Structure your query to retrieve only what you need and split from there.
So make your query the following:
# vv or Job.find(1) vv
attachments = Attachment.where(job_id: @job.id, file_type: ["logo", "image"])
# or
Job.includes(:attachments).where(id: your_job_id, attachments: { file_type: ["logo", "image"] })
And then partition the data:
@logos, @images = attachments.partition { |attachment| attachment.file_type == "logo" }
That will get the data you're after in a neat and efficient manner.
The problem is that date is a reserved sqlite3 keyword. I had a similar problem with time, also a reserved keyword, which worked fine in PostgreSQL, but not in sqlite3. The solution is renaming the column.
See this: Sqlite3 activerecord :order => "time DESC" doesn't sort
You can do:
User.find_or_create_by(first_name: 'Penélope', last_name: 'Lopez')
User.where(first_name: 'Penélope', last_name: 'Lopez').first_or_create
Or to just initialize:
User.find_or_initialize_by(first_name: 'Penélope', last_name: 'Lopez')
User.where(first_name: 'Penélope', last_name: 'Lopez').first_or_initialize
If it is just avoiding the exception you are worried about, the "find_all_by.." family of functions works without throwing exceptions.
Comment.find_all_by_id([2, 3, 5])
will work even if some of the ids don't exist. This works in the
user.comments.find_all_by_id(potentially_nonexistent_ids)
case as well.
Comment.where(id: [2, 3, 5])
@article = user.articles.build(:title => "MainTitle")
@article.save
The magic you have been looking for has been added in Rails 6
Now you can upsert (update or insert).
For single record use:
Model.upsert(column_name: value)
For multiple records use upsert_all :
Model.upsert_all(column_name: value, unique_by: :column_name)
Note:
You would do
Person.where('name=? OR lastname=?', 'John', 'Smith')
Right now, there isn't any other OR support by the new AR3 syntax (that is without using some 3rd party gem).
You can add references to your model through command line in the following manner:
rails g migration add_column_to_tester user_id:integer
This will generate a migration file like :
class AddColumnToTesters < ActiveRecord::Migration
def change
add_column :testers, :user_id, :integer
end
end
This works fine every time i use it..
Model.select(:rating)
The result of this is a collection of Model
objects. Not plain ratings. And from uniq
's point of view, they are completely different. You can use this:
Model.select(:rating).map(&:rating).uniq
or this (most efficient):
Model.uniq.pluck(:rating)
Model.distinct.pluck(:rating)
Apparently, as of rails 5.0.0.1, it works only on "top level" queries, like above. Doesn't work on collection proxies ("has_many" relations, for example).
Address.distinct.pluck(:city) # => ['Moscow']
user.addresses.distinct.pluck(:city) # => ['Moscow', 'Moscow', 'Moscow']
In this case, deduplicate after the query
user.addresses.pluck(:city).uniq # => ['Moscow']
You can change your code to this:
$where_au = "(library.available_until >= '{date('Y-m-d H:i:s)}' OR library.available_until = '00-00-00 00:00:00')";
$this->db
->select('*')
->from('library')
->where('library.rating >=', $form['slider'])
->where('library.votes >=', '1000')
->where('library.language !=', 'German')
->where($where_au)
->where('library.release_year >=', $year_start)
->where('library.release_year <=', $year_end)
->join('rating_repo', 'library.id = rating_repo.id');
Tip: to watch the generated query you can use
echo $this->db->last_query(); die();
$count = DB::table('category_issue')->count();
will give you the number of items.
For more detailed information check Fluent Query Builder section in beautiful Laravel Documentation.
$sql = "SELECT count(id) as value FROM your_table WHERE your_field = ?";
$your_count = $this->db->query($sql, array($your_field))->row(0)->value;
echo $your_count;
The query execution happens on all get methods like
$this->db->get('table_name');
$this->db->get_where('table_name',$array);
While last_query contains the last query which was run
$this->db->last_query();
If you want to get query string without execution you will have to do this. Go to system/database/DB_active_rec.php Remove public or protected keyword from these functions
public function _compile_select($select_override = FALSE)
public function _reset_select()
Now you can write query and get it in a variable
$this->db->select('trans_id');
$this->db->from('myTable');
$this->db->where('code','B');
$subQuery = $this->db->_compile_select();
Now reset query so if you want to write another query the object will be cleared.
$this->db->_reset_select();
And the thing is done. Cheers!!! Note : While using this way you must use
$this->db->from('myTable')
instead of
$this->db->get('myTable')
which runs the query.
A belongs_to
association cannot have a :through
option. You're better off caching the question_id
on Choice
and adding a unique index to the table (especially because validates_uniqueness_of
is prone to race conditions).
If you're paranoid, add a custom validation to Choice
that confirms that the answer's question_id
matches, but it sounds like the end user should never be given the opportunity to submit data that would create this kind of mismatch.
You can try to use:
where(date: p[:date]..Float::INFINITY)
equivalent in sql
WHERE (`date` >= p[:date])
The result is:
Note.where(user_id: current_user.id, notetype: p[:note_type], date: p[:date]..Float::INFINITY).order(:fecha, :created_at)
And I have changed too
order('date ASC, created_at ASC')
For
order(:fecha, :created_at)
In this case I like to use the exists?
method provided by ActiveRecord:
Business.exists? user_id: current_user.id
In my rails (rails 4.2)
project, I use
Model.last(10) # get the last 10 record order by id
and it works.
I would consider using the attr_defaults found here. Your wildest dreams will come true.
With Rails 6, Zetiwerk became the default code loader.
For eager loading, try:
Zeitwerk::Loader.eager_load_all
Then
ApplicationRecord.descendants
This gives you just the helper method without the side effects of loading every ActionView::Helpers method into your model:
ActionController::Base.helpers.sanitize(str)
Through
remove_column :table_name, :column_name
in a migration file
You can remove a column directly in a rails console by typing:
ActiveRecord::Base.remove_column :table_name, :column_name
If someone is using column names like "key"
or "value"
, then you still see the same error that your mysql query syntax is bad. This should fix:
.where("`key` LIKE ?", "%#{key}%")
A good bet is to utilize Rails' Arel SQL manager, which explicitly supports case-insensitive ActiveRecord queries:
t = Guide.arel_table Guide.where(t[:title].matches('%attack'))
Here's an interesting blog post regarding the portability of case-insensitive queries using Arel. It's worth a read to understand the implications of utilizing Arel across databases.
And just to give you yet another option, you can use NOT ISNULL(archived)
as your WHERE filter.
user = Product.where(email: /^#{email}$/i).first
Using this code to multiple order by in single query.
$this->db->from($this->table_name);
$this->db->order_by("column1 asc,column2 desc");
$query = $this->db->get();
return $query->result();
For me, I couldn't get this to return a hash.
results = ActiveRecord::Base.connection.execute(sql)
But using the exec_query method worked.
results = ActiveRecord::Base.connection.exec_query(sql)
Change the variable into a property and add a breakpoint in the set method. Example:
private bool m_Var = false;
protected bool var
{
get {
return m_var;
}
set {
m_var = value;
}
}
pg_hba.conf
entry define login methods by IP addresses. You need to show the relevant portion of pg_hba.conf
in order to get proper help.
Change this line:
host all all <my-ip-address>/32 md5
To reflect your local network settings. So, if your IP is 192.168.16.78
(class C) with a mask of 255.255.255.0
, then put this:
host all all 192.168.16.0/24 md5
Make sure your WINDOWS MACHINE is in that network 192.168.16.0
and try again.
First, get the string that identifies the commit in some date, doing:
git rev-list -n 1 --before="2009-07-27 13:37" origin/master
It prints the commit identifier, takes the string (for instance XXXX) and does:
git checkout XXXX
I got an amazing scroller on my div-popup
. To apply, add this style to your div element:
overflow-y: scroll;
height: XXXpx;
The height
you specify will be the height of the div and once if you have contents to exceed this height, you have to scroll it.
Thank you.
You can use git stash
to save the current repository before doing the commit you want to make (after merging the changes from the upstream repo with git stash pop
). I had to do this yesterday when I had the same problem.
Swift - 4
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
addKeyBoardListener()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self) //remove observer
}
func addKeyBoardListener() {
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil);
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil);
}
@objc func keyboardWillShow(_ notification: Notification) {
}
@objc func keyboardWillHide(_ notification: Notification) {
}
It is possible to use patterns in a .gitignore
file. See the gitignore man page. The pattern */target/*
should ignore any directory named target and anything under it. Or you may try */target/**
to ignore everything under target.
Back to the original question:
xcopy "bin\development\whee.config.example" "TestConnectionExternal\bin\Debug\whee.config"
could be done with two commands eg:
mkdir "c:\mybackup\TestConnectionExternal\bin\Debug\whee.config\.."
xcopy "bin\development\whee.config.example" "c:\mybackup\TestConnectionExternal\bin\Debug\whee.config\"
By simply appending "\.." to the path of the destination file the destination directory is created if it not already exists. In this case
"c:\mybackup\TestConnectionExternal\bin\Debug\"
which is the parent directory of the non-existing directory
"c:\mybackup\TestConnectionExternal\bin\Debug\whee.config\.."
At least for WIN7 mkdir does not care if the directory
"c:\mybackup\TestConnectionExternal\bin\Debug\whee.config\"
really exists.
Here's a little plug if you mostly want to
select
elementoptions
, proper zindex, etc)ul
, li
generated markupsThen jquery.yaselect.js could be a better fit. Simply:
$('select').yaselect();
And the final markup is:
<div class="yaselect-wrap">
<div class="yaselect-current"><!-- current selection --></div>
</div>
<select class="yaselect-select" size="5">
<!-- your option tags -->
</select>
Check it out on github.com
First of all check error log in the path that your webserver indicates. Then maybe the browser is showing friendly error messages, so disable it.
https://superuser.com/questions/202244/show-http-error-details-in-google-chrome
http://animeshrivastava.blogspot.in/2017/08/activity-lifecycle-oncreate-beating_3.html
@Override
protected void onSaveInstanceState(Bundle b)
{
super.onSaveInstanceState(b);
String str="Screen Change="+String.valueOf(screenChange)+"....";
Toast.makeText(ctx,str+"You are changing orientation...",Toast.LENGTH_SHORT).show();
screenChange=true;
}
If you are using VS Code Insiders Build:
code-insiders .
With regular VS Code:
code .
Update image field to add full URL, ignoring null fields:
UPDATE test SET image = CONCAT('https://my-site.com/images/',image) WHERE image IS NOT NULL;
If you are using Outlook 2010, you can define your own style and select your formatting you want, in the Format options there is one option for Language, here you can specify the language and specify whether you want spell checker to ignore the text with this style.
With this style you can now paste the code as text and select your new style. Outlook will not correct the text and will not perform the spell check on it.
Below is the summary of the style I have defined for emailing the code snippets.
Do not check spelling or grammar, Border:
Box: (Single solid line, Orange, 0.5 pt Line width)
Pattern: Clear (Custom Color(RGB(253,253,217))), Style: Linked, Automatically update, Quick Style
Based on: HTML Preformatted
I guess the question arises, why would you need to do this? The reason for async
in C# 5.0 is so you can await a result. This method is not actually asynchronous, but simply called at a time so as not to interfere too much with the current thread.
Perhaps it may be better to start a thread and leave it to finish on its own.
If you're using Java 8, the Arrays
class provides a stream(int[] array)
method which returns a sequential IntStream
with the specified int
array. It has also been overloaded for double
and long
arrays.
int [] arr = {1,2,3,4};
int sum = Arrays.stream(arr).sum(); //prints 10
It also provides a method
stream(int[] array, int startInclusive, int endExclusive)
which permits you to take a specified range of the array (which can be useful) :
int sum = Arrays.stream(new int []{1,2,3,4}, 0, 2).sum(); //prints 3
Finally, it can take an array of type T
. So you can per example have a String
which contains numbers as an input and if you want to sum them just do :
int sum = Arrays.stream("1 2 3 4".split("\\s+")).mapToInt(Integer::parseInt).sum();
I had exactly the same error. My network is an internal one of a company. I downloaded neon-eclipse for java developpers. These steps worked for me:
1- I downloaded a VPN client on my PC to be totally blinded from the network. Shellfire I used. Use free account and connect to Shellserver.
2- Inside the windows firewall, I added incoming rule for Eclipse. Navigate to where eclipse exe is found.
3- Perform Maven Update project.
Then the project was able to fetch from the maven repository.
hope it helps.
it's well documented here:
https://cwiki.apache.org/confluence/display/TOMCAT/Connectors#Connectors-Q6
How do I bind to a specific ip address? - "Each Connector element allows an address property. See the HTTP Connector docs or the AJP Connector docs". And HTTP Connectors docs:
http://tomcat.apache.org/tomcat-7.0-doc/config/http.html
Standard Implementation -> address
"For servers with more than one IP address, this attribute specifies which address will be used for listening on the specified port. By default, this port will be used on all IP addresses associated with the server."
Spring uses dependency injection to populate the specific value when it finds the @Value annotation. However, instead of handing the value to the instance variable, it's handed to the implicit setter instead. This setter then handles the population of our NAME_STATIC value.
@RestController
//or if you want to declare some specific use of the properties file then use
//@Configuration
//@PropertySource({"classpath:application-${youeEnvironment}.properties"})
public class PropertyController {
@Value("${name}")//not necessary
private String name;//not necessary
private static String NAME_STATIC;
@Value("${name}")
public void setNameStatic(String name){
PropertyController.NAME_STATIC = name;
}
}
An important point that the other answers forgot, is that "@keyword" is compiled into "keyword" in the CIL.
So if you have a framework that was made in, say, F#, which requires you to define a class with a property named "class", you can actually do it.
It is not that useful in practice, but not having it would prevent C# from some forms of language interop.
I usually see it used not for interop, but to avoid the keyword restrictions (usually on local variable names, where this is the only effect) ie.
private void Foo(){
int @this = 2;
}
but I would strongly discourage that! Just find another name, even if the 'best' name for the variable is one of the reserved names.
Simple. When I use it, it's a modern dynamic language, when you use it, it's merely a scripting language!
A violation like that means that there's something seriously wrong with the code, and it's unreliable. I can see that a program might want to try to save the user's data in a way that one hopes won't write over previous data, in the hope that the user's data isn't already corrupted, but there is by definition no standard method of dealing with undefined behavior.
StringUtils.isEmpty(str)
or StringUtils.isNotEmpty(str)
StringUtils.isBlank(str)
or StringUtils.isNotBlank(str)
from Apache commons-lang.
The difference between empty
and blank
is : a string consisted of whitespaces only is blank
but isn't empty
.
I generally prefer using apache-commons if possible, instead of writing my own utility methods, although that is also plausible for simple ones like these.
To increase the heap size you can use the -Xmx argument when starting Java; e.g.
-Xmx256M
Just copy your favicon on: /yourappname/mainapp(ex:core)/static/mainapp(ex:core)/img
Then go to your mainapp template(ex:base.html) and just copy this, after {% load static %} because you must load first the statics.
<link href="{% static 'core/img/favi_x.png' %}" rel="shortcut icon" type="image/png" />
I just came across this tonight. Can't say if they are legit, how long in business, and whether they'll be around long, but seems interesting. I may give them a try, and will post update if I do.
Per the website, they say they offer hourly pay-as-you-go and weekly/monthly plans, plus there's a free trial.
Per @Iterator, posting update on my findings for this service, moving out from my comments:
I did the trial/evaluation. The trial can be misleading on how the trial works. You may need to signup to see prices but the trial so far, per the trial software download, doesn't appear to be time limited. It's just feature restricted. You signup to get your own account, but you actually use a generic trial login account to do the trial, not your own account. Your own account is used when you actually pay for the service. The trial limits what you can do, install, save, etc. but good enough to give you an idea of how things work. So it doesn't hurt to signup to evaluate and not pay anything.
Persistence of data is offered via saving files to DropBox (pre-installed, you just need login/configure), etc. There is no concept of AMIs, EBS, or some VM image. Their service is actually like a shared website hosting solution, where users timeshare a Mac machine (like timesharing a Unix/Linux server), and I think they limit or periodically purge what you put on the machine, or perhaps rather they don't backup your files, hence use of DropBox to do the backup. One should contact them to clarify this if desired.
They have various pricing options, as you mention the all day pass, monthly plans at $20, and their is a pay as you go plan at $1/hr. I'd probably go with pay as you go based on my usage. The pay as you go is based on prepaid credits (1 credit = 1 hour, billed at 30 credit increments). One caveat is that you need to periodically use the plan at least once every 60 days for the pay as you go plan or else you lose unused credits. So that's like minimum of spending 1 credit /1 hour every 60 days.
One last comment for now, from my evaluation, you'll need high bandwidth to use the service effectively. It's usable over 1.5 Mbps DSL but kind of slow in response. You'd want to use it from a corporate network with Gbps bandwidth for optimal use. Or at least a higher speed cable/DSL broadband connection. On my last test ~3Mbps seemed sufficient on the low bandwidth profile (they have multiple bandwidth connection profiles, low, medium, high, optimized for some bandwidth ranges). I didn't test on the higher ones. Your mileage may vary.
You can use length
:
if($("#one").length) { // 0 == false; >0 == true
alert('yes');
}
For short queries that can fit on one or two lines, I use the string literal solution in the top-voted solution above. For longer queries, I break them out to .sql
files. I then use a wrapper function to load the file and execute the script, something like:
script_cache = {}
def execute_script(cursor,script,*args,**kwargs):
if not script in script_cache:
with open(script,'r') as s:
script_cache[script] = s
return cursor.execute(script_cache[script],*args,**kwargs)
Of course this often lives inside a class so I don't usually have to pass cursor
explicitly. I also generally use codecs.open()
, but this gets the general idea across. Then SQL scripts are completely self-contained in their own files with their own syntax highlighting.
Building off of deepee1 and this, here's how to accept a class name in a string, and then use it to read and write to a database with LINQ. I use "dynamic" instead of deepee1's casting because it allows me to assign properties, which allows us to dynamically select and operate on any table we want.
Type tableType = Assembly.GetExecutingAssembly().GetType("NameSpace.TableName");
ITable itable = dbcontext.GetTable(tableType);
//prints contents of the table
foreach (object y in itable) {
string value = (string)y.GetType().GetProperty("ColumnName").GetValue(y, null);
Console.WriteLine(value);
}
//inserting into a table
dynamic tableClass = Activator.CreateInstance(tableType);
//Alternative to using tableType, using Tony's tips
dynamic tableClass = Activator.CreateInstance(null, "NameSpace.TableName").Unwrap();
tableClass.Word = userParameter;
itable.InsertOnSubmit(tableClass);
dbcontext.SubmitChanges();
//sql equivalent
dbcontext.ExecuteCommand("INSERT INTO [TableNme]([ColumnName]) VALUES ({0})", userParameter);
Bit old, but doesn't hurt to add some notes.
When you write something like this
let a: any;
let b: Object;
let c: {};
And that's why
a.doSomething(); // Ok: the compiler trusts you on that
b.doSomething(); // Error: Object has no doSomething member
c.doSomething(); // Error: c neither has doSomething nor inherits it from Object
and why
a.toString(); // Ok: whatever, dude, have it your way
b.toString(); // Ok: toString is defined in Object
c.toString(); // Ok: c inherits toString from Object
So Object
and {}
are equivalents in TypeScript.
If you declare functions like these
function fa(param: any): void {}
function fb(param: Object): void {}
with the intention of accepting anything for param (maybe you're going to check types at run-time to decide what to do with it), remember that
It is worth noting, though, that if param is supposed to accept multiple known types, a better approach is to declare it using union types, as in
function fc(param: string|number): void {}
Obviously, OO inheritance rules still apply, so if you want to accept instances of derived classes and treat them based on their base type, as in
interface IPerson {
gender: string;
}
class Person implements IPerson {
gender: string;
}
class Teacher extends Person {}
function func(person: IPerson): void {
console.log(person.gender);
}
func(new Person()); // Ok
func(new Teacher()); // Ok
func({gender: 'male'}); // Ok
func({name: 'male'}); // Error: no gender..
the base type is the way to do it, not any. But that's OO, out of scope, I just wanted to clarify that any should only be used when you don't know whats coming, and for anything else you should annotate the correct type.
UPDATE:
Typescript 2.2 added an object
type, which specifies that a value is a non-primitive: (i.e. not a number
, string
, boolean
, symbol
, undefined
, or null
).
Consider functions defined as:
function b(x: Object) {}
function c(x: {}) {}
function d(x: object) {}
x
will have the same available properties within all of these functions, but it's a type error to call d
with a primitive:
b("foo"); //Okay
c("foo"); //Okay
d("foo"); //Error: "foo" is a primitive
Use the format()
function with a '02x'
format.
>>> format(255, '02x')
'ff'
>>> format(2, '02x')
'02'
The 02
part tells format()
to use at least 2 digits and to use zeros to pad it to length, x
means lower-case hexadecimal.
The Format Specification Mini Language also gives you X
for uppercase hex output, and you can prefix the field width with #
to include a 0x
or 0X
prefix (depending on wether you used x
or X
as the formatter). Just take into account that you need to adjust the field width to allow for those extra 2 characters:
>>> format(255, '02X')
'FF'
>>> format(255, '#04x')
'0xff'
>>> format(255, '#04X')
'0XFF'
Since .NET Framework 4.5 and .NET Standard 1.0 you should use WebUtility.UrlEncode
. Advantages over alternatives:
It is part of .NET Framework 4.5+, .NET Core 1.0+, .NET Standard 1.0+, UWP 10.0+ and all Xamarin platforms as well. HttpUtility
, while being available in .NET Framework earlier (.NET Framework 1.1+), becomes available on other platforms much later (.NET Core 2.0+, .NET Standard 2.0+) and it still unavailable in UWP (see related question).
In .NET Framework, it resides in System.dll
, so it does not require any additional references, unlike HttpUtility
.
It properly escapes characters for URLs, unlike Uri.EscapeUriString
(see comments to drweb86's answer).
It does not have any limits on the length of the string, unlike Uri.EscapeDataString
(see related question), so it can be used for POST requests, for example.
A stable sorting algorithm is the one that sorts the identical elements in their same order as they appear in the input, whilst unstable sorting may not satisfy the case. - I thank my algorithm lecturer Didem Gozupek to have provided insight into algorithms.
Stable Sorting Algorithms:
Unstable Sorting Algorithms:
The problem happens whenever a process uses port 80.
You can run Netstat which is available in XAMPP Control Panel and check which process uses port 80 in your system.
For me it wasn't IIS, but Skype.
Turn off that process/application and then start the Apache services.
It heavily depends on the environment you're working in. Take for example javascript. In javascript the best way to pass in parameters is using objects with key/value pairs, which in practice means you only have one parameter. In other systems the sweet spot will be at three or four.
In the end, it all boils down to personal taste.
I tried other solutions and I didn't get the result I was looking for. This works for me.
<TouchableOpacity onPress={() => navigation.goBack()} style={{ flex: 1 }}>
<Image style={{ height: undefined, width: undefined, flex: 1 }}
source={{ uri: link }} resizeMode="contain"
/>
</TouchableOpacity>
Note I needed to set this as property of image tag than in css.
resizeMode="contain"
Also note that, you need to set flex: 1 on your parent container. For my component, TouchableOpacity is the root of the component.
I faced a similar problem, here's how I solved in my case. I verify if the task
already is RUNNING
or FINISHED
because an task can run only once. Below you will see a partial and adapted code from my solution.
public class MyActivity... {
private MyTask task;
@Override
protected void onCreate(Bundle savedInstanceState) {
// your code
task = new MyTask();
setList();
}
private void setList() {
if (task != null)
if (task.getStatus().equals(AsyncTask.Status.RUNNING)){
task.cancel(true);
task = new MyTask();
task.execute();
} else if (task.getStatus().equals(AsyncTask.Status.FINISHED)) {
task = new MyTask();
task.execute();
} else
task.execute();
}
class MyTask extends AsyncTask<Void, Item, Void>{
List<Item> Itens;
@Override
protected void onPreExecute() {
//your code
list.setVisibility(View.GONE);
adapterItem= new MyListAdapter(MyActivity.this, R.layout.item, new ArrayList<Item>());
list.setAdapter(adapterItem);
adapterItem.notifyDataSetChanged();
}
@Override
protected Void doInBackground(Void... params) {
Itens = getItens();
for (Item item : Itens) {
publishProgress(item );
}
return null;
}
@Override
protected void onProgressUpdate(Item ... item ) {
adapterItem.add(item[0]);
}
@Override
protected void onPostExecute(Void result) {
//your code
adapterItem.notifyDataSetChanged();
list.setVisibility(View.VISIBLE);
}
}
}
Here is an example of iterating over a pd.DataFrame
grouped by the column atable
. For this sample, "create" statements for an SQL database are generated within the for
loop:
import pandas as pd
df1 = pd.DataFrame({
'atable': ['Users', 'Users', 'Domains', 'Domains', 'Locks'],
'column': ['col_1', 'col_2', 'col_a', 'col_b', 'col'],
'column_type':['varchar', 'varchar', 'int', 'varchar', 'varchar'],
'is_null': ['No', 'No', 'Yes', 'No', 'Yes'],
})
df1_grouped = df1.groupby('atable')
# iterate over each group
for group_name, df_group in df1_grouped:
print('\nCREATE TABLE {}('.format(group_name))
for row_index, row in df_group.iterrows():
col = row['column']
column_type = row['column_type']
is_null = 'NOT NULL' if row['is_null'] == 'NO' else ''
print('\t{} {} {},'.format(col, column_type, is_null))
print(");")
While a mutex may be used to solve other problems, the primary reason they exist is to provide mutual exclusion and thereby solve what is known as a race condition. When two (or more) threads or processes are attempting to access the same variable concurrently, we have potential for a race condition. Consider the following code
//somewhere long ago, we have i declared as int
void my_concurrently_called_function()
{
i++;
}
The internals of this function look so simple. It's only one statement. However, a typical pseudo-assembly language equivalent might be:
load i from memory into a register
add 1 to i
store i back into memory
Because the equivalent assembly-language instructions are all required to perform the increment operation on i, we say that incrementing i is a non-atmoic operation. An atomic operation is one that can be completed on the hardware with a gurantee of not being interrupted once the instruction execution has begun. Incrementing i consists of a chain of 3 atomic instructions. In a concurrent system where several threads are calling the function, problems arise when a thread reads or writes at the wrong time. Imagine we have two threads running simultaneoulsy and one calls the function immediately after the other. Let's also say that we have i initialized to 0. Also assume that we have plenty of registers and that the two threads are using completely different registers, so there will be no collisions. The actual timing of these events may be:
thread 1 load 0 into register from memory corresponding to i //register is currently 0
thread 1 add 1 to a register //register is now 1, but not memory is 0
thread 2 load 0 into register from memory corresponding to i
thread 2 add 1 to a register //register is now 1, but not memory is 0
thread 1 write register to memory //memory is now 1
thread 2 write register to memory //memory is now 1
What's happened is that we have two threads incrementing i concurrently, our function gets called twice, but the outcome is inconsistent with that fact. It looks like the function was only called once. This is because the atomicity is "broken" at the machine level, meaning threads can interrupt each other or work together at the wrong times.
We need a mechanism to solve this. We need to impose some ordering to the instructions above. One common mechanism is to block all threads except one. Pthread mutex uses this mechanism.
Any thread which has to execute some lines of code which may unsafely modify shared values by other threads at the same time (using the phone to talk to his wife), should first be made acquire a lock on a mutex. In this way, any thread that requires access to the shared data must pass through the mutex lock. Only then will a thread be able to execute the code. This section of code is called a critical section.
Once the thread has executed the critical section, it should release the lock on the mutex so that another thread can acquire a lock on the mutex.
The concept of having a mutex seems a bit odd when considering humans seeking exclusive access to real, physical objects but when programming, we must be intentional. Concurrent threads and processes don't have the social and cultural upbringing that we do, so we must force them to share data nicely.
So technically speaking, how does a mutex work? Doesn't it suffer from the same race conditions that we mentioned earlier? Isn't pthread_mutex_lock() a bit more complex that a simple increment of a variable?
Technically speaking, we need some hardware support to help us out. The hardware designers give us machine instructions that do more than one thing but are guranteed to be atomic. A classic example of such an instruction is the test-and-set (TAS). When trying to acquire a lock on a resource, we might use the TAS might check to see if a value in memory is 0. If it is, that would be our signal that the resource is in use and we do nothing (or more accurately, we wait by some mechanism. A pthreads mutex will put us into a special queue in the operating system and will notify us when the resource becomes available. Dumber systems may require us to do a tight spin loop, testing the condition over and over). If the value in memory is not 0, the TAS sets the location to something other than 0 without using any other instructions. It's like combining two assembly instructions into 1 to give us atomicity. Thus, testing and changing the value (if changing is appropriate) cannot be interrupted once it has begun. We can build mutexes on top of such an instruction.
Note: some sections may appear similar to an earlier answer. I accepted his invite to edit, he preferred the original way it was, so I'm keeping what I had which is infused with a little bit of his verbiage.
editText.setInputType(InputType.TYPE_NULL);
Without quotes works for me:
<item name="android:textStyle">bold|italic</item>
forEach()
can be implemented to be faster than for-each loop, because the iterable knows the best way to iterate its elements, as opposed to the standard iterator way. So the difference is loop internally or loop externally.
For example ArrayList.forEach(action)
may be simply implemented as
for(int i=0; i<size; i++)
action.accept(elements[i])
as opposed to the for-each loop which requires a lot of scaffolding
Iterator iter = list.iterator();
while(iter.hasNext())
Object next = iter.next();
do something with `next`
However, we also need to account for two overhead costs by using forEach()
, one is making the lambda object, the other is invoking the lambda method. They are probably not significant.
see also http://journal.stuffwithstuff.com/2013/01/13/iteration-inside-and-out/ for comparing internal/external iterations for different use cases.
My exception-handling strategy is:
To catch all unhandled exceptions by hooking to the Application.ThreadException event
, then decide:
Then I always enclose every piece of code that is run externally in try/catch
:
Then I enclose in 'try/catch'
ApplicationException("custom message", innerException)
to keep track of what really happenedAdditionally, I try my best to sort exceptions correctly. There are exceptions which:
need to be shown to the user immediately
require some extra processing to put things together when they happen to avoid cascading problems (ie: put .EndUpdate in the finally
section during a TreeView
fill)
the user does not care, but it is important to know what happened. So I always log them:
In the event log
or in a .log file on the disk
It is a good practice to design some static methods to handle exceptions in the application top level error handlers.
I also force myself to try to:
So finally:
Bad:
// DON'T DO THIS; ITS BAD
try
{
...
}
catch
{
// only air...
}
Useless:
// DON'T DO THIS; IT'S USELESS
try
{
...
}
catch(Exception ex)
{
throw ex;
}
Having a try finally without a catch is perfectly valid:
try
{
listView1.BeginUpdate();
// If an exception occurs in the following code, then the finally will be executed
// and the exception will be thrown
...
}
finally
{
// I WANT THIS CODE TO RUN EVENTUALLY REGARDLESS AN EXCEPTION OCCURRED OR NOT
listView1.EndUpdate();
}
What I do at the top level:
// i.e When the user clicks on a button
try
{
...
}
catch(Exception ex)
{
ex.Log(); // Log exception
-- OR --
ex.Log().Display(); // Log exception, then show it to the user with apologies...
}
What I do in some called functions:
// Calculation module
try
{
...
}
catch(Exception ex)
{
// Add useful information to the exception
throw new ApplicationException("Something wrong happened in the calculation module:", ex);
}
// IO module
try
{
...
}
catch(Exception ex)
{
throw new ApplicationException(string.Format("I cannot write the file {0} to {1}", fileName, directoryName), ex);
}
There is a lot to do with exception handling (Custom Exceptions) but those rules that I try to keep in mind are enough for the simple applications I do.
Here is an example of extensions methods to handle caught exceptions a comfortable way. They are implemented in a way they can be chained together, and it is very easy to add your own caught exception processing.
// Usage:
try
{
// boom
}
catch(Exception ex)
{
// Only log exception
ex.Log();
-- OR --
// Only display exception
ex.Display();
-- OR --
// Log, then display exception
ex.Log().Display();
-- OR --
// Add some user-friendly message to an exception
new ApplicationException("Unable to calculate !", ex).Log().Display();
}
// Extension methods
internal static Exception Log(this Exception ex)
{
File.AppendAllText("CaughtExceptions" + DateTime.Now.ToString("yyyy-MM-dd") + ".log", DateTime.Now.ToString("HH:mm:ss") + ": " + ex.Message + "\n" + ex.ToString() + "\n");
return ex;
}
internal static Exception Display(this Exception ex, string msg = null, MessageBoxImage img = MessageBoxImage.Error)
{
MessageBox.Show(msg ?? ex.Message, "", MessageBoxButton.OK, img);
return ex;
}
For MySQL, this can be shortened to:
SELECT distributor_id,
COUNT(*) total,
SUM(level = 'exec') ExecCount,
SUM(level = 'personal') PersonalCount
FROM yourtable
GROUP BY distributor_id
Another example : I use it to group Data by date. But some data don't have date. I can group it with the header "NoDate"
JSON.parse()
function will do.
or
Using Jquery,
var obj = jQuery.parseJSON( '{ "name": "Vinod" }' );
alert( obj.name === "Vinod" );
Either you need
std::function<void(Foo*)> f = &Foo::doSomething;
so that you can call it on any instance, or you need to bind a specific instance, for example this
std::function<void(void)> f = std::bind(&Foo::doSomething, this);
In my case, I had all of the required features, but I had installed the Team Explorer version (accidentally used the wrong installer) before installing Professional.
When running the Team Explorer version, only the Blank Solution option was available.
The Team Explorer EXE was located in: "C:\Program Files (x86)\Microsoft Visual Studio\2017\TeamExplorer\Common7\IDE\devenv.exe"
Once I launched the correct EXE, Visual Studio started working as expected.
The Professional EXE was located in: "C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\devenv.exe"
This solved my issue, and the reason was I had enterprise edition previously installed and then uninstalled and installed the professional edition. Team Explorer was not modified later when I moved to professional from enterprise edition.
Supported by SQL Server 2005 and later versions
SELECT CONVERT(VARCHAR(10), GETDATE(), 101)
+ ' ' + CONVERT(VARCHAR(8), GETDATE(), 108)
* See Microsoft's documentation to understand what the 101
and 108
style codes above mean.
Supported by SQL Server 2012 and later versions
SELECT FORMAT(GETDATE() , 'MM/dd/yyyy HH:mm:ss')
Result
Both of the above methods will return:
10/16/2013 17:00:20
Any one on windows 10 Pro , this is for you guys --
Paste below code-
RD /S /Q "%WinDir%\System32\GroupPolicyUsers"
RD /S /Q "%WinDir%\System32\GroupPolicy"
gpupdate /force
After few seconds you will see this -
User Policy update has completed successfully.
Computer Policy update has completed successfully.
Now you can change your search engine to whatever you want.
Thank you
z-index
only applies to elements that have been given an explicit position. Add position:relative
to #popupContent and you should be good to go.
you can use:
overflow-x: auto;
If you set 'auto' in overflow-x, scroll will appear only when inner size is biggest that DIV area
dictc={"stName":"asas"}
keys=dictc.keys()
for key in list(keys):
dictc[key.upper()] ='New value'
print(str(dictc))
You can use it only in body tag or in tables. Something like this:
<table width="100%" background="YOUR_IMAGE_URL" style="STYLES YOU WANT (i.e. background-repeat)">
This worked for me.
While this question is rather old, and has been answered, I thought I'd take the time to offer a couple of options that are, as yet, not addressed in other answers.
Given the corrected HTML (camelCasing the id
attribute-value) of:
<label year="2010" month="6" id="currentMonth"> June 2010</label>
You could use regular expressions to extract the month-name, and year:
// gets the eleent with an id equal to 'currentMonth',
// retrieves its text-content,
// uses String.prototype.trim() to remove leading and trailing white-space:
var labelText = $('#currentMonth').text().trim(),
// finds the sequence of one, or more, letters (a-z, inclusive)
// at the start (^) of the string, and retrieves the first match from
// the array returned by the match() method:
month = labelText.match(/^[a-z]+/i)[0],
// finds the sequence of numbers (\d) of length 2-4 ({2,4}) characters,
// at the end ($) of the string:
year = labelText.match(/\d{2,4}$/)[0];
var labelText = $('#currentMonth').text().trim(),_x000D_
month = labelText.match(/^[a-z]+/i)[0],_x000D_
year = labelText.match(/\d{2,4}$/)[0];_x000D_
_x000D_
console.log(month, year);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<label year="2010" month="6" id="currentMonth"> June 2010</label>
_x000D_
Rather than regular expressions, though, you could instead use custom data-*
attributes (which work in HTML 4.x, despite being invalid under the doctype, but are valid under HTML 5):
var label = $('#currentMonth'),_x000D_
month = label.data('month'),_x000D_
year = label.data('year');_x000D_
_x000D_
console.log(month, year);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<label data-year="2010" data-month="6" id="currentMonth"> June 2010</label>
_x000D_
Note that this will output 6
(for the data-month
), rather than 'June'
as in the previous example, though if you use an array to tie numbers to month-names, that can be solved easily:
var monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],_x000D_
label = $('#currentMonth'),_x000D_
month = monthNames[+label.data('month') - 1],_x000D_
year = label.data('year');_x000D_
_x000D_
console.log(month, year);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<label data-year="2010" data-month="6" id="currentMonth"> June 2010</label>
_x000D_
Similarly, the above could be easily transcribed to the native DOM (in compliant browsers):
var monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],_x000D_
label = document.getElementById('currentMonth'),_x000D_
month = monthNames[+label.dataset.month - 1],_x000D_
year = label.dataset.year;_x000D_
_x000D_
console.log(month, year);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<label data-year="2010" data-month="6" id="currentMonth"> June 2010</label>
_x000D_
References:
Adding scroll="no"
and style="overflow:hidden"
on iframe didn't work, I had to add style="overflow:hidden"
on body of html document loaded inside iframe.
Move script tag at the end of BODY instead of HEAD because in current code when the script is computed html element doesn't exist in document.
Since you don't want to you jquery. Use window.onload or document.onload to execute the entire piece of code that you have in current script tag. window.onload vs document.onload
Now Microsoft is migrating to open-source - see CoreFX (GitHub).
Sort a two dimensional array based on one column
The first column is a date of format "yyyy.MM.dd HH:mm" and the second column is a String.
Since you say 2-D array, I assume "date of format ..." means a String. Here's code for sorting a 2-D array of String[][]:
import java.util.Arrays;
import java.util.Comparator;
public class Asdf {
public static void main(final String[] args) {
final String[][] data = new String[][] {
new String[] { "2009.07.25 20:24", "Message A" },
new String[] { "2009.07.25 20:17", "Message G" },
new String[] { "2009.07.25 20:25", "Message B" },
new String[] { "2009.07.25 20:30", "Message D" },
new String[] { "2009.07.25 20:01", "Message F" },
new String[] { "2009.07.25 21:08", "Message E" },
new String[] { "2009.07.25 19:54", "Message R" } };
Arrays.sort(data, new Comparator<String[]>() {
@Override
public int compare(final String[] entry1, final String[] entry2) {
final String time1 = entry1[0];
final String time2 = entry2[0];
return time1.compareTo(time2);
}
});
for (final String[] s : data) {
System.out.println(s[0] + " " + s[1]);
}
}
}
Output:
2009.07.25 19:54 Message R
2009.07.25 20:01 Message F
2009.07.25 20:17 Message G
2009.07.25 20:24 Message A
2009.07.25 20:25 Message B
2009.07.25 20:30 Message D
2009.07.25 21:08 Message E
Adding to Jim's elaborate answer:
Check the typing
module -- this module supports type hints as specified by PEP 484.
For example, the function below takes and returns values of type str
and is annotated as follows:
def greeting(name: str) -> str:
return 'Hello ' + name
The typing
module also supports:
I use this form for just this sort of thing:
gci . hosts -r | ? {!$_.PSIsContainer}
.
maps to positional parameter Path
and "hosts" maps to positional parameter Filter
. I highly recommend using Filter
over Include
if the provider supports filtering (and the filesystem provider does). It is a good bit faster than Include
.
document.body.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
console.log('clicked ;)');
}
});
DEMO
Steps to comment / uncommented
Press alt + f11/ Developer tab visual basic editor view tab - toolbar - edit - comments.
Any one looking for a swift solution
let url = NSURL(string: "http://www.apple.com/")
let request = NSMutableURLRequest(URL: url!)
request.HTTPBody = "company=Locassa&quality=AWESOME!".dataUsingEncoding(NSUTF8StringEncoding)
>>> 2 == 2.0
True
>>> 2 is 2.0
False
Use ==
All I can think of is that something is over-riding this afterwards.
You are including the reset styles first, right?
If your regex includes a variable, make sure to escape it.
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
This can be used like this
new RegExp(escapeRegExp(searchString), 'i')
Or in a mongoDb query like this
{ '$regex': escapeRegExp(searchString) }
Posted same comment here
I faced this issue in Xcode 6.1 when I removed Main.storyboard
, the LaunchScreen.xib
file and the default ViewController
classes from my project.
I fixed it by deleting the Launch Screen File
and Main Interface
entries from Info.plist
You can easily send the email with HTML content via PHP. Use the following script.
<?php
$to = '[email protected]';
$subject = "Send HTML Email Using PHP";
$htmlContent = '
<html>
<body>
<h1>Send HTML Email Using PHP</h1>
<p>This is a HTMl email using PHP by CodexWorld</p>
</body>
</html>';
// Set content-type header for sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// Additional headers
$headers .= 'From: CodexWorld<[email protected]>' . "\r\n";
$headers .= 'Cc: [email protected]' . "\r\n";
$headers .= 'Bcc: [email protected]' . "\r\n";
// Send email
if(mail($to,$subject,$htmlContent,$headers)):
$successMsg = 'Email has sent successfully.';
else:
$errorMsg = 'Email sending fail.';
endif;
?>
Source code and live demo can be found from here - Send Beautiful HTML Email using PHP
Simplify or break apart the function so that it doesn't require nine arguments (or ignore pylint, but dodges like the ones you're proposing defeat the purpose of a lint tool).
EDIT: if it's a temporary measure, disable the warning for the particular function in question using a comment as described here: http://lists.logilab.org/pipermail/python-projects/2006-April/000664.html
Later, you can grep for all of the disabled warnings.
I've tried sean662's 3rd solution and worked with now() function stored in an INSERT sql an then it's value in the date_create() function. After that the variable is then passed through the date_format() function and you can have the date order that you like.
Are you trying to join data or filter data?
For readability it makes the most sense to isolate these use cases to ON and WHERE respectively.
It can become very difficult to read a query where the JOIN condition and a filtering condition exist in the WHERE clause.
Performance wise you should not see a difference, though different types of SQL sometimes handle query planning differently so it can be worth trying ¯\_(?)_/¯
(Do be aware of caching effecting the query speed)
Also as others have noted, if you use an outer join you will get different results if you place the filter condition in the ON clause because it only effects one of the tables.
I wrote a more in depth post about this here: https://dataschool.com/learn/difference-between-where-and-on-in-sql
You need to set the path of maven under Global setting like MAVEN_HOME
/user/share/maven
and make sure the workbench have permission of read, write and delete "777"
Please find below the code that generates automatically the content of the txt local file and display it html. Good luck!
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
var x;
if(navigator.appName.search('Microsoft')>-1) { x = new ActiveXObject('MSXML2.XMLHTTP'); }
else { x = new XMLHttpRequest(); }
function getdata() {
x.open('get', 'data1.txt', true);
x.onreadystatechange= showdata;
x.send(null);
}
function showdata() {
if(x.readyState==4) {
var el = document.getElementById('content');
el.innerHTML = x.responseText;
}
}
</script>
</head>
<body onload="getdata();showdata();">
<div id="content"></div>
</body>
</html>
$.each(result, function(key, value) {
console.log(key+ ':' + value);
});
This awk
function returns substring of $0
that includes fields from begin
to end
:
function fields(begin, end, b, e, p, i) {
b = 0; e = 0; p = 0;
for (i = 1; i <= NF; ++i) {
if (begin == i) { b = p; }
p += length($i);
e = p;
if (end == i) { break; }
p += length(FS);
}
return substr($0, b + 1, e - b);
}
To get everything starting from field 3:
tail = fields(3);
To get section of $0
that covers fields 3 to 5:
middle = fields(3, 5);
b, e, p, i
nonsense in function parameter list is just an awk
way of declaring local variables.
i think token must include all the needed information encoded inside it, which makes authentication by validating the token and decoding the info https://www.oauth.com/oauth2-servers/access-tokens/self-encoded-access-tokens/
MEMORY USAGE key
command gives you the number of bytes that a key and its value require to be stored in RAM.
The reported usage is the total of memory allocations for data and administrative overheads that a key its value require (source redis documentation)
I had a similar problem caused by the addition of a CSS value for perspective in the body CSS
body { perspective: 1200px; }
Killed
#mainNav { position: fixed; }
You've mentioned that they each have their own machines, but if they need to log onto a co-workers machine, and then use the file, saving it through "C:\Users\Public\Desktop\" will make it available to different usernames.
Public Sub SaveToDesktop()
ThisWorkbook.SaveAs Filename:="C:\Users\Public\Desktop\" & ThisWorkbook.Name & "_copy", _
FileFormat:=xlOpenXMLWorkbookMacroEnabled
End Sub
I'm not sure whether this would be a requirement, but may help!
Use find
with a wildcard:
find . -name 'mystring*'
It's the "frame" or "range" clause of window functions, which are part of the SQL standard and implemented in many databases, including Teradata.
A simple example would be to calculate the average amount in a frame of three days. I'm using PostgreSQL syntax for the example, but it will be the same for Teradata:
WITH data (t, a) AS (
VALUES(1, 1),
(2, 5),
(3, 3),
(4, 5),
(5, 4),
(6, 11)
)
SELECT t, a, avg(a) OVER (ORDER BY t ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING)
FROM data
ORDER BY t
... which yields:
t a avg
----------
1 1 3.00
2 5 3.00
3 3 4.33
4 5 4.00
5 4 6.67
6 11 7.50
As you can see, each average is calculated "over" an ordered frame consisting of the range between the previous row (1 preceding
) and the subsequent row (1 following
).
When you write ROWS UNBOUNDED PRECEDING
, then the frame's lower bound is simply infinite. This is useful when calculating sums (i.e. "running totals"), for instance:
WITH data (t, a) AS (
VALUES(1, 1),
(2, 5),
(3, 3),
(4, 5),
(5, 4),
(6, 11)
)
SELECT t, a, sum(a) OVER (ORDER BY t ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
FROM data
ORDER BY t
yielding...
t a sum
---------
1 1 1
2 5 6
3 3 9
4 5 14
5 4 18
6 11 29
Here's another very good explanations of SQL window functions.
If this command not help
git config http.postBuffer 524288000
Try to change ssh method to https
git remote -v
git remote rm origin
git remote add origin https://github.com/username/project.git
As already stated above, the ISO-C11 preprocessor does not support string comparison. However, the problem of assigning a macro with the “opposite value” can be solved with “token pasting” and “table access”. Jesse’s simple concatenate/stringify macro-solution fails with gcc 5.4.0 because the stringization is done before the evaluation of the concatenation (conforming to ISO C11). However, it can be fixed:
#define P_(user) user ## _VS
#define VS(user) P_ (user)
#define S(U) S_(U)
#define S_(U) #U
#define jack_VS queen
#define queen_VS jack
S (VS (jack))
S (jack)
S (VS (queen))
S (queen)
#define USER jack // jack or queen, your choice
#define USER_VS USER##_VS // jack_VS or queen_VS
S (USER)
S (USER_VS)
The first line (macro P_()
) adds one indirection to let the next line (macro VS()
) finish the concatenation before the stringization (see Why do I need double layer of indirection for macros?). The stringization macros (S()
and S_()
) are from Jesse.
The table (macros jack_VS
and queen_VS
) which is much easier to maintain than the if-then-else construction of the OP is from Jesse.
Finally, the next four-line block invokes the function-style macros. The last four-line block is from Jesse’s answer.
Storing the code in foo.c
and invoking the preprocessor gcc -nostdinc -E foo.c
yields:
# 1 "foo.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "foo.c"
# 9 "foo.c"
"queen"
"jack"
"jack"
"queen"
"jack"
"USER_VS"
The output is as expected. The last line shows that the USER_VS
macro is not expanded before stringization.
You can also use the Properties class
Here's the constants file called
# this will hold all of the constants
frameWidth = 1600
frameHeight = 900
Here is the code that uses the constants
public class SimpleGuiAnimation {
int frameWidth;
int frameHeight;
public SimpleGuiAnimation() {
Properties properties = new Properties();
try {
File file = new File("src/main/resources/dataDirectory/gui_constants.properties");
FileInputStream fileInputStream = new FileInputStream(file);
properties.load(fileInputStream);
}
catch (FileNotFoundException fileNotFoundException) {
System.out.println("Could not find the properties file" + fileNotFoundException);
}
catch (Exception exception) {
System.out.println("Could not load properties file" + exception.toString());
}
this.frameWidth = Integer.parseInt(properties.getProperty("frameWidth"));
this.frameHeight = Integer.parseInt(properties.getProperty("frameHeight"));
}
A few principles:
you have a std::exception base class, you should have your exceptions derive from it. That way general exception handler still have some information.
Don't throw pointers but object, that way memory is handled for you.
Example:
struct MyException : public std::exception
{
std::string s;
MyException(std::string ss) : s(ss) {}
~MyException() throw () {} // Updated
const char* what() const throw() { return s.c_str(); }
};
And then use it in your code:
void Foo::Bar(){
if(!QueryPerformanceTimer(&m_baz)){
throw MyException("it's the end of the world!");
}
}
void Foo::Caller(){
try{
this->Bar();// should throw
}catch(MyException& caught){
std::cout<<"Got "<<caught.what()<<std::endl;
}
}
outfile = open( 'dict.txt', 'w' )
for key, value in sorted( mydict.items() ):
outfile.write( str(key) + '\t' + str(value) + '\n' )
Here is an angularjs directive for panzi's answer.
module.directive('autoHeight', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element = element[0];
var resize = function(){
element.style.height = 'auto';
element.style.height = (element.scrollHeight)+'px';
};
element.addEventListener('change', resize, false);
element.addEventListener('cut', resize, false);
element.addEventListener('paste', resize, false);
element.addEventListener('drop', resize, false);
element.addEventListener('keydown',resize, false);
setTimeout(resize, 100);
}
};
});
HTML:
<textarea ng-model="foo" auto-height></textarea>
You can use the EXACT
Function for exact string comparisons.
=IF(EXACT(A1, "ENG"), 1, 0)
Try This Code $scope.DSRListGrid.data = data; this one for source data
for (var prop in data[0]) {
if (data[0].hasOwnProperty(prop)) {
$scope.ListColumns.push(
{
"name": prop,
"field": prop,
"width": 150,
"headerCellClass": 'font-12'
}
);
}
}
console.log($scope.ListColumns);
Prior to PHP 5.2.0 and above you should use filter_input()
which is especially created for that to get a specific external user inputs such as get, post or cookie variables by name and optionally filters it to avoid any XSS/Injection attacks on your site. For example:
$user = filter_input(INPUT_POST, 'username');
You may use one of INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV.
By using optional 3rd argument, you can extend it by variety of filters (for validating, sanitizing, filtering or other), e.g. FILTER_SANITIZE_SPECIAL_CHARS
, FILTER_SANITIZE_ENCODED
, etc.
For example:
<?php
$search_html = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_SPECIAL_CHARS);
$search_url = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_ENCODED);
echo "You have searched for $search_html.\n";
echo "<a href='?search=$search_url'>Search again.</a>";
?>
The syntax is:
mixed
filter_input
( int $type , string $variable_name [, int $filter = FILTER_DEFAULT [, mixed $options ]] )(PHP 5 >= 5.2.0, PHP 7)
See also: Why is better to use filter_input()?
Try this out.
<iframe src="https://docs.google.com/viewerng/viewer?url=http://infolab.stanford.edu/pub/papers/google.pdf&embedded=true" frameborder="0" height="100%" width="100%">_x000D_
</iframe>
_x000D_
For Windows:
mvn deploy:deploy-file -DgroupId=joda-time -DartifactId=joda-time -Dversion=2.7 -Dpackaging=jar -Dfile=joda-time-2.7.jar
-DgeneratePom=true -DrepositoryId=[Your ID] -Durl=[YourURL]
Skype likes to use port 80 and blocks IIS. That was my prob.
Some time ago Jupyter Notebooks started stripping JavaScript from HTML content [#3118]. Here are two solutions:
Serving Local HTML
If you want to embed an HTML page with JavaScript on your page now, the easiest thing to do is to save your HTML file to the directory with your notebook and then load the HTML as follows:
from IPython.display import IFrame
IFrame(src='./nice.html', width=700, height=600)
Serving Remote HTML
If you prefer a hosted solution, you can upload your HTML page to an Amazon Web Services "bucket" in S3, change the settings on that bucket so as to make the bucket host a static website, then use an Iframe component in your notebook:
from IPython.display import IFrame
IFrame(src='https://s3.amazonaws.com/duhaime/blog/visualizations/isolation-forests.html', width=700, height=600)
This will render your HTML content and JavaScript in an iframe, just like you can on any other web page:
<iframe src='https://s3.amazonaws.com/duhaime/blog/visualizations/isolation-forests.html', width=700, height=600></iframe>
_x000D_
It's probably caused by a local network connectivity issue (but also a DNS error is possible). Unfortunately HResult
is generic, however you can determine the exact issue catching HttpRequestException
and then inspecting InnerException
: if it's a WebException
then you can check the WebException.Status
property, for example WebExceptionStatus.NameResolutionFailure
should indicate a DNS resolution problem.
It may happen, there isn't much you can do.
What I'd suggest to always wrap that (network related) code in a loop with a try
/catch
block (as also suggested here for other fallible operations). Handle known exceptions, wait a little (say 1000 msec) and try again (for say 3 times). Only if failed all times then you can quit/report an error to your users. Very raw example like this:
private const int NumberOfRetries = 3;
private const int DelayOnRetry = 1000;
public static async Task<HttpResponseMessage> GetFromUrlAsync(string url) {
using (var client = new HttpClient()) {
for (int i=1; i <= NumberOfRetries; ++i) {
try {
return await client.GetAsync(url);
}
catch (Exception e) when (i < NumberOfRetries) {
await Task.Delay(DelayOnRetry);
}
}
}
}
I use this method so I can have more control.
git branch -D $(git branch | grep -v "master" | grep -v "develop")
This is remove any branches not named: master
or develop
.
When the iFrame points to your site like this:
<html>
<head>
<script type="text/javascript" src="/jquery.js"></script>
</head>
<body>
<iframe id="my_frame" src="/wherev"></iframe>
</body>
</html>
You can access iFrame DOM through this kind of thing.
var iframeBody = $(window.my_frame.document.getElementsByTagName("body")[0]);
iframeBody.append($("<h1/>").html("Hello world!"));
To account for leading and trailing whitespace, you probably want to use normalize-space()
//div[contains(@class, 'Caption') and normalize-space(.)='Model saved']
and
//div[@id='alertLabel' and normalize-space(.)='Save to server successful']
Note that //div[contains(@class, 'Caption') and normalize-space(.//text())='Model saved']
also works.
For completeness sake, also a solution with Joda-Time version 2.5 and its DateTime
class:
new Timestamp(new DateTime(2007, 9, 23, 0, 0, DateTimeZone.forID( "America/Montreal" )).getMillis())
You can import a csv file to this website(https://www.tablesgenerator.com/latex_tables) and click copy to clipboard.
Simplest of all Solutions:
dict = {'first': 1,
'second': 2,
'third': 3}
Now,
dict['last'] || 'Excluded'
will return 'Excluded', which is the default value.
You can use below command from your SQL editor/Terminal:
"mysql -h(hostname/IP>) -u(username) -p(password) databasename <(query.sql) > outputFILE(.txt/.xls)"
e.g hostname -x.x.x.x
uname - username
password - password
DBName - employeeDB
queryFile - employee.sql
outputFile - outputFile.xls
mysql -hx.x.x.x -uusername -ppassword employeeDB< employee.sql> outputFile.xls
Make sure you are executing the command from the directory where SQL query is located or mention the full path of the sql query location in the above command.
It may be important to point out the current stable, unstable and dev versions of each (including date):
http://pecl.php.net/package/apc
dev dev 2013-09-12
3.1.14 beta 2013-01-02
3.1.9 stable 2011-05-14
dev/3.2 dev 2013-12-13
dev/3.1 dev 2013-11-05
3.1.0 stable 2013-10-10
3.0.4 stable 2013-10-10
https://github.com/eaccelerator/eaccelerator
dev dev 2012-08-16
0.9.6-rc1 unstable 2010-01-26
0.9.5.1 stable 2007-05-16
Use a border-radius property of 50%.
So for example:
.example-div {
border-radius: 50%
}
Let's say you have a string:
var string = "potatoes + carrots"
And you want to replace the word "potatoes" in that string with "tomatoes"
string = string.replacingOccurrences(of: "potatoes", with: "tomatoes", options: NSString.CompareOptions.literal, range: nil)
If you print your string, it will now be: "tomatoes + carrots"
If you want to remove the word potatoes from the sting altogether, you can use:
string = string.replacingOccurrences(of: "potatoes", with: "", options: NSString.CompareOptions.literal, range: nil)
If you want to use some other characters in your sting, use:
- Null Character (\0)
- Backslash (\)
- Horizontal Tab (\t)
- Line Feed (\n)
- Carriage Return (\r)
- Double Quote (\")
- Single Quote (\')
Example:
string = string.replacingOccurrences(of: "potatoes", with: "dog\'s toys", options: NSString.CompareOptions.literal, range: nil)
Output: "dog's toys + carrots"
just go to the window bottom tray click on wamp icon ,click mysql->my.ini,then there is option ;sql-mode="" uncomment this make it like sql-mode="" and restart wamp worked for me
Now (with JDK 9 onwards), you can just use java to get that executed. In order to execute "Hello.java" containing the main, one can use: java Hello.java
You do not need to compile using separately using javac anymore.
Be careful when using milliseconds.
The date.getTime() returns milliseconds and doing math operation with milliseconds requires to include
The example from comment above is the best solution I found so far https://stackoverflow.com/a/11252167/2091095 . But use +1 to its result if you want the to count all days involved.
function treatAsUTC(date) {
var result = new Date(date);
result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
return result;
}
function daysBetween(startDate, endDate) {
var millisecondsPerDay = 24 * 60 * 60 * 1000;
return (treatAsUTC(endDate) - treatAsUTC(startDate)) / millisecondsPerDay;
}
var diff = daysBetween($('#first').val(), $('#second').val()) + 1;
To convert integer to char only 0 to 9 will be converted. As we know 0's ASCII value is 48 so we have to add its value to the integer value to convert in into the desired character hence
int i=5;
char c = i+'0';
Fix:
I chose the "ISAPI & CGI Restrictions" after clicking the server name (not the site name) in IIS Manager, and right clicked the "ASP.NET v4.0.30319" lines and chose "Allow".
After turning on ASP.NET from "Programs and Features > Turn Windows features on or off", you must install ASP.NET from the Windows command prompt. The MIME types don't ever show up, but after doing this command, I noticed these extensions showed up under the IIS web site "Handler Mappings" section of IIS Manager.
C:\>cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319
C:\Windows\Microsoft.NET\Framework64\v4.0.30319>dir aspnet_reg*
Volume in drive C is Windows
Volume Serial Number is 8EE6-5DD0
Directory of C:\Windows\Microsoft.NET\Framework64\v4.0.30319
03/18/2010 08:23 PM 19,296 aspnet_regbrowsers.exe
03/18/2010 08:23 PM 36,696 aspnet_regiis.exe
03/18/2010 08:23 PM 102,232 aspnet_regsql.exe
3 File(s) 158,224 bytes
0 Dir(s) 34,836,508,672 bytes free
C:\Windows\Microsoft.NET\Framework64\v4.0.30319>aspnet_regiis.exe -i
Start installing ASP.NET (4.0.30319).
.....
Finished installing ASP.NET (4.0.30319).
C:\Windows\Microsoft.NET\Framework64\v4.0.30319>
However, I still got this error. But if you do what I mentioned for the "Fix", this will go away.
HTTP Error 404.2 - Not Found
The page you are requesting cannot be served because of the ISAPI and CGI Restriction list settings on the Web server.
Here is the code you can use for every browser:
<embed src="pdfFiles/interfaces.pdf" width="600" height="500" alt="pdf" pluginspage="http://www.adobe.com/products/acrobat/readstep2.html">
Tested on firefox and chrome
Create an array to store the objects:
ArrayList<MyObject> list = new ArrayList<MyObject>();
In a single step:
list.add(new MyObject (1, 2, 3)); //Create a new object and adding it to list.
or
MyObject myObject = new MyObject (1, 2, 3); //Create a new object.
list.add(myObject); // Adding it to the list.
Here's a good example. I use it to rename the variable because the JSON is coming from a .Net
environment where properties start with an upper-case letter.
public class Parameter {
@JsonProperty("Name")
public String name;
@JsonProperty("Value")
public String value;
}
This correctly parses to/from the JSON:
"Parameter":{
"Name":"Parameter-Name",
"Value":"Parameter-Value"
}
Important to note is the INT32 limit of Batch: 'Invalid number. Numbers are limited to 32-bits of precision.'
Try the following statements:
IF 2147483647 GTR 2147483646 echo A is greater than B (will be TRUE)
IF 2147483648 GTR 2147483647 echo A is greater than B (will be FALSE!)
Any number greater than the max INT32 value will BREAK THE SCRIPT! Seeing as filesize is measured in bytes, the scripts will support a maximum filesize of about 255.9999997615814 MB !
melt()
from the reshape2 package gets you close ...
library(reshape2)
(res <- melt(as.data.frame(mat), id="time"))
# time variable value
# 1 0.0 C_0 0.1
# 2 0.5 C_0 0.2
# 3 1.0 C_0 0.3
# 4 0.0 C_1 0.3
# 5 0.5 C_1 0.4
# 6 1.0 C_1 0.5
... although you may want to post-process its results to get your preferred column names and ordering.
setNames(res[c("variable", "time", "value")], c("name", "time", "val"))
# name time val
# 1 C_0 0.0 0.1
# 2 C_0 0.5 0.2
# 3 C_0 1.0 0.3
# 4 C_1 0.0 0.3
# 5 C_1 0.5 0.4
# 6 C_1 1.0 0.5
Root directory is fine for placing the .gitignore
file.
Don't forget to use git rm --cached FILENAME
to add files to .gitignore if you have created the gitignore file after you committed the repo with a file you want ignored. See github docs. I found this out when I created a .env file, then committed it, then tried it to ignore it by creating a .gitignore file.
Simple solution: just create and add a second, non-generic interface to the generic class:
public interface IGenericClass
{
}
public class GenericClass<T> : GenericInterface<T>, IGenericClass
{
}
Then just check for that in any way you like using is
, as
, IsAssignableFrom
, etc.
if (thing is IGenericClass)
{
// Do work
{
Obviously only possible if you have the ability to edit the generic class (which the OP seems to have), but it's a bit more elegant and readable than using a cryptic extension method.
The only thing which worked for me is this
fetchData()
.subscribe(
(data) => {
//Called when success
},
(error) => {
//Called when error
}
).add(() => {
//Called when operation is complete (both success and error)
});
All nice solutions, borrowing and improvising for special case -> If you want to add a label near the arrowhead:
arr = [2,3]
txt = “Vector X”
ax.annotate(txt, arr)
ax.arrow(0, 0, *arr, head_width=0.05, head_length=0.1)
if you want to access table cell
WebElement thirdCell = driver.findElement(By.Xpath("//table/tbody/tr[2]/td[1]"));
If you want to access nested table cell -
WebElement thirdCell = driver.findElement(By.Xpath("//table/tbody/tr[2]/td[2]"+//table/tbody/tr[1]/td[2]));
For more details visit this Tutorial
This code will help you to show your cursor at the last position of editing text.
editText.requestFocus();
editText.setSelection(editText.length());
According to spark documentation "where()
is an alias for filter()
"
filter(condition)
Filters rows using the given condition.
where()
is an alias for filter()
.
Parameters: condition – a Column
of types.BooleanType
or a string of SQL expression.
>>> df.filter(df.age > 3).collect()
[Row(age=5, name=u'Bob')]
>>> df.where(df.age == 2).collect()
[Row(age=2, name=u'Alice')]
>>> df.filter("age > 3").collect()
[Row(age=5, name=u'Bob')]
>>> df.where("age = 2").collect()
[Row(age=2, name=u'Alice')]
FTL stands for FreeMarker Template.
It is very useful when you want to follow the MVC (Model View Controller) pattern.
The idea behind using the MVC pattern for dynamic Web pages is that you separate the designers (HTML authors) from the programmers.
OK, very obvious answer here... basically relative position is relative to previous element or window, while absolute don't care about the other elements unless it's a parent if you using top and left...
Look at the example I create for you to show the differences...
Also you can see it in action, using the css I create for you, you can see how absolute and relative positions behave:
.parent {_x000D_
display: inline-block;_x000D_
width: 180px;_x000D_
height: 160px;_x000D_
border: 1px solid black;_x000D_
}_x000D_
_x000D_
.black {_x000D_
position: relative;_x000D_
width: 100px;_x000D_
height: 30px;_x000D_
margin: 5px;_x000D_
border: 1px solid black;_x000D_
}_x000D_
_x000D_
.red {_x000D_
width: 100px;_x000D_
height: 30px;_x000D_
margin: 5px;_x000D_
top: 16px;_x000D_
background: red;_x000D_
border: 1px solid red;_x000D_
}_x000D_
_x000D_
.red-1 {_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.red-2 {_x000D_
position: absolute;_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="black">_x000D_
</div>_x000D_
<div class="red red-1">_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="parent">_x000D_
<div class="black">_x000D_
</div>_x000D_
<div class="red red-2">_x000D_
</div>_x000D_
</div>
_x000D_
This function returns a string with the difference from a datetime string and the current datetime.
function get_time_diff( datetime )
{
var datetime = typeof datetime !== 'undefined' ? datetime : "2014-01-01 01:02:03.123456";
var datetime = new Date( datetime ).getTime();
var now = new Date().getTime();
if( isNaN(datetime) )
{
return "";
}
console.log( datetime + " " + now);
if (datetime < now) {
var milisec_diff = now - datetime;
}else{
var milisec_diff = datetime - now;
}
var days = Math.floor(milisec_diff / 1000 / 60 / (60 * 24));
var date_diff = new Date( milisec_diff );
return days + " Days "+ date_diff.getHours() + " Hours " + date_diff.getMinutes() + " Minutes " + date_diff.getSeconds() + " Seconds";
}
Tested in the Google Chrome console
(press F12)
get_time_diff()
1388534523123 1375877555722
"146 Days 12 Hours 49 Minutes 27 Seconds"
Last revision merged from trunk to branch can be found by running this command inside the working copy directory:
svn log -v --stop-on-copy
If your interested , then go with directive property . Code might looks bit tough , but itshows all the property of Angular 6 . Here am adding a sample code
import { Directive, OnInit, ElementRef, Renderer2 ,HostListener,HostBinding,Input} from '@angular/core';
import { MockNgModuleResolver } from '@angular/compiler/testing';
//import { Event } from '@angular/router';
@Directive({
selector: '[appBetterHighlight]'
})
export class BetterHighlightDirective implements OnInit {
defaultcolor :string = 'black'
Highlightedcolor : string = 'red'
@HostBinding('style.color') color : string = this.defaultcolor;
constructor(private elm : ElementRef , private render:Renderer2) { }
ngOnInit()
{}
@HostListener('mouseenter') mouseover(event :Event)
{
this.color= this.Highlightedcolor ;
}
@HostListener('mouseleave') mouseleave(event: Event)
{
this.color = this.defaultcolor;
}
}
Just use the selector name 'appBetterHighlight' anywhere in the template to access this property .
Simple way is just concatenate ""
with integer:
int i = 100;
String s = "" + i;
now s
will have 100
as string value.
From my limited experience, this happens for two main reasons:
The simple solution here is to use an error handler ending with Resume Next
If your lookup_value
is a variable you can enclose it with TRIM()
cellNum = wsFunc.VLookup(TRIM(currName), rngLook, 13, False)
The benefit is that the output of previous function is used. You do not need to repeat where the data source comes from, for example.
Here is a python 3 solution for Windows building upon the answer posted above by CyberSnoopy (using GetSystemTimePreciseAsFileTime). We borrow some code from jfs
Python datetime.utcnow() returning incorrect datetime
and get a precise timestamp (Unix time) in microseconds
#! python3
import ctypes.wintypes
def utcnow_microseconds():
system_time = ctypes.wintypes.FILETIME()
#system call used by time.time()
#ctypes.windll.kernel32.GetSystemTimeAsFileTime(ctypes.byref(system_time))
#getting high precision:
ctypes.windll.kernel32.GetSystemTimePreciseAsFileTime(ctypes.byref(system_time))
large = (system_time.dwHighDateTime << 32) + system_time.dwLowDateTime
return large // 10 - 11644473600000000
for ii in range(5):
print(utcnow_microseconds()*1e-6)
References
https://docs.microsoft.com/en-us/windows/win32/sysinfo/time-functions
https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtimepreciseasfiletime
https://support.microsoft.com/en-us/help/167296/how-to-convert-a-unix-time-t-to-a-win32-filetime-or-systemtime
If it helps anyone. You can do what the accepted answer by Infeligo has suggested but just put this extra bit in the code for a forced download.
response.setContentType("application/force-download");
You would have to call a Validator on the Entity if you want to validate it. Then you will get a set of ConstraintViolationException, which basically show for which field/s of your Entity there is a constraint violation and what exactly was it. Maybe you can also share some of the code you expect to validate your entity.
An often used technique is to do validation in @PrePersist and rollback transaction if using multiple data modifications during transaction or do other actions when you get a validation exception.
Your code should go like this:
@PrePersist
public void prePersist(SomeEntity someEntity){
Validator validator = Validation.buildDefaultValidatorFactory.getValidator();
Set<ConstraintViolation<SomeEntity>> = validator.validate(someEntity);
//do stuff with them, like notify client what was the wrong field, log them, or, if empty, be happy
}
Your live apps will not be taken down. Nothing will happen to anything that is live in the app store.
Once they formally expire, the only thing that will be impacted is your ability to sign code (and thus make new builds and provide updates).
Regarding your distribution certificate, once it expires, it simply disappears from the ‘Certificates, Identifier & Profiles’ section of Member Center. If you want to renew it before it expires, revoke the current certificate and you will get a button to request a new one.
Regarding the provisioning profile, don't worry about it before expiration, just keep using it. It's easy enough to just renew it once it expires.
The peace of mind is that nothing will happen to your live app in the store.
another example:
request:
curl -XGET http://127.0.0.1:5000/alert/dingding/test?x=y
then:
request.method: GET
request.url: http://127.0.0.1:5000/alert/dingding/test?x=y
request.base_url: http://127.0.0.1:5000/alert/dingding/test
request.url_charset: utf-8
request.url_root: http://127.0.0.1:5000/
str(request.url_rule): /alert/dingding/test
request.host_url: http://127.0.0.1:5000/
request.host: 127.0.0.1:5000
request.script_root:
request.path: /alert/dingding/test
request.full_path: /alert/dingding/test?x=y
request.args: ImmutableMultiDict([('x', 'y')])
request.args.get('x'): y
You can get this in Emacs by changing the mode. For example, here is what things look like in Whitespace mode.
import datetime
def date_generator():
cur = base = datetime.date.today()
end = base + datetime.timedelta(days=100)
delta = datetime.timedelta(days=1)
while(end>base):
base = base+delta
print base
date_generator()
I tried this and it works: ( Please replace this with the pill or tab you are using )
jQuery(document).ready(function() {
jQuery('a[data-toggle="pill"]').on('show.bs.tab', function(e) {
localStorage.setItem('activeTab', jQuery(e.target).attr('href'));
});
// Here, save the index to which the tab corresponds. You can see it
// in the chrome dev tool.
var activeTab = localStorage.getItem('activeTab');
// In the console you will be shown the tab where you made the last
// click and the save to "activeTab". I leave the console for you to
// see. And when you refresh the browser, the last one where you
// clicked will be active.
console.log(activeTab);
if (activeTab) {
jQuery('a[href="' + activeTab + '"]').tab('show');
}
});
I hope it would help somebody.
Here is the result: https://jsfiddle.net/neilbannet/ego1ncr5/5/
Simple bash
script that relies only on python
itself (I assume that in the context of the question it should be installed) and one of curl
or wget
. It has an assumption that you have setuptools
package installed to sort versions (almost always installed). It doesn't rely on external dependencies such as:
jq
which may not be present;grep
and awk
that may behave differently on Linux and macOS.curl --silent --location https://pypi.org/pypi/requests/json | python -c "import sys, json, pkg_resources; releases = json.load(sys.stdin)['releases']; print(' '.join(sorted(releases, key=pkg_resources.parse_version)))"
A little bit longer version with comments.
Put the package name into a variable:
PACKAGE=requests
Get versions (using curl
):
VERSIONS=$(curl --silent --location https://pypi.org/pypi/$PACKAGE/json | python -c "import sys, json, pkg_resources; releases = json.load(sys.stdin)['releases']; print(' '.join(sorted(releases, key=pkg_resources.parse_version)))")
Get versions (using wget
):
VERSIONS=$(wget -qO- https://pypi.org/pypi/$PACKAGE/json | python -c "import sys, json, pkg_resources; releases = json.load(sys.stdin)['releases']; print(' '.join(sorted(releases, key=pkg_resources.parse_version)))")
Print sorted versions:
echo $VERSIONS
In CakePHP 1.2 ..
$db =& ConnectionManager::getDataSource('default');
$db->showLog();
Mostly READABILITY. When reading others code, it is much more intuitive to read as NOT CONTAINS KEY !values.containsKey(NoteColumns.CREATED_DATE)
instead of reading CONTAINS KEY IS FALSE (values.containsKey(NoteColumns.CREATED_DATE) == false)
.
Under Windows, you can use
C:>dir /b /s java.exe
to print the full path of each and every "java.exe" on your C: drive, regardless of whether they are on your PATH environment variable.
Let's talk only in code with working examples. I like russ's answer above but to remove any doubt I had, I enhanced it a little bit. I ran it twice, once with the worker thread set to deamon true (deamon thread) and another time set it to false (user thread). It confirms that the deamon thread ends when the main thread terminates.
public class DeamonThreadTest {
public static void main(String[] args) {
new WorkerThread(false).start(); //set it to true and false and run twice.
try {
Thread.sleep(7500);
} catch (InterruptedException e) {
// handle here exception
}
System.out.println("Main Thread ending");
}
}
class WorkerThread extends Thread {
boolean isDeamon;
public WorkerThread(boolean isDeamon) {
// When false, (i.e. when it's a user thread),
// the Worker thread continues to run.
// When true, (i.e. when it's a daemon thread),
// the Worker thread terminates when the main
// thread terminates.
this.isDeamon = isDeamon;
setDaemon(isDeamon);
}
public void run() {
System.out.println("I am a " + (isDeamon ? "Deamon Thread" : "User Thread (none-deamon)"));
int counter = 0;
while (counter < 10) {
counter++;
System.out.println("\tworking from Worker thread " + counter++);
try {
sleep(5000);
} catch (InterruptedException e) {
// handle exception here
}
}
System.out.println("\tWorker thread ends. ");
}
}
result when setDeamon(true)
=====================================
I am a Deamon Thread
working from Worker thread 0
working from Worker thread 1
Main Thread ending
Process finished with exit code 0
result when setDeamon(false)
=====================================
I am a User Thread (none-deamon)
working from Worker thread 0
working from Worker thread 1
Main Thread ending
working from Worker thread 2
working from Worker thread 3
working from Worker thread 4
working from Worker thread 5
working from Worker thread 6
working from Worker thread 7
working from Worker thread 8
working from Worker thread 9
Worker thread ends.
Process finished with exit code 0
Well, as most of the answers pointed out, you can include the jQuery file locally as well as use Google's CDN/Microsoft CDN servers. On choosing Google vs. Microsoft CDN go Google_CDN vs. Microsoft_CDN depending on your requirement.
Generally for intranet applications include jQuery file locally and never use the CDN method since for intranet, the LAN is 10x times faster than Internet. For Internet and public facing applications use a hybrid approach as suggested by cowgod elsewhere. Also don't forget to use the nice tool JS_Compressor to compress the extra JavaScript code you add to your jQuery library. It makes JavaScript really fast.
I recently hit the same error. Some digging brought up this: http://support.microsoft.com/kb/815645
Basically, if you have spaces in the path of the .lib, that's bad. Don't know if that's what's happening for you, but seems reasonably possible.
The fix is either 1) put the lib reference in "quotes", or 2) add the lib's path to your Library Directories (Configuration Properties >> VC++ Directories).
VisualSVN for Windows has a command-line-only executable (as well Visual Studio plugins). See https://www.visualsvn.com/downloads/
It is completely portable, so no installation is necessary.
To clarify earlier answers, the HTTP protocol is 'registered' with port 80, and HTTP over SSL (aka HTTPS) is registered with port 443.
Well known port numbers are documented by IANA.
If you mean "bypass logging software" on the web server, no. It will see the traffic coming from you through the proxy system's IP address, at least. If you're trying to circumvent controls put into place by your IT department, then you need to rethink this. If your IT department blocks traffic to port 80, 8080 or 443 anywhere outbound, there is a reason. Ask your IT director. If you need access to these ports outbound from your local workstation to do your job, make your case with them.
Installing a proxy server, or using a free proxy service, may be a violation of company policies and could put your employment at risk.
JS provides the tools to do this the right way. Try the demo snippet.
var doc = document;_x000D_
var buttons = doc.getElementsByTagName('button');_x000D_
var button = buttons[0];_x000D_
_x000D_
button.addEventListener("mouseover", function(){_x000D_
this.classList.add('mouse-over');_x000D_
});_x000D_
_x000D_
button.addEventListener("mouseout", function(){_x000D_
this.classList.remove('mouse-over');_x000D_
});_x000D_
_x000D_
button.addEventListener("mousedown", function(){_x000D_
this.classList.add('mouse-down');_x000D_
});_x000D_
_x000D_
button.addEventListener("mouseup", function(){_x000D_
this.classList.remove('mouse-down');_x000D_
alert('Button Clicked!');_x000D_
});_x000D_
_x000D_
//this is unrelated to button styling. It centers the button._x000D_
var box = doc.getElementById('box');_x000D_
var boxHeight = window.innerHeight;_x000D_
box.style.height = boxHeight + 'px';
_x000D_
button{_x000D_
text-transform: uppercase;_x000D_
background-color:rgba(66, 66, 66,0.3);_x000D_
border:none;_x000D_
font-size:4em;_x000D_
color:white;_x000D_
-webkit-box-shadow: 0px 10px 5px -4px rgba(0,0,0,0.33);_x000D_
-moz-box-shadow: 0px 10px 5px -4px rgba(0,0,0,0.33);_x000D_
box-shadow: 0px 10px 5px -4px rgba(0,0,0,0.33);_x000D_
}_x000D_
button:focus {_x000D_
outline:0;_x000D_
}_x000D_
.mouse-over{_x000D_
background-color:rgba(66, 66, 66,0.34);_x000D_
}_x000D_
.mouse-down{_x000D_
-webkit-box-shadow: 0px 6px 5px -4px rgba(0,0,0,0.52);_x000D_
-moz-box-shadow: 0px 6px 5px -4px rgba(0,0,0,0.52);_x000D_
box-shadow: 0px 6px 5px -4px rgba(0,0,0,0.52); _x000D_
}_x000D_
_x000D_
/* unrelated to button styling */_x000D_
#box {_x000D_
display: flex;_x000D_
flex-flow: row nowrap ;_x000D_
justify-content: center;_x000D_
align-content: center;_x000D_
align-items: center;_x000D_
width:100%;_x000D_
}_x000D_
_x000D_
button {_x000D_
order:1;_x000D_
flex: 0 1 auto;_x000D_
align-self: auto;_x000D_
min-width: 0;_x000D_
min-height: auto;_x000D_
} _x000D_
_x000D_
_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset=utf-8 />_x000D_
<meta name="description" content="3d Button Configuration" />_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<section id="box">_x000D_
<button>_x000D_
Submit_x000D_
</button>_x000D_
</section>_x000D_
</body>_x000D_
</html>
_x000D_
For me its not text box its a span tag and this worked for me.
var len = $("span").text().length;
I followed approach as shown in code below to return a dictionary. Created a class and declared dictionary as global and created a function to add value corresponding to some keys in dictionary.
**Note have used Python 2.7 so some minor modification might be required for Python 3+
class a:
global d
d={}
def get_config(self,x):
if x=='GENESYS':
d['host'] = 'host name'
d['port'] = '15222'
return d
Calling get_config method using class instance in a separate python file:
from constant import a
class b:
a().get_config('GENESYS')
print a().get_config('GENESYS').get('host')
print a().get_config('GENESYS').get('port')
On your existing button code, simply insert this line before the procedure:
If MsgBox("This will erase everything! Are you sure?", vbYesNo) = vbNo Then Exit Sub
This will force it to quit if the user presses no.
At a minimum, change this:
function BlockID() {
var IDs = new Array();
images['s'] = "Images/Block_01.png";
images['g'] = "Images/Block_02.png";
images['C'] = "Images/Block_03.png";
images['d'] = "Images/Block_04.png";
return IDs;
}
To this:
function BlockID() {
var IDs = new Object();
IDs['s'] = "Images/Block_01.png";
IDs['g'] = "Images/Block_02.png";
IDs['C'] = "Images/Block_03.png";
IDs['d'] = "Images/Block_04.png";
return IDs;
}
There are a couple fixes to point out. First, images
is not defined in your original function, so assigning property values to it will throw an error. We correct that by changing images
to IDs
. Second, you want to return an Object
, not an Array
. An object can be assigned property values akin to an associative array or hash -- an array cannot. So we change the declaration of var IDs = new Array();
to var IDs = new Object();
.
After those changes your code will run fine, but it can be simplified further. You can use shorthand notation (i.e., object literal property value shorthand) to create the object and return it immediately:
function BlockID() {
return {
"s":"Images/Block_01.png"
,"g":"Images/Block_02.png"
,"C":"Images/Block_03.png"
,"d":"Images/Block_04.png"
};
}
You should always include all relevant code when asking a question. In this case, the print statement that is the center of your question. The print statement is probably the most crucial piece of information. The second most crucial piece of information is the error, which you also did not include. Next time, include both of those.
print $ids
should be a fairly hard statement to mess up, but it is possible. Possible reasons:
$ids
is undefined. Gives the warning undefined value in print
$ids
is out of scope. With use
strict
, gives fatal warning Global
variable $ids needs explicit package
name
, and otherwise the undefined
warning from above.print $ids $nIds
,
in which case perl thinks that $ids
is supposed to be a filehandle, and
you get an error such as print to
unopened filehandle
.Explanations
1: Should not happen. It might happen if you do something like this (assuming you are not using strict
):
my $var;
while (<>) {
$Var .= $_;
}
print $var;
Gives the warning for undefined value, because $Var
and $var
are two different variables.
2: Might happen, if you do something like this:
if ($something) {
my $var = "something happened!";
}
print $var;
my
declares the variable inside the current block. Outside the block, it is out of scope.
3: Simple enough, common mistake, easily fixed. Easier to spot with use warnings
.
4: Also a common mistake. There are a number of ways to correctly print two variables in the same print
statement:
print "$var1 $var2"; # concatenation inside a double quoted string
print $var1 . $var2; # concatenation
print $var1, $var2; # supplying print with a list of args
Lastly, some perl magic tips for you:
use strict;
use warnings;
# open with explicit direction '<', check the return value
# to make sure open succeeded. Using a lexical filehandle.
open my $fh, '<', 'file.txt' or die $!;
# read the whole file into an array and
# chomp all the lines at once
chomp(my @file = <$fh>);
close $fh;
my $ids = join(' ', @file);
my $nIds = scalar @file;
print "Number of lines: $nIds\n";
print "Text:\n$ids\n";
Reading the whole file into an array is suitable for small files only, otherwise it uses a lot of memory. Usually, line-by-line is preferred.
Variations:
print "@file"
is equivalent to
$ids = join(' ',@file); print $ids;
$#file
will return the last index
in @file
. Since arrays usually start at 0,
$#file + 1
is equivalent to scalar @file
. You can also do:
my $ids;
do {
local $/;
$ids = <$fh>;
}
By temporarily "turning off" $/
, the input record separator, i.e. newline, you will make <$fh>
return the entire file. What <$fh>
really does is read until it finds $/
, then return that string. Note that this will preserve the newlines in $ids
.
Line-by-line solution:
open my $fh, '<', 'file.txt' or die $!; # btw, $! contains the most recent error
my $ids;
while (<$fh>) {
chomp;
$ids .= "$_ "; # concatenate with string
}
my $nIds = $.; # $. is Current line number for the last filehandle accessed.
Thanks to RandomUs 1r for this observation:
changing it to display:inline-block; solves that issue. – RandomUs1r May 14 '13 at 21:59
I tried it myself for a top navigation menu bar, as follows:
First style the "li" element as follows:
display: inline-block;
width: 7em;
text-align: center;
Then style the "a"> element as follows:
width: 100%;
Now the navigation links are all equal width with text centered in each link.
Have you checked your hidden input field where the token is generated?
If it is null then your token is not returned by csrf_token function.You have to write your route that renders the form inside the middleware group provide by laravel as follows:
Route::group(['middleware' => 'web'], function () {
Route::get('/', function () {
return view('welcome');
});
Here root route contains my sign up page which requires csrf token. This token is managed by laravel 5.2.7 inside 'web' middleware in kernel.php.
Do not forget to insert {!! csrf_field() !!} inside the form..
How about you store it like this? Maybe in username:password format, so
sebastion:password123
anotheruser:password321
Then you can use list($username,$password) = explode(':',file_get_contents('users.txt'));
to parse the data on your end.
Run this inside python shell:
from distutils.sysconfig import get_python_lib
print(get_python_lib())
try this,
$("document").ready(function(){
$("your id here").trigger("click");
});
DBMS: is a software system that allows Defining, Creation, Querying, Update, and Administration of data stored in data files.
Features:
RDBMS: is a DBMS that is based on Relational model that stores data in tabular form.
Features:
In order to resolve this, Kindly go to the below path
Project-->Properties-->Application-->TargetFramework
and change the Framework to ".NET Framework 4".
Once you do this, the project will close and re-open.
This should solve the error.
Example 2 on w3schools shows what you are trying to achieve.
<?php header("Content-type:application/pdf"); // It will be called downloaded.pdf header("Content-Disposition:attachment;filename='downloaded.pdf'"); // The PDF source is in original.pdf readfile("original.pdf"); ?>
Also remember that,
It is important to notice that header() must be called before any actual output is sent (In PHP 4 and later, you can use output buffering to solve this problem)
Great news, the fix is coming in March 2018, see this link: https://developers.google.com/web/updates/2018/01/devtools
"Local Overrides let you make changes in DevTools, and keep those changes across page loads. Previously, any changes that you made in DevTools would be lost when you reloaded the page. Local Overrides work for most file types
How it works:
To set up Local Overrides:
UPDATE (March 19, 2018): It's live, detailed explanations here: https://developers.google.com/web/updates/2018/01/devtools#overrides
I can suggest the following method:
Convert the number to a string ? convert the string into an array of characters ? convert the array of characters into an array of integers
Here comes my code:
public class test {
public static void main(String[] args) {
int num1 = 123456; // Example 1
int num2 = 89786775; // Example 2
String str1 = Integer.toString(num1); // Converts num1 into String
String str2 = Integer.toString(num2); // Converts num2 into String
char[] ch1 = str1.toCharArray(); // Gets str1 into an array of char
char[] ch2 = str2.toCharArray(); // Gets str2 into an array of char
int[] t1 = new int[ch1.length]; // Defines t1 for bringing ch1 into it
int[] t2 = new int[ch2.length]; // Defines t2 for bringing ch2 into it
for(int i=0;i<ch1.length;i++) // Watch the ASCII table
t1[i]= (int) ch1[i]-48; // ch1[i] is 48 units more than what we want
for(int i=0;i<ch2.length;i++) // Watch the ASCII table
t2[i]= (int) ch2[i]-48; // ch2[i] is 48 units more than what we want
}
}
Try this one:
find . -type f -printf "%T@ %p\n" | sort -nr | cut -d\ -f2-
In my opinion, uniqueidentifier
/ GUID is neither a varchar
nor an nvarchar
but a char(36)
. Therefore I use:
CAST(xyz AS char(36))
You want the TimeSpan
struct:
TimeSpan diff = dateTime1 - dateTime2;
A TimeSpan object represents a time interval (duration of time or elapsed time) that is measured as a positive or negative number of days, hours, minutes, seconds, and fractions of a second. The TimeSpan structure can also be used to represent the time of day, but only if the time is unrelated to a particular date.
There are various methods for getting the days, hours, minutes, seconds and milliseconds back from this structure.
If you are just interested in the difference then:
TimeSpan diff = Math.Abs(dateTime1 - dateTime2);
will give you the positive difference between the times regardless of the order.
If you have just got the time component but the times could be split by midnight then you need to add 24 hours to the span to get the actual difference:
TimeSpan diff = dateTime1 - dateTime2;
if (diff < 0)
{
diff = diff + TimeSpan.FromDays(1);
}
First method
For Windows 7 and above users, Windows PowerShell give you this option. Users with windows version less than 7 can download PowerShell online and install it.
Steps:
type PowerShell in search area and click on "Windows PowerShell"
If you have a .bat (batch) file go to step 3 OR copy your commands to a file and save it with .bat extension (e.g. file.bat)
run the .bat file with following command
PS (location)> <path to bat file>/file.bat | Tee-Object -file log.txt
This will generate a log.txt file with all command prompt output in it. Advantage is that you can also the output on command prompt.
Second method
You can use file redirection (>, >>) as suggest by Bali C above.
I will recommend first method if you have lots of commands to run or a script to run. I will recommend last method if there is only few commands to run.
Another alternative is to use a UIWebView
to display the animated GIF. If the GIF is going to be fetched from a server, then this takes care of the fetching. It also works with local GIFs.
This is probably because an empty line at the end of your input file.
Try this:
for x in f:
try:
print int(x.strip(),16)
except ValueError:
print "Invalid input:", x
I found jszip quite useful. I've used so far only for reading, but they have create/edit capabilities as well.
Code wise it looks something like this
var new_zip = new JSZip();
new_zip.load(file);
new_zip.files["doc.xml"].asText() // this give you the text in the file
One thing I noticed is that it seems the file has to be in binary stream format (read using the .readAsArrayBuffer of FileReader(), otherwise I was getting errors saying I might have a corrupt zip file
Edit: Note from the 2.x to 3.0.0 upgrade guide:
The load() method and the constructor with data (new JSZip(data)) have been replaced by loadAsync().
Thanks user2677034
I'm assuming you have multiple markers that you wish to display on a google map.
The solution is two parts, one to create and populate an array containing all the details of the markers, then a second to loop through all entries in the array to create each marker.
Not know what environment you're using, it's a little difficult to provide specific help.
My best advice is to take a look at this article & accepted answer to understand the principals of creating a map with multiple markers: Display multiple markers on a map with their own info windows
From Python 2.5 onwards, you can use
from ..Modules import LDAPManager
The leading period takes you "up" a level in your heirarchy.
See the Python docs on intra-package references for imports.
Check this one (Password should be password):
<wsse:UsernameToken xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="SecurityToken-6138db82-5a4c-4bf7-915f-af7a10d9ae96">
<wsse:Username>user</wsse:Username>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">CBb7a2itQDgxVkqYnFtggUxtuqk=</wsse:Password>
<wsse:Nonce>5ABcqPZWb6ImI2E6tob8MQ==</wsse:Nonce>
<wsu:Created>2010-06-08T07:26:50Z</wsu:Created>
</wsse:UsernameToken>
ObservableCollection Caveat
Mentioned above (Said Roohullah Allem)
What makes the ObservableCollection class unique is that this class supports an event named CollectionChanged.
Keep this in mind...If you adding a large number of items to an ObservableCollection
the UI will also update that many times. This can really gum up or freeze your UI.
A work around would be to create a new list, add all the items then set your property to the new list. This hits the UI once. Again...this is for adding a large number of items.
Thanks everybody, here is the most succinct explanation I found on the MSDN site:
// y = x, unless x is null, in which case y = -1.
int y = x ?? -1;
CORS is Cross Origin Resource Sharing, you get this error if you are trying to access from one domain to another domain.
Try using JSONP. In your case, JSONP should work fine because it only uses the GET method.
Try something like this:
var url = "https://api.getevents.co/event?&lat=41.904196&lng=12.465974";
$http({
method: 'JSONP',
url: url
}).
success(function(status) {
//your code when success
}).
error(function(status) {
//your code when fails
});
I needed this as well, and with the help of Bombe's answer + some fiddling around, I got it working. Here's the recipe:
1. cd /path/to/git/localrepo
2. svn mkdir --parents protocol:///path/to/repo/PROJECT/trunk -m "Importing git repo"
3. git svn init protocol:///path/to/repo/PROJECT -s
4. git svn fetch
5. git rebase origin/trunk
5.1. git status
5.2. git add (conflicted-files)
5.3. git rebase --continue
5.4. (repeat 5.1.)
6. git svn dcommit
After #3 you'll get a cryptic message like this:
Using higher level of URL:
protocol:///path/to/repo/PROJECT => protocol:///path/to/repo
Just ignore that.
When you run #5, you might get conflicts. Resolve these by adding files with state "unmerged" and resuming rebase. Eventually, you'll be done; then sync back to the SVN repository, using dcommit
. That's all.
You can now synchronise from SVN to Git, using the following commands:
git svn fetch
git rebase trunk
And to synchronise from Git to SVN, use:
git svn dcommit
You might want to try this out on a local copy, before applying to a live repository. You can make a copy of your Git repository to a temporary place; simply use cp -r
, as all data is in the repository itself. You can then set up a file-based testing repository, using:
svnadmin create /home/name/tmp/test-repo
And check a working copy out, using:
svn co file:///home/name/tmp/test-repo svn-working-copy
That'll allow you to play around with things before making any lasting changes.
git svn init
If you accidentally run git svn init
with the wrong URL, and you weren't smart enough to take a backup of your work (don't ask ...), you can't just run the same command again. You can however undo the changes by issuing:
rm -rf .git/svn
edit .git/config
And remove the section [svn-remote "svn"]
section.
You can then run git svn init
anew.
Just use TO_DATE()
function to convert string to DATE
.
For Example:
create table Customer(
CustId int primary key,
CustName varchar(20),
DOB date);
insert into Customer values(1,'Vishnu', TO_DATE('1994/12/16 12:00:00', 'yyyy/mm/dd hh:mi:ss'));
I came across another solution to use the Google play services on an emulator. The guys at http://www.genymotion.com/ provide very fast emulators on which you can install Google play services. They just need you to sign up to begin downloading and you need Virtual box installed. At the moment they cater for Android 16 and 17 but more are on the way.
Just cast your double to a float.
double d = getInfoValueNumeric();
float f = (float)d;
Also notice that the primitive types can NOT store an infinite set of numbers:
float range: from 1.40129846432481707e-45 to 3.40282346638528860e+38
double range: from 1.7e–308 to 1.7e+308
Did you compile with Eclipse? It uses a different compiler (not javac). That should not result in this error (if everything is configured properly), but you can try to compile it with javac instead.
If that fixed the problem, try to see if Eclipse has some incorrect compiler settings. Specifically have it target Java 5.
Comparison expressions should each be in their own brackets:
{% if (a == 'foo') or (b == 'bar') %}
...
{% endif %}
Alternative if you are inspecting a single variable and a number of possible values:
{% if a in ['foo', 'bar', 'qux'] %}
...
{% endif %}
if you like to display that time in seconds:
<?php
class debugTimer
{
private $startTime;
private $callsCounter;
function __construct()
{
$this->startTime = microtime(true);
$this->callsCounter = 0;
}
public function getTimer(): float
{
$timeEnd = microtime(true);
$time = $timeEnd - $this->startTime;
$this->callsCounter++;
return $time;
}
public function getCallsNumber(): int
{
return $this->callsCounter;
}
}
$timer = new debugTimer();
usleep(100);
echo '<br />\n
' . $timer->getTimer() . ' seconds before call #' . $timer->getCallsNumber();
usleep(100);
echo '<br />\n
' . $timer->getTimer() . ' seconds before call #' . $timer->getCallsNumber();
replace all the \
with \\
.
it's trying to escape the next character in this case the U
so to insert a \
you need to insert an escaped \
which is \\
my_list = sorted(dict.items(), key=lambda x: x[1])
While you can in theory Integer.MAX_VALUE characters, the JVM is limited in the size of the array it can use.
public static void main(String... args) {
for (int i = 0; i < 4; i++) {
int len = Integer.MAX_VALUE - i;
try {
char[] ch = new char[len];
System.out.println("len: " + len + " OK");
} catch (Error e) {
System.out.println("len: " + len + " " + e);
}
}
}
on Oracle Java 8 update 92 prints
len: 2147483647 java.lang.OutOfMemoryError: Requested array size exceeds VM limit
len: 2147483646 java.lang.OutOfMemoryError: Requested array size exceeds VM limit
len: 2147483645 OK
len: 2147483644 OK
Note: in Java 9, Strings will use byte[] which will mean that multi-byte characters will use more than one byte and reduce the maximum further. If you have all four byte code-points e.g. emojis, you will only get around 500 million characters
Most Subversion commands take the --username
option to specify the username you want to use to the repository. Subversion remembers the last repository username and password used in each working copy, which means, among other things, that if you use svn checkout --username myuser
you never need to specify the username again.
As Kamil Kisiel says, when Subversion is accessing the repository directly off the file system (that is, the repository URL is of form file:///path/to/repo
or file://file-server/path/to/repo
), it uses your file system permissions to access the repository. And when you connect via SSH tunneling (svn+ssh://server/path/to/repo
), SVN uses your FS permissions on the server, as determined by your SSH login. In those cases, svn checkout --username
may not work for your repository.
As of 18/05/2016 Firebase is Google's unified platform for mobile developers including push notifications.
It's not much of an answer, but you might need to go old school and capture an image snapshot of the IIS process and debug it. You might also want to check out Tess Ferrandez's blog - she is a kick a** microsoft escalation engineer and her blog focuses on debugging windows ASP.NET, but the blog is relevant to windows debugging in general. If you select the ASP.NET tag (which is what I've linked to) then you'll see several items that are similar.
I had a similar issue, mine was caused by a mismatch between the UID of the host and the UID of the container's user. The fix was to pass the UID of the user as an argument to the docker build and create the container's user with the same UID.
In the DockerFile:
ARG UID=1000
ENV USER="ubuntu"
RUN useradd -u $UID -ms /bin/bash $USER
In the build step:
docker build <path/to/Dockerfile> -t <tag/name> --build-arg UID=$UID
After that, running the container and commands as per the OP gave me the expected result.
Google used to recommend putting it just before the </body>
tag, because the original method they provided for loading ga.js
was blocking. The newer async syntax, though, can safely be put in the head with minimal blockage, so the current recommendation is just before the </head>
tag.
<head>
will add a little latency; in the footer will reduce the number of pageviews recorded at some small margin. It's a tradeoff. ga.js
is heavily cached and present on a large percentage of sites across the web, so its often served from the cache, reducing latency to almost nil.
As a matter of personal preference, I like to include it in the <head>
, but its really a matter of preference.
I prefer to use the @ symbol so I see the query exactly as I can copy and paste into a query file:
string name = "Joe";
string gender = "M";
string query = String.Format(@"
SELECT
*
FROM
tableA
WHERE
Name = '{0}' AND
Gender = '{1}'", name, gender);
It's really great with long complex queries. Nice thing is it keeps tabs and line feeds so pasting into a query browser retains the nice formatting
Try invoking your command with Invoke-Expression
:
Invoke-Expression $cmd1
Here is a working example on my machine:
$cmd = "& 'C:\Program Files\7-zip\7z.exe' a -tzip c:\temp\test.zip c:\temp\test.txt"
Invoke-Expression $cmd
iex
is an alias for Invoke-Expression
so you could do:
iex $cmd1
For a full list :
Visit https://ss64.com/ps/ for more Powershell
stuff.
Good Luck...
If you aren't comfortable with using negative margins, check this out.
div {
position: fixed;
left: 50%;
bottom: 20px;
transform: translate(-50%, -50%);
margin: 0 auto;
}
<div>
Your Text
</div>
Especially useful when you don't know the width of the div.
align="center"
has no effect.
Since you have position:absolute
, I would recommend positioning it 50% from the left and then subtracting half of its width from its left margin.
#manipulate {
position:absolute;
width:300px;
height:300px;
background:#063;
bottom:0px;
right:25%;
left:50%;
margin-left:-150px;
}
I'd like to comment on Wikipedia's definition of virtual, as repeated by several here. [At the time this answer was written,] Wikipedia defined a virtual method as one that can be overridden in subclasses. [Fortunately, Wikipedia has been edited since, and it now explains this correctly.] That is incorrect: any method, not just virtual ones, can be overridden in subclasses. What virtual does is to give you polymorphism, that is, the ability to select at run-time the most-derived override of a method.
Consider the following code:
#include <iostream>
using namespace std;
class Base {
public:
void NonVirtual() {
cout << "Base NonVirtual called.\n";
}
virtual void Virtual() {
cout << "Base Virtual called.\n";
}
};
class Derived : public Base {
public:
void NonVirtual() {
cout << "Derived NonVirtual called.\n";
}
void Virtual() {
cout << "Derived Virtual called.\n";
}
};
int main() {
Base* bBase = new Base();
Base* bDerived = new Derived();
bBase->NonVirtual();
bBase->Virtual();
bDerived->NonVirtual();
bDerived->Virtual();
}
What is the output of this program?
Base NonVirtual called.
Base Virtual called.
Base NonVirtual called.
Derived Virtual called.
Derived overrides every method of Base: not just the virtual one, but also the non-virtual.
We see that when you have a Base-pointer-to-Derived (bDerived), calling NonVirtual calls the Base class implementation. This is resolved at compile-time: the compiler sees that bDerived is a Base*, that NonVirtual is not virtual, so it does the resolution on class Base.
However, calling Virtual calls the Derived class implementation. Because of the keyword virtual, the selection of the method happens at run-time, not compile-time. What happens here at compile-time is that the compiler sees that this is a Base*, and that it's calling a virtual method, so it insert a call to the vtable instead of class Base. This vtable is instantiated at run-time, hence the run-time resolution to the most-derived override.
I hope this wasn't too confusing. In short, any method can be overridden, but only virtual methods give you polymorphism, that is, run-time selection of the most derived override. In practice, however, overriding a non-virtual method is considered bad practice and rarely used, so many people (including whoever wrote that Wikipedia article) think that only virtual methods can be overridden.
I faced same issue when I ran following commands
vagrant init
vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Box 'base' could not be found. Attempting to find and install...
default: Box Provider: virtualbox
default: Box Version: >= 0
==> default: Box file was not detected as metadata. Adding it directly...
==> default: Adding box 'base' (v0) for provider: virtualbox
default: Downloading: base
An error occurred while downloading the remote file. The error
message, if any, is reproduced below. Please fix this error and try
again.
Couldn't open file /home/...../base
I corrected with
>vagrant init laravel/homestead
>Vagrant up
It worked for me.
Happy coding