As of November 17, 2015. This rule has officially changed. Instagram has deprecated the rule against using their API to upload images.
Good luck.
WinMount provides an easiest way to mount VMDK as a virtual disk. You can read or write to the vmdk file without loading the virtual system. Here shows you how to do: http://www.winmount.com/mount_vmdk.html
to convert CString to std::string
. You can use this format.
std::string sText(CW2A(CSText.GetString(), CP_UTF8 ));
The format you use for the date doesn't match to Oracle's default date format.
A default installation of Oracle Database sets the DEFAULT DATE FORMAT to dd-MMM-yyyy
.
Either use the function TO_DATE(dateStr, formatStr)
or simply use dd-MMM-yyyy
date format model.
Map function is fast way to convert big collection
from time import time
cursor = db.collection.find()
def f(x):
return x['name']
t1 = time()
blackset = set(map(f, cursor))
print(time() - t1)
Here you have example how to set the readonly attribute:
<form action="demo_form.asp">_x000D_
Country: <input type="text" name="country" value="Norway" readonly><br>_x000D_
<input type="submit" value="Submit">_x000D_
</form>
_x000D_
Be sure to have this startup script enabled : ( Preferences > Console > Advanced Options )
/usr/lib/python2.7/dist-packages/spyderlib/scientific_startup.py
If the standard PYTHONSTARTUP is enabled you won't have an interactive plot
If you're okay with Apache commons lib
outputWriter.write(ArrayUtils.join(array, ","));
There are some easy steps to make Dump file of your Tables,Users and Procedures:
Goto sqlplus or any sql*plus
connect by your username or password
There doesn't seem to be a static valueOf
method for this, which is a bit surprising.
One rather ugly, but simple, way, would be to iterate over Locale.getAvailableLocales()
, comparing their toString
values with your value.
Not very nice, but no string parsing required. You could pre-populate a Map
of Strings to Locales, and look up your database string in that Map.
For the macOS Catalina 10.15.3 and onwards iTunes is no longer present in the system. all iTunes contents are added in Finder itself. So instead, open Music app and drag drop IPA as mentioned below.
Delete Temp files by run > %temp%
And Open VS2015 by run as admin,
it works for me.
Here's a good discussion on this:
Basically you should
Pass the File object to the constructor PrintWriter(File file)
:
PrintWriter printWriter = new PrintWriter(file);
tfe answered this question in another post on StackOverflow: Answered
Another method would be to use:
$(document).bind("touchmove",function(event){
event.preventDefault();
});
But it may prevent some of the jquery mobile functionality from working properly.
WebApiConfig is the place where you can configure whether you want to output in json or xml. By default, it is xml. In the register function, we can use HttpConfiguration Formatters to format the output.
System.Net.Http.Headers => MediaTypeHeaderValue("text/html")
is required to get the output in the json format.
Another way could be the following:
virtual const ULONG Write(ULONG &State, bool sequence = true);
// wrapper
const ULONG Write(bool sequence = true)
{
ULONG dummy;
return Write(dummy, sequence);
}
then the following calls are possible:
ULONG State;
object->Write(State, false); // sequence is false, "returns" State
object->Write(State); // assumes sequence = true, "returns" State
object->Write(false); // sequence is false, no "return"
object->Write(); // assumes sequence = true, no "return"
window.location.href, this as saved my life in webview from Android 5.1. The page don't reload with location.reload() in this version from Android.
I would like to add that there's an eval function in jQuery allowing you to eval the code globally which should get you rid of any contextual problems. The function is called globalEval() and it worked great for my purposes. Its documentation can be found here.
This is the example code provided by the jQuery API documentation:
function test()
{
jQuery.globalEval("var newVar = true;")
}
test();
// newVar === true
This function is extremely useful when it comes to loading external scripts dynamically which you apparently were trying to do.
There are two problems with your attempt.
First, you've used n+1
instead of i+1
, so you're going to return something like [5, 5, 5, 5]
instead of [1, 2, 3, 4]
.
Second, you can't for
-loop over a number like n
, you need to loop over some kind of sequence, like range(n)
.
So:
def naturalNumbers(n):
return [i+1 for i in range(n)]
But if you already have the range
function, you don't need this at all; you can just return range(1, n+1)
, as arshaji showed.
So, how would you build this yourself? You don't have a sequence to loop over, so instead of for
, you have to build it yourself with while
:
def naturalNumbers(n):
results = []
i = 1
while i <= n:
results.append(i)
i += 1
return results
Of course in real-life code, you should always use for
with a range
, instead of doing things manually. In fact, even for this exercise, it might be better to write your own range
function first, just to use it for naturalNumbers
. (It's already pretty close.)
There is one more option, if you want to get clever.
If you have a list, you can slice it. For example, the first 5 elements of my_list
are my_list[:5]
. So, if you had an infinitely-long list starting with 1
, that would be easy. Unfortunately, you can't have an infinitely-long list… but you can have an iterator that simulates one very easily, either by using count
or by writing your own 2-liner equivalent. And, while you can't slice an iterator, you can do the equivalent with islice
. So:
from itertools import count, islice
def naturalNumbers(n):
return list(islice(count(1), n))
First I needed to remote into my server with ssh. If someone has a non ssh way of doing this please post.
I found my bare repositories at
cd /var/opt/gitlab/git-data/repositories/group-name/project-name.git
used
git branch
to see the wrong active branch
git symbolic-ref HEAD refs/heads/master
to change the master to to be the branch called master then use the web interface and "git branch" to confirm.
To make it more generic of keeping both columns in df1
and df2
:
import pyspark.sql.functions as F
# Keep all columns in either df1 or df2
def outter_union(df1, df2):
# Add missing columns to df1
left_df = df1
for column in set(df2.columns) - set(df1.columns):
left_df = left_df.withColumn(column, F.lit(None))
# Add missing columns to df2
right_df = df2
for column in set(df1.columns) - set(df2.columns):
right_df = right_df.withColumn(column, F.lit(None))
# Make sure columns are ordered the same
return left_df.union(right_df.select(left_df.columns))
You can check the HTTP_USER_AGENT server variable. The user agent transfered by IE contains MSIE
if(strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false) { ... }
For specific versions you can extend your condition
if(strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 6.') !== false) { ... }
Also see this related question.
Switch to AppCompatActivity and add a 25 dp paddingTop on the toolbar and turn on
<item name="android:windowTranslucentStatus">true</item>
Then, the will toolbar go up top the top
var time = moment().toDate(); // This will return a copy of the Date that the moment uses
time.setHours(0);
time.setMinutes(0);
time.setSeconds(0);
time.setMilliseconds(0);
There are five ways to convert The First Way :
String str = " 123" ;
int i = Integer.parse(str);
output : 123
The second way :
String str = "hello123world";
int i = Integer.parse(str.replaceAll("[\\D]" , "" ) );
output : 123
The Third Way :
String str"123";
int i = new Integer(str);
output "123
The Fourth Way :
String str"123";
int i = Integer.valueOf(Str);
output "123
The Fifth Way :
String str"123";
int i = Integer.decode(str);
output "123
There could be other ways But that's what I remember now
I've been using this code to instantiate my custom segue subclass and run it programmatically. It seems to work. Anything wrong with this? I'm puzzled, reading all the other answers saying it cannot be done.
UIViewController *toViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"OtherViewControllerId"];
MyCustomSegue *segue = [[MyCustomSegue alloc] initWithIdentifier:@"" source:self destination:toViewController];
[self prepareForSegue:segue sender:sender];
[segue perform];
All above answers and other online posts mention following:
What they have not told us is how to achieve it. For part of the program to be more declarative, other parts must provide the abstraction to hide the implementation details (which are the imperative codes).
list.Where()
to get a new filtered list. For this to work, Microsoft has done all the heavy lifting behind the LINQ abstraction.In fact, one of the reason functional programming and functional libraries are more declarative is because they have abstracted away loops and list creations, hiding all the implementation details (most likely imperative codes with loops) behind the scene.
In any program, you will always have both imperative and declarative codes, what you should aim for is to hide all imperative codes behind the domain-specific abstractions, so that other parts of the program can use them declaratively.
Finally, although functional programming and LINQ can make your program more declarative, you can always make it even more declarative by providing more abstractions. For example:
// JavaScript example
// Least declarative
const bestProducts = [];
for(let i = 0; i < products.length; i++) {
let product = products[i];
if (product.rating >= 5 && product.price < 100) {
bestProducts.push(product);
}
}
// More declarative
const bestProducts = products.filter(function(product) {
return product.rating >= 5 && product.price < 100;
});
// Most declarative, implementation details are hidden in a function
const bestProducts = getBestProducts();
P.S. the extreme of declarative programming is to invent new domain specific languages (DSL):
<form>
<input
type="text"
name="company_name"
oninvalid="this.setCustomValidity('Lütfen isaretli yerleri doldurunuz')"
required
/><input type="submit" />
</form>
_x000D_
Use
white-space: pre-line;
It will prevent text from flowing out of the div
. It will break the text as it reaches the end of the div
.
Based on the answer of https://stackoverflow.com/a/31837264/4360308 I've implemented this functionality with Nodejs (+ express + cheerio) as follows:
HTML (index.html)
<div class="include" data-include="componentX" data-method="append"></div>
<div class="include" data-include="componentX" data-method="replace"></div>
JS
function includeComponents($) {
$('.include').each(function () {
var file = 'view/html/component/' + $(this).data('include') + '.html';
var dataComp = fs.readFileSync(file);
var htmlComp = dataComp.toString();
if ($(this).data('method') == "replace") {
$(this).replaceWith(htmlComp);
} else if ($(this).data('method') == "append") {
$(this).append(htmlComp);
}
})
}
function foo(){
fs.readFile('./view/html/index.html', function (err, data) {
if (err) throw err;
var html = data.toString();
var $ = cheerio.load(html);
includeComponents($);
...
}
}
append -> includes the content into the div
replace -> replaces the div
you could easily add more behaviours following the same design
Go to the Debug menu and select Options and uncheck "Redirect all Output Window text to Immediate Window"
jQuery's CSS manipulation isn't queued, but you can make it executed inside the 'fx' queue by doing:
$('#div').delay(1000).queue('fx', function() { $(this).removeClass('error'); });
Quite same thing as calling setTimeout but uses jQuery's queue mecanism instead.
If are you working with numbers a lot, you might want to take a look at NumPy. It lets you perform all kinds of operation directly on numerical arrays. For example:
>>> import numpy
>>> array = numpy.array([49, 51, 53, 56])
>>> array - 13
array([36, 38, 40, 43])
When entered as the reference of a Named range
, it refers to range on the sheet the named range is used on.
For example, create a named range MyName
refering to =SUM(!B1:!K1)
Place a formula on Sheet1
=MyName
. This will sum Sheet1!B1:K1
Now place the same formula (=MyName
) on Sheet2
. That formula will sum Sheet2!B1:K1
Note: (as pnuts commented) this and the regular SheetName!B1:K1
format are relative, so reference different cells as the =MyName
formula is entered into different cells.
From kafka 1.1
Purge a topic
bin/kafka-configs.sh --zookeeper localhost:2181 --alter --entity-type topics --entity-name tp_binance_kline --add-config retention.ms=100
wait 1 minute, to be secure that kafka purge the topic remove the configuration, and then go to default value
bin/kafka-configs.sh --zookeeper localhost:2181 --alter --entity-type topics --entity-name tp_binance_kline --delete-config retention.ms
As of 2016 you can also use the tidyverse
.
library(tidyverse)
samp %>% remove_rownames %>% column_to_rownames(var="names")
If you're looking for a more generic method:
public static List<U> FindDuplicates<T, U>(this List<T> list, Func<T, U> keySelector)
{
return list.GroupBy(keySelector)
.Where(group => group.Count() > 1)
.Select(group => group.Key).ToList();
}
EDIT: Here's an example:
public class Person {
public string Name {get;set;}
public int Age {get;set;}
}
List<Person> list = new List<Person>() { new Person() { Name = "John", Age = 22 }, new Person() { Name = "John", Age = 30 }, new Person() { Name = "Jack", Age = 30 } };
var duplicateNames = list.FindDuplicates(p => p.Name);
var duplicateAges = list.FindDuplicates(p => p.Age);
foreach(var dupName in duplicateNames) {
Console.WriteLine(dupName); // Will print out John
}
foreach(var dupAge in duplicateAges) {
Console.WriteLine(dupAge); // Will print out 30
}
This may be helpful:
rename.columns=function(df,changelist){
#renames columns of a dataframe
for(i in 1:length(names(df))){
if(length(changelist[[names(df)[i]]])>0){
names(df)[i]= changelist[[names(df)[i]]]
}
}
df
}
# Specify new dataframe
df=rename.columns(df,list(old.column='new.column.name'))
There is some incorrect information in this thread. I copied and pasted the incorrect information:
LEFT OUTER JOIN
SELECT * FROM A, B WHERE A.column = B.column(+)
RIGHT OUTER JOIN
SELECT * FROM A, B WHERE B.column(+) = A.column
The above is WRONG!!!!! It's reversed. How I determined it's incorrect is from the following book:
Oracle OCP Introduction to Oracle 9i: SQL Exam Guide. Page 115 Table 3-1 has a good summary on this. I could not figure why my converted SQL was not working properly until I went old school and looked in a printed book!
Here is the summary from this book, copied line by line:
Oracle outer Join Syntax:
from tab_a a, tab_b b,
where a.col_1 + = b.col_1
ANSI/ISO Equivalent:
from tab_a a left outer join
tab_b b on a.col_1 = b.col_1
Notice here that it's the reverse of what is posted above. I suppose it's possible for this book to have errata, however I trust this book more so than what is in this thread. It's an exam guide for crying out loud...
Expression -- from the New Oxford American Dictionary:
expression: Mathematics a collection of symbols that jointly express a quantity : the expression for the circumference of a circle is 2pr.
In gross general terms: Expressions produce at least one value.
In Python, expressions are covered extensively in the Python Language Reference In general, expressions in Python are composed of a syntactically legal combination of Atoms, Primaries and Operators.
Python expressions from Wikipedia
Examples of expressions:
Literals and syntactically correct combinations with Operators and built-in functions or the call of a user-written functions:
>>> 23
23
>>> 23l
23L
>>> range(4)
[0, 1, 2, 3]
>>> 2L*bin(2)
'0b100b10'
>>> def func(a): # Statement, just part of the example...
... return a*a # Statement...
...
>>> func(3)*4
36
>>> func(5) is func(a=5)
True
Statement from Wikipedia:
In computer programming a statement can be thought of as the smallest standalone element of an imperative programming language. A program is formed by a sequence of one or more statements. A statement will have internal components (e.g., expressions).
Python statements from Wikipedia
In gross general terms: Statements Do Something and are often composed of expressions (or other statements)
The Python Language Reference covers Simple Statements and Compound Statements extensively.
The distinction of "Statements do something" and "expressions produce a value" distinction can become blurry however:
if
is usually a statement, such as if x<0: x=0
but you can also have a conditional expression like x=0 if x<0 else 1
that are expressions. In other languages, like C, this form is called an operator like this x=x<0?0:1;
def func(a): return a*a
is an expression when used but made up of statements when defined. None
is a procedure in Python: def proc(): pass
Syntactically, you can use proc()
as an expression, but that is probably a bug...func(x=2);
Is that an Expression or Statement? (Answer: Expression used as a Statement with a side-effect.) The assignment statement of x=2
inside of the function call of func(x=2)
in Python sets the named argument a
to 2 only in the call to func
and is more limited than the C example. The answers given here didn't fully convince me. So instead, I make another example.
public void passOn(Consumer<Animal> consumer, Supplier<Animal> supplier) {
consumer.accept(supplier.get());
}
sounds fine, doesn't it? But you can only pass Consumer
s and Supplier
s for Animal
s. If you have a Mammal
consumer, but a Duck
supplier, they should not fit although both are animals. In order to disallow this, additional restrictions have been added.
Instead of the above, we have to define relationships between the types we use.
E. g.,
public <A extends Animal> void passOn(Consumer<A> consumer, Supplier<? extends A> supplier) {
consumer.accept(supplier.get());
}
makes sure that we can only use a supplier which provides us the right type of object for the consumer.
OTOH, we could as well do
public <A extends Animal> void passOn(Consumer<? super A> consumer, Supplier<A> supplier) {
consumer.accept(supplier.get());
}
where we go the other way: we define the type of the Supplier
and restrict that it can be put into the Consumer
.
We even can do
public <A extends Animal> void passOn(Consumer<? super A> consumer, Supplier<? extends A> supplier) {
consumer.accept(supplier.get());
}
where, having the intuitive relations Life
-> Animal
-> Mammal
-> Dog
, Cat
etc., we could even put a Mammal
into a Life
consumer, but not a String
into a Life
consumer.
This is how I do it if I need a form displayed for each item, and inputs for various properties. Really depends on what I'm trying to do though.
ViewModel looks like this:
public class MyViewModel
{
public List<Person> Persons{get;set;}
}
View(with BeginForm of course):
@model MyViewModel
@for( int i = 0; i < Model.Persons.Count(); ++i)
{
@Html.HiddenFor(m => m.Persons[i].PersonId)
@Html.EditorFor(m => m.Persons[i].FirstName)
@Html.EditorFor(m => m.Persons[i].LastName)
}
Action:
[HttpPost]public ViewResult(MyViewModel vm)
{
...
Note that on post back only properties which had inputs available will have values. I.e., if Person had a .SSN property, it would not be available in the post action because it wasn't a field in the form.
Note that the way MVC's model binding works, it will only look for consecutive ID's. So doing something like this where you conditionally hide an item will cause it to not bind any data after the 5th item, because once it encounters a gap in the IDs, it will stop binding. Even if there were 10 people, you would only get the first 4 on the postback:
@for( int i = 0; i < Model.Persons.Count(); ++i)
{
if(i != 4)//conditionally hide 5th item,
{ //but BUG occurs on postback, all items after 5th will not be bound to the the list
@Html.HiddenFor(m => m.Persons[i].PersonId)
@Html.EditorFor(m => m.Persons[i].FirstName)
@Html.EditorFor(m => m.Persons[i].LastName)
}
}
Your syntax is fine, it will return rows where LastAdDate
lies within the last 6 months;
select cast('01-jan-1970' as datetime) as LastAdDate into #PubAdvTransData
union select GETDATE()
union select NULL
union select '01-feb-2010'
DECLARE @sp_Date DATETIME = DateAdd(m, -6, GETDATE())
SELECT * FROM #PubAdvTransData pat
WHERE (pat.LastAdDate > @sp_Date)
>2010-02-01 00:00:00.000
>2010-04-29 21:12:29.920
Are you sure LastAdDate
is of type DATETIME
?
For Hibernate as provider which is most common IMHO:
In case of build tools like Gradle, Maven you need to have Hibernate JPA 2 Metamodel Generator jar in the classpath and compiler level>=1.6 that is all you need build the project and metamodel will be generated automatically.
In case of IDE Eclipse 1. goto Project->Properties->Java Compiler->Annotation Processing and enable it. 2. Expand Annotation Processing->Factory Path-> Add External Jar add Hibernate JPA 2 Metamodel Generator jar check the newly added jar and say OK. Clean and Build done!
Link Hibernate JPA 2 Metamodel Generator jar link from maven repo https://mvnrepository.com/artifact/org.hibernate/hibernate-jpamodelgen
Another version which is simple
BiFunction<TreeSet<Employee>,List<Employee> ,TreeSet<Employee>> appendTree = (y,x) -> (y.addAll(x))? y:y;
TreeSet<Employee> outputList = appendTree.apply(new TreeSet<Employee>(Comparator.comparing(p->p.getId())),personList);
import numpy as np
my_list = ['0.49', '0.54', '0.54', '0.54', '0.54', '0.54', '0.55', '0.54', '0.54', '0.54', '0.55', '0.55', '0.55', '0.54', '0.55', '0.55', '0.54',
'0.55', '0.55', '0.54']
print(type(my_list), type(my_list[0]))
# <class 'list'> <class 'str'>
which displays the type as a list of strings. You can convert this list to an array of floats simultaneously using numpy:
my_list = np.array(my_list).astype(np.float)
print(type(my_list), type(my_list[0]))
# <class 'numpy.ndarray'> <class 'numpy.float64'>
You cannot open new fragments. Fragments need to be always hosted by an activity. If the fragment is in the same activity (eg tabs) then the back key navigation is going to be tricky I am assuming that you want to open a new screen with that fragment.
So you would simply create a new activity and put the new fragment in there. That activity would then react to the intent either explicitly via the activity class or implicitly via intent filter
s.
you need to include the Wordpress loop in your search.php this is example
search.php template file:
<?php get_header(); ?>
<?php
$s=get_search_query();
$args = array(
's' =>$s
);
// The Query
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
_e("<h2 style='font-weight:bold;color:#000'>Search Results for: ".get_query_var('s')."</h2>");
while ( $the_query->have_posts() ) {
$the_query->the_post();
?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php
}
}else{
?>
<h2 style='font-weight:bold;color:#000'>Nothing Found</h2>
<div class="alert alert-info">
<p>Sorry, but nothing matched your search criteria. Please try again with some different keywords.</p>
</div>
<?php } ?>
<?php get_sidebar(); ?>
<?php get_footer(); ?>
ArrayList: The ArrayList class extends AbstractList and implements the List interface and RandomAccess (marker interface). ArrayList supports dynamic arrays that can grow as needed. It gives us first iteration over elements.
LinkedList: A LinkedList is ordered by index position, like ArrayList, except that the elements are doubly-linked to one another. This linkage gives you new methods (beyond what you get from the List interface) for adding and removing from the beginning or end, which makes it an easy choice for implementing a stack or queue. Keep in mind that a LinkedList may iterate more slowly than an ArrayList, but it's a good choice when you need fast insertion and deletion. As of Java 5, the LinkedList class has been enhanced to implement the java.util.Queue interface. As such, it now supports the common queue methods: peek (), poll (), and offer ().
Usage depends on whether the component's parent has a layout manager or not.
setSize()
-- use when a parent layout manager does not exist;setPreferredSize()
(also its related setMinimumSize
and setMaximumSize
) -- use when a parent layout manager exists.The setSize()
method probably won't do anything if the component's parent is using a layout manager; the places this will typically have an effect would be on top-level components (JFrame
s and JWindow
s) and things that are inside of scrolled panes. You also must call setSize()
if you've got components inside a parent without a layout manager.
Generally, setPreferredSize()
will lay out the components as expected if a layout manager is present; most layout managers work by getting the preferred (as well as minimum and maximum) sizes of their components, then using setSize()
and setLocation()
to position those components according to the layout's rules.
For example, a BorderLayout
tries to make the bounds of its "north" region equal to the preferred size of its north component---they may end up larger or smaller than that, depending on the size of the JFrame
, the size of the other components in the layout, and so on.
This is because the content of
<p myHighlight>Highlight me!</p>
has not been rendered when the constructor of the HighlightDirective is called so there is no content yet.
If you implement the AfterContentInit hook you will get the element and its content.
import { Directive, ElementRef, AfterContentInit } from '@angular/core';
@Directive({ selector: '[myHighlight]' })
export class HighlightDirective {
constructor(private el: ElementRef) {
//el.nativeElement.style.backgroundColor = 'yellow';
}
ngAfterContentInit(){
//you can get to the element content here
//this.el.nativeElement
}
}
$(this).parents('div').attr('id');
Here is a procedure and code using generated ProjectInstaller
in Visual Studio:
ProjectInstaller
in design editor (it should open automatically when installer is created) and set properties of generated serviceProcessInstaller1
(e.g. Account: LocalSystem) and serviceInstaller1
(e.g. StartType: Automatic)ProjectInstaller
in code editor (press F7
in design editor) and add event handler to ServiceInstaller.AfterInstall
- see the following code. It will start the service after its installation.ProjectInstaller class:
using System.ServiceProcess;
[RunInstaller(true)]
public partial class ProjectInstaller : System.Configuration.Install.Installer
{
public ProjectInstaller()
{
InitializeComponent(); //generated code including property settings from previous steps
this.serviceInstaller1.AfterInstall += Autorun_AfterServiceInstall; //use your ServiceInstaller name if changed from serviceInstaller1
}
void Autorun_AfterServiceInstall(object sender, InstallEventArgs e)
{
ServiceInstaller serviceInstaller = (ServiceInstaller)sender;
using (ServiceController sc = new ServiceController(serviceInstaller.ServiceName))
{
sc.Start();
}
}
}
If you are using this for Angular, then export a function via a named export. Such as:
function someFunc(){}
export { someFunc as someFuncName }
otherwise, Angular will complain that object is not a function.
ifneq ("$(wildcard $(PATH_TO_FILE))","")
FILE_EXISTS = 1
else
FILE_EXISTS = 0
endif
This solution posted above works best. But make sure that you do not stringify the PATH_TO_FILE assignment E.g.,
PATH_TO_FILE = "/usr/local/lib/libhl++.a" # WILL NOT WORK
It must be
PATH_TO_FILE = /usr/local/lib/libhl++.a
var i = 1;
while( ( n /= 10 ) >= 1 ){ i++ }
23432 i = 1
2343.2 i = 2
234.32 i = 3
23.432 i = 4
2.3432 i = 5
0.23432
You shouldn't be setting the value of the input through refs.
Take a look at the documentation for controlled form components here - https://facebook.github.io/react/docs/forms.html#controlled-components
In a nutshell
<input value={this.state.value} onChange={(e) => this.setState({value: e.target.value})} />
Then you will be able to control the disabled state by using disabled={!this.state.value}
For the current information you are giving, it will be enought with this simple regex to do the replacement:
str.replaceAll(",", ".");
The getRequestURL()
omits the port when it is 80 while the scheme is http
, or when it is 443 while the scheme is https
.
So, just use getRequestURL()
if all you want is obtaining the entire URL. This does however not include the GET query string. You may want to construct it as follows then:
StringBuffer requestURL = request.getRequestURL();
if (request.getQueryString() != null) {
requestURL.append("?").append(request.getQueryString());
}
String completeURL = requestURL.toString();
Google Play services Integration in Android studio.
Step 1:
SDK manager->Tools Update this
1.Google play services
2.Android Support Repository
Step 2:
chance in build.gradle
defaultConfig {
minSdkVersion 8
targetSdkVersion 19
versionCode 1
versionName "1.0"
}
dependencies {
compile 'com.android.support:appcompat-v7:+'
compile 'com.google.android.gms:play-services:4.0.+'
}
Step 3:
android.manifest.xml
<uses-sdk
android:minSdkVersion="8" />
Step 4:
Sync project file with grandle.
wait for few minute.
Step 5:
File->Project Structure find error with red bulb images,click on go to add dependencies select your app module.
Save
Please put comment if you have require help. Happy coding.
I'd like to clarify a few things:
pandas.Series.tolist()
. I'm not sure why the top voted answer
leads off with using pandas.Series.values.tolist()
since as far as I can tell, it adds syntax/confusion with no added benefit.tst[lookupValue][['SomeCol']]
is a dataframe (as stated in the
question), not a series (as stated in a comment to the question). This is because tst[lookupValue]
is a dataframe, and slicing it with [['SomeCol']]
asks for
a list of columns (that list that happens to have a length of 1), resulting in a dataframe being returned. If you
remove the extra set of brackets, as in
tst[lookupValue]['SomeCol']
, then you are asking for just that one
column rather than a list of columns, and thus you get a series back.pandas.Series.tolist()
, so you should
definitely skip the second set of brackets in this case. FYI, if you
ever end up with a one-column dataframe that isn't easily avoidable
like this, you can use pandas.DataFrame.squeeze()
to convert it to
a series.tst[lookupValue]['SomeCol']
is getting a subset of a particular column via
chained slicing. It slices once to get a dataframe with only certain rows
left, and then it slices again to get a certain column. You can get
away with it here since you are just reading, not writing, but
the proper way to do it is tst.loc[lookupValue, 'SomeCol']
(which returns a series).ID = tst.loc[tst['SomeCol'] == 'SomeValue', 'SomeCol'].tolist()
Demo Code:
import pandas as pd
df = pd.DataFrame({'colA':[1,2,1],
'colB':[4,5,6]})
filter_value = 1
print "df"
print df
print type(df)
rows_to_keep = df['colA'] == filter_value
print "\ndf['colA'] == filter_value"
print rows_to_keep
print type(rows_to_keep)
result = df[rows_to_keep]['colB']
print "\ndf[rows_to_keep]['colB']"
print result
print type(result)
result = df[rows_to_keep][['colB']]
print "\ndf[rows_to_keep][['colB']]"
print result
print type(result)
result = df[rows_to_keep][['colB']].squeeze()
print "\ndf[rows_to_keep][['colB']].squeeze()"
print result
print type(result)
result = df.loc[rows_to_keep, 'colB']
print "\ndf.loc[rows_to_keep, 'colB']"
print result
print type(result)
result = df.loc[df['colA'] == filter_value, 'colB']
print "\ndf.loc[df['colA'] == filter_value, 'colB']"
print result
print type(result)
ID = df.loc[rows_to_keep, 'colB'].tolist()
print "\ndf.loc[rows_to_keep, 'colB'].tolist()"
print ID
print type(ID)
ID = df.loc[df['colA'] == filter_value, 'colB'].tolist()
print "\ndf.loc[df['colA'] == filter_value, 'colB'].tolist()"
print ID
print type(ID)
Result:
df
colA colB
0 1 4
1 2 5
2 1 6
<class 'pandas.core.frame.DataFrame'>
df['colA'] == filter_value
0 True
1 False
2 True
Name: colA, dtype: bool
<class 'pandas.core.series.Series'>
df[rows_to_keep]['colB']
0 4
2 6
Name: colB, dtype: int64
<class 'pandas.core.series.Series'>
df[rows_to_keep][['colB']]
colB
0 4
2 6
<class 'pandas.core.frame.DataFrame'>
df[rows_to_keep][['colB']].squeeze()
0 4
2 6
Name: colB, dtype: int64
<class 'pandas.core.series.Series'>
df.loc[rows_to_keep, 'colB']
0 4
2 6
Name: colB, dtype: int64
<class 'pandas.core.series.Series'>
df.loc[df['colA'] == filter_value, 'colB']
0 4
2 6
Name: colB, dtype: int64
<class 'pandas.core.series.Series'>
df.loc[rows_to_keep, 'colB'].tolist()
[4, 6]
<type 'list'>
df.loc[df['colA'] == filter_value, 'colB'].tolist()
[4, 6]
<type 'list'>
If all you need is to clear the screen, this is probably good enough. The problem is there's not even a 100% cross platform way of doing this across linux versions. The problem is the implementations of the terminal all support slightly different things. I'm fairly sure that "clear" will work everywhere. But the more "complete" answer is to use the xterm control characters to move the cursor, but that requires xterm in and of itself.
Without knowing more of your problem, your solution seems good enough.
The default keystore file: debug.keystore
is present in the folder .android
which is usually located in the default home folder of your operating system of the user who installed that Android SDK.
In my Ubuntu PC, it's location is /home/dhananjay/.android
Whereas in the Windows PC it is located at C:\Users\dhananjay\.android
I use Ubuntu 18.04
Installing the corresponding "-dev" package worked for me,
sudo apt install libgconf2-dev
I was getting the below error till I installed the above package,
turtl: error while loading shared libraries: libgconf-2.so.4: cannot open shared object file: No such file or directory
i also appear this problem,and my code below
storeFile file(properties.getProperty("filepath"))
storePassword properties.getProperty("keypassword")
keyAlias properties.getProperty("keyAlias")
keyPassword properties.getProperty("keypassword")
the reason is property name error,it should be keyPassword not keypassword
It's written as:
def my_function(self, param_one=None): # Or custom sentinel if None is vaild
if param_one is None:
param_one = self.one_of_the_vars
And I think it's safe to say that will never happen in Python due to the nature that self
doesn't really exist until the function starts... (you can't reference it, in its own definition - like everything else)
For example: you can't do d = {'x': 3, 'y': d['x'] * 5}
The short answer is, you have to loop.
More info on this topic:
What's the fastest way to copy the values and keys from one dictionary into another in C#?
Use subDays()
method:
$users = Users::where('status_id', 'active')
->where( 'created_at', '>', Carbon::now()->subDays(30))
->get();
Absolutely.
If the constructor doesn't receive valid input, or can't construct the object in a valid manner, it has no other option but to throw an exception and alert its caller.
When the directory is deleted, the inode for that directory (and the inodes for its contents) are recycled. The pointer your shell has to that directory's inode (and its contents's inodes) are now no longer valid. When the directory is restored from backup, the old inodes are not (necessarily) reused; the directory and its contents are stored on random inodes. The only thing that stays the same is that the parent directory reuses the same name for the restored directory (because you told it to).
Now if you attempt to access the contents of the directory that your original shell is still pointing to, it communicates that request to the file system as a request for the original inode, which has since been recycled (and may even be in use for something entirely different now). So you get a stale file handle
message because you asked for some nonexistent data.
When you perform a cd
operation, the shell reevaluates the inode location of whatever destination you give it. Now that your shell knows the new inode for the directory (and the new inodes for its contents), future requests for its contents will be valid.
Here is an answer with support to IE using object-fit
so you won't lose ratio
Using a simple JS snippet to detect if the object-fit
is supported and then replace the img
for a svg
//ES6 version
if ('objectFit' in document.documentElement.style === false) {
document.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('img[data-object-fit]').forEach(image => {
(image.runtimeStyle || image.style).background = `url("${image.src}") no-repeat 50%/${image.currentStyle ? image.currentStyle['object-fit'] : image.getAttribute('data-object-fit')}`
image.src = `data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='${image.width}' height='${image.height}'%3E%3C/svg%3E`
})
})
}
//ES5 version
if ('objectFit' in document.documentElement.style === false) {
document.addEventListener('DOMContentLoaded', function() {
Array.prototype.forEach.call(document.querySelectorAll('img[data-object-fit]').forEach(function(image) {
(image.runtimeStyle || image.style).background = "url(\"".concat(image.src, "\") no-repeat 50%/").concat(image.currentStyle ? image.currentStyle['object-fit'] : image.getAttribute('data-object-fit'));
image.src = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='".concat(image.width, "' height='").concat(image.height, "'%3E%3C/svg%3E");
}));
});
}
_x000D_
img {
display: inline-flex;
width: 175px;
height: 175px;
margin-right: 10px;
border: 1px solid red
}
/*for browsers which support object fit */
[data-object-fit='cover'] {
object-fit: cover
}
[data-object-fit='contain'] {
object-fit: contain
}
_x000D_
<img data-object-fit='cover' src='//picsum.photos/1200/600' />
<img data-object-fit='contain' src='//picsum.photos/1200/600' />
<img src='//picsum.photos/1200/600' />
_x000D_
Note: There are also a few object-fit
polyfills out there that will make object-fit
work.
Here are a few examples:
May this code help you. It works in my case.
$filename = "D:\xampp\htdocs\wordpress/wp-content/uploads/json/2018-10-25.json";
$fileUrl = "http://localhost/wordpress/wp-content/uploads/json/2018-10-25.json";
if(!file_exists($filename)):
$handle = fopen( $filename, 'a' ) or die( 'Cannot open file: ' . $fileUrl ); //implicitly creates file
fwrite( $handle, json_encode(array()));
fclose( $handle );
endif;
$response = file_get_contents($filename);
$tempArray = json_decode($response);
if(!empty($tempArray)):
$count = count($tempArray) + 1;
else:
$count = 1;
endif;
$tempArray[] = array_merge(array("sn." => $count), $data);
$jsonData = json_encode($tempArray);
file_put_contents($filename, $jsonData);
The excellent Pandas library adds features to numpy that make these kinds of operations more intuitive IMO. For example:
import numpy as np
import pandas as pd
# column
df = pd.DataFrame([1,2,3])
# row
df2 = pd.DataFrame([[1,2,3]])
You can even define a DataFrame and make a spreadsheet-like pivot table.
import missingno as msno
msno.matrix(df) # just to visualize. no missing value.
?php
/* Database config */
$db_host = 'localhost';
$db_user = '~';
$db_pass = '~';
$db_database = 'banners';
/* End config */
$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_database);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
In React 16.8+, using functional components, you would do
import React from 'react';
import { Button, Linking } from 'react-native';
const ExternalLinkBtn = (props) => {
return <Button
title={props.title}
onPress={() => {
Linking.openURL(props.url)
.catch(err => {
console.error("Failed opening page because: ", err)
alert('Failed to open page')
})}}
/>
}
export default function exampleUse() {
return (
<View>
<ExternalLinkBtn title="Example Link" url="https://example.com" />
</View>
)
}
Assuming B is the current branch:
$ git diff A <file-path> > patch.tmp
$ git apply patch.tmp -R
Note that this only applies changes to the local file. You'll need to commit afterwards.
I think it could be used for "retroactively forking"
If you have a Git repo, and have now decided that it should have forked another repo. Retroactively you would like it to become a fork, without disrupting the team that uses the repo by needing them to target a new repo.
But I could be wrong.
We also encountered similar problems. However, setting the charset as noted in the previous comment did not help. Our application was making an AJAX request every 60 seconds and our webserver, nginx, was sending Keep-Alive timeout at 60 seconds.
We fixed the problem by setting the keep-alive timeout value to 75 seconds.
This is what we believe was happening:
A Wireshark TCP dump would provide more clarity, our problem is fixed and we do not wish to spend more time on it.
The Java Communications API (also known as javax.comm) provides applications access to RS-232 hardware (serial ports): http://www.oracle.com/technetwork/java/index-jsp-141752.html
In regards to the first comment: If you do this you will get an error(in Android Studio). This is in regards to it being out of the Android namespace. If you don't know how to fix this error, check the example out below. Hope this helps!
Example -Before :
<string-array name="roomSize">
<item>Small(0-4)</item>
<item>Medium(4-8)</item>
<item>Large(9+)</item>
</string-array>
Example - After:
<string-array android:name="roomSize">
<item>Small(0-4)</item>
<item>Medium(4-8)</item>
<item>Large(9+)</item>
</string-array>
AngularJS's Filter worked out for me.
Assuming the code/id
is unique, we can filter out that particular object with AngularJS's filter
and work with the selected objects properties. Considering the example above:
<select ng-options="size.code as size.name for size in sizes"
ng-model="item.size.code"
ng-change="update(MAGIC_THING); search.code = item.size.code">
</select>
<!-- OUTSIDE THE SELECT BOX -->
<h1 ng-repeat="size in sizes | filter:search:true"
ng-init="search.code = item.size.code">
{{size.name}}
</h1>
Now, there are 3 important aspects to this:
ng-init="search.code = item.size.code"
- on initializing h1
element outside select
box, set the filter query to the selected option.
ng-change="update(MAGIC_THING); search.code = item.size.code"
- when you change the select input, we'll run one more line which will set the "search" query to the currently selected item.size.code
.
filter:search:true
- Pass true
to filter to enable strict matching.
That's it. If the size.code
is uniqueID, we'll have only one h1
element with the text of size.name
.
I've tested this in my project and it works.
Good Luck
Set the default value, for example:
$(this).css("height", "auto");
or in the case of other CSS features
$(this).css("height", "inherit");
You can try string.strip()
It worked for me! :)
The easiest way I found was
private boolean checkPermissions(){
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
return true;
}
else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_CODE);
return false;
}
}
You should always write command after a Tab and not white space.
This applies to gcc
line (line #4) in your case. You need to insert tab before gcc
.
Also replace \rm -fr ll
with rm -fr ll
. Insert tabs before this command too.
Where do these values come from? The documentation for android:fontFamily does not list this information in any place
These are indeed not listed in the documentation. But they are mentioned here under the section 'Font families'. The document lists every new public API for Android Jelly Bean 4.1.
In the styles.xml file in the application I'm working on somebody listed this as the font family, and I'm pretty sure it's wrong:
Yes, that's wrong. You don't reference the font file, you have to use the font name mentioned in the linked document above. In this case it should have been this:
<item name="android:fontFamily">sans-serif</item>
Like the linked answer already stated, 12 variants are possible:
Regular (default):
<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">normal</item>
Italic:
<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">italic</item>
Bold:
<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">bold</item>
Bold-italic:
<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">bold|italic</item>
Light:
<item name="android:fontFamily">sans-serif-light</item>
<item name="android:textStyle">normal</item>
Light-italic:
<item name="android:fontFamily">sans-serif-light</item>
<item name="android:textStyle">italic</item>
Thin :
<item name="android:fontFamily">sans-serif-thin</item>
<item name="android:textStyle">normal</item>
Thin-italic :
<item name="android:fontFamily">sans-serif-thin</item>
<item name="android:textStyle">italic</item>
Condensed regular:
<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">normal</item>
Condensed italic:
<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">italic</item>
Condensed bold:
<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">bold</item>
Condensed bold-italic:
<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">bold|italic</item>
Medium:
<item name="android:fontFamily">sans-serif-medium</item>
<item name="android:textStyle">normal</item>
Medium-italic:
<item name="android:fontFamily">sans-serif-medium</item>
<item name="android:textStyle">italic</item>
Black:
<item name="android:fontFamily">sans-serif-black</item>
<item name="android:textStyle">italic</item>
For quick reference, this is how they all look like:
This is a short and simple example I just used:
If:
fp = open("file.txt", "w")
Then:
fp.write(line.replace('is', 'now'))
// "This is me" becomes "This now me"
Not:
line.replace('is', 'now')
fp.write(line)
// "This is me" not changed while writing
$host
is a variable of the Core module.
$host
This variable is equal to line Host in the header of request or name of the server processing the request if the Host header is not available.
This variable may have a different value from $http_host in such cases: 1) when the Host input header is absent or has an empty value, $host equals to the value of server_name directive; 2)when the value of Host contains port number, $host doesn't include that port number. $host's value is always lowercase since 0.8.17.
$http_host
is also a variable of the same module but you won't find it with that name because it is defined generically as $http_HEADER
(ref).
$http_HEADER
The value of the HTTP request header HEADER when converted to lowercase and with 'dashes' converted to 'underscores', e.g. $http_user_agent, $http_referer...;
Summarizing:
$http_host
equals always the HTTP_HOST
request header.$host
equals $http_host
, lowercase and without the port number (if present), except when HTTP_HOST
is absent or is an empty value. In that case, $host
equals the value of the server_name
directive of the server which processed the request.That is the best way to check it. You could write a helper method to do it:
public static boolean isNullOrEmpty( final Collection< ? > c ) {
return c == null || c.isEmpty();
}
public static boolean isNullOrEmpty( final Map< ?, ? > m ) {
return m == null || m.isEmpty();
}
For a flattened export of a container's filesystem, use;
docker export CONTAINER_ID > my_container.tar
Use cat my_container.tar | docker import -
to import said image.
None of these answers quite fit the problem i had as the migration i wanted to delete was missing:
I had created and run a migration in some other branch, which was then discarded. The problem is when a migration is run, rails adds the version into a schema_migrations
table in the database. So even if it isn't listed in your db structure or schema, rails looks for it.
You can reveal these orphaned migrations by running:
rails db:migrate:status
Note the versions of the missing migrations and head into the db console:
rails dbconsole
Now remove the versions from the migration table manually:
delete from schema_migrations where version='<version>';
You should now be good.
var month = mydate.getMonth(); // month (in integer 0-11)
var year = mydate.getFullYear(); // year
Then all you would need to have is an array of months:
var months = ['Jan', 'Feb', 'Mar', ...];
And then to show it:
alert(months[month] + " " + year);
Another possibility is that the debug agent is binding to the wrong network interface.
I've just seen this when trying to debug a Windows 10 JVM inside a VirtualBox VM, and I'm trying to connect from Eclipse running on the VirtualBox host. In my case, the agent only bound to the 127.0.0.1
interface.
To fix, you can qualify the address
including the IP of the interface you want to bind to. For example:
java -agentlib:jdwp=transport=dt_socket,server=y,address=192.168.0.5:8000,suspend=n <other arguments>
Change ng-disabled="!contractTypeValid"
to [disabled]="!contractTypeValid"
You can group by status and select a row from the largest group:
table.GroupBy(r => r.Status).OrderByDescending(g => g.Key).First().First();
The first First()
gets the first group (the set of rows with the largest status); the second First()
gets the first row in that group.
If the status is always unqiue, you can replace the second First()
with Single()
.
What's wrong with the standard stuff?
JSONObject jsonObject = new JSONObject(someJsonString);
JSONArray jsonArray = jsonObject.getJSONArray("someJsonArray");
String value = jsonArray.optJSONObject(i).getString("someJsonValue");
I'm on lubuntu 19.10
I've used combination of previous answers, and didn't tweak the $PATH
.
npm uninstall --global gulp gulp-cli
This removes any package if they are already there.sudo npm install --global gulp-cli
Reinstall it as root user.If you want to do copy and paste
npm uninstall --global gulp gulp-cli && sudo npm install --global gulp-cli
should work
I guess --global
is unnecessary here as it's installed using sudo
, but I've used it just in case.
You can easily print a void printer
int p=15;
void *q;
q=&p;
printf("%d",*((int*)q));
I figured out the solution:
Anaconda/Scripts
pip install google
No more errors.
There are several methods, two of which are as follows. Provide a custom installer or a setup project.
Here is how to create a custom installer
[RunInstaller(true)]
public class MyInstaller : Installer
{
public HelloInstaller()
: base()
{
}
public override void Commit(IDictionary mySavedState)
{
base.Commit(mySavedState);
System.IO.File.CreateText("Commit.txt");
}
public override void Install(IDictionary stateSaver)
{
base.Install(stateSaver);
System.IO.File.CreateText("Install.txt");
}
public override void Uninstall(IDictionary savedState)
{
base.Uninstall(savedState);
File.Delete("Commit.txt");
File.Delete("Install.txt");
}
public override void Rollback(IDictionary savedState)
{
base.Rollback(savedState);
File.Delete("Install.txt");
}
}
To add a setup project
Menu file -> New -> Project --> Other Projects Types --> Setup and Deployment
Set properties of the project, using the properties window
The article How to create a Setup package by using Visual Studio .NET provides the details.
I had the same error, I was updating from within Eclipse and I got many errors. So I tried updating from a DOS command window, and got the same issue.
Then I tried the solution " git gc --prune=now " This gave messages that the files were locked in the refs directory.
Eclipse must have had a locked on something in the "refs" directory.
The solution I found was to simply close Eclipse.
Then I updated the repository from DOS with a " git PULL " command, and everything worked fine.
Since this question is still asked over and over again one year later I will post my answer here as well.
The clue (on Windows only) is to arrange the entries in the path variable right.
As the NPM wiki tells us:
Because the installer puts C:\Program Files (x86)\nodejs before C:\Users\\AppData\Roaming\npm on your PATH, it will always use version of npm installed with node instead of the version of npm you installed using
npm -g install npm@<version>
.
So your path variable will look something like:
…;C:\<path-to-node-installation>;%appdata%\npm;…
Now you have two possibilities:
…;%appdata%\npm;C:\<path-to-node-installation>;…
This will load the npm version installed with npm (and not with node) and with the installed Angular CLI version.
…;C:\Users\<username>\AppData\Roaming\npm\node_modules\@angular\cli;C:\<path-to-node-installation>;%appdata%\npm;…
or …;%appdata%\npm\node_modules\@angular\cli;C:\<path-to-node-installation>;%appdata%\npm;…
for the short form.This worked for me since a while now.
You can open it in a new window with window.open('https://support.wwf.org.uk/earth_hour/index.php?type=individual');
. If you want to open it in new tab open the current page in two tabs and then alllow the script to run so that both current page and the new page will be obtained.
Try to use response.json():
fetch('http://example.com/api/node', {
mode: "no-cors",
method: "GET",
headers: {
"Accept": "application/json"
}
}).then((response) => {
console.log(response.json()); // null
return dispatch({
type: "GET_CALL",
response: response.json()
});
})
.catch(error => { console.log('request failed', error); });
I've used the following recipe:
and it worked for me...
This error occures when you try to refer to a null object instance. I can`t tell you what causes this error by your given information, but you can debug it easily in your IDE. I strongly recommend you that use exception handling to avoid unexpected program behavior.
As datetime is not stable in numpy I would use pandas for this:
In [52]: import pandas as pd
In [53]: dates = pd.DatetimeIndex(['2010-10-17', '2011-05-13', "2012-01-15"])
In [54]: dates.year
Out[54]: array([2010, 2011, 2012], dtype=int32)
Pandas uses numpy datetime internally, but seems to avoid the shortages, that numpy has up to now.
Append a ?v=random_string to the url. If you are using this idea with Facebook share, make sure that the og:url param in the response matches the url you are sharing. This will work with google plus too.
For Facebook, you can also force recrawl by making a post request to https://graph.facebook.com
{id: url,
scrape: true}
Obviously you mean the baseurl. If so:
base url: URL to your CodeIgniter root. Typically this will be your base URL, | WITH a trailing slash.
Root in codeigniter specifically means that the position where you can append your controller to your url.
For example, if the root is localhost/ci_installation/index.php/
, then to access the mycont
controller you should go to localhost/ci_installation/index.php/mycont
.
So, instead of writing such a long link you can (after loading "url" helper) , replace the term localhost/ci_installation/index.php/
by base_url()
and this function will return the same string url.
NOTE: if you hadn't appended index.php/
to your base_url
in your config.php
, then if you use base_url()
, it will return something like that localhost/ci_installation/mycont
. And that will not work, because you have to access your controllers from index.php
, instead of that you can place a .htaccess
file to your codeigniter installation position. Cope that the below code to it:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /imguplod/index.php/$1 [L]
And it should work :)
I don't think this is quite what your looking for, there's no way to display variable values that don't fail, but this may help you get closer to outputting the results the way you want.
You can use the TestResult object returned by the TestRunner.run() for results analysis and processing. Particularly, TestResult.errors and TestResult.failures
About the TestResults Object:
http://docs.python.org/library/unittest.html#id3
And some code to point you in the right direction:
>>> import random
>>> import unittest
>>>
>>> class TestSequenceFunctions(unittest.TestCase):
... def setUp(self):
... self.seq = range(5)
... def testshuffle(self):
... # make sure the shuffled sequence does not lose any elements
... random.shuffle(self.seq)
... self.seq.sort()
... self.assertEqual(self.seq, range(10))
... def testchoice(self):
... element = random.choice(self.seq)
... error_test = 1/0
... self.assert_(element in self.seq)
... def testsample(self):
... self.assertRaises(ValueError, random.sample, self.seq, 20)
... for element in random.sample(self.seq, 5):
... self.assert_(element in self.seq)
...
>>> suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
>>> testResult = unittest.TextTestRunner(verbosity=2).run(suite)
testchoice (__main__.TestSequenceFunctions) ... ERROR
testsample (__main__.TestSequenceFunctions) ... ok
testshuffle (__main__.TestSequenceFunctions) ... FAIL
======================================================================
ERROR: testchoice (__main__.TestSequenceFunctions)
----------------------------------------------------------------------
Traceback (most recent call last):
File "<stdin>", line 11, in testchoice
ZeroDivisionError: integer division or modulo by zero
======================================================================
FAIL: testshuffle (__main__.TestSequenceFunctions)
----------------------------------------------------------------------
Traceback (most recent call last):
File "<stdin>", line 8, in testshuffle
AssertionError: [0, 1, 2, 3, 4] != [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
----------------------------------------------------------------------
Ran 3 tests in 0.031s
FAILED (failures=1, errors=1)
>>>
>>> testResult.errors
[(<__main__.TestSequenceFunctions testMethod=testchoice>, 'Traceback (most recent call last):\n File "<stdin>"
, line 11, in testchoice\nZeroDivisionError: integer division or modulo by zero\n')]
>>>
>>> testResult.failures
[(<__main__.TestSequenceFunctions testMethod=testshuffle>, 'Traceback (most recent call last):\n File "<stdin>
", line 8, in testshuffle\nAssertionError: [0, 1, 2, 3, 4] != [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n')]
>>>
You can use
value.ToString(CultureInfo.InvariantCulture)
to get exact double value without putting precision.
You can hide an image using javascript like this:
document.images['imageName'].style.visibility = hidden;
If that isn't what you are after, you need to explain yourself more clearly.
try this out:
SELECT
`userName`,
`carPrice`
FROM `users`
LEFT JOIN `cars`
ON cars.belongsToUser=users.id
WHERE `id`='4'
ORDER BY `carPrice` DESC
LIMIT 1
Felix
I ended up doing systemd service for WAR/JAR layout
I'm calling java -jar because its more flexible. Tried also putting the ExecStart=spring-mvc.war but even though is executable, I got 'Exec format error'
Anyway these days, systemd is present on all distros, and offers a nice solution to redirect logs(syserr is important when you service doesn't even start log4j file location will be empty :) ).
cat /etc/systemd/system/spring-mvc.service
[Unit]
Description=Spring MVC Java Service
[Service]
User=spring-mvc
# The configuration file application.properties should be here:
WorkingDirectory=/usr/local/spring-mvc
# Run ExecStartPre with root-permissions
PermissionsStartOnly=true
ExecStartPre=-/bin/mkdir -p /var/log/spring-mvc
ExecStartPre=/bin/chown -R spring-mvc:syslog /var/log/spring-mvc
ExecStartPre=/bin/chmod -R 775 /var/log/spring-mvc
#https://www.freedesktop.org/software/systemd/man/systemd.service.html#ExecStart=
ExecStart=/usr/bin/java \
-Dlog4j.configurationFile=log4j2-spring.xml \
-DLog4jContextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector \
-Dspring.profiles.active=dev \
-Denvironment-type=dev \
-XX:+UseConcMarkSweepGC \
-XX:CMSInitiatingOccupancyFraction=80 \
-XX:NewSize=756m \
-XX:MetaspaceSize=256m \
-Dsun.net.inetaddr.ttl=5 \
-Xloggc:/var/log/spring-mvc/gc.log \
-verbose:gc \
-verbosegc \
-XX:+DisableExplicitGC \
-XX:+PrintGCDetails \
-XX:+PrintGCDateStamps \
-XX:+PreserveFramePointer \
-XX:+StartAttachListener \
-Xms1024m \
-Xmx1024m \
-XX:+HeapDumpOnOutOfMemoryError \
-jar spring-mvc.war
SuccessExitStatus=143
StandardOutput=journal
StandardError=journal
KillSignal=SIGINT
TimeoutStopSec=20
Restart=always
RestartSec=5
StartLimitInterval=0
StartLimitBurst=10
LimitNOFILE=500000
LimitNPROC=500000
#https://www.freedesktop.org/software/systemd/man/systemd.exec.html#LimitCPU=
#LimitCPU=, LimitFSIZE=, LimitDATA=, LimitSTACK=, LimitCORE=, LimitRSS=, LimitNOFILE=, LimitAS=, LimitNPROC=, LimitMEMLOCK=, LimitLOCKS=, LimitSIGPENDING=, LimitMSGQUEUE=, LimitNICE=, LimitRTPRIO=, LimitRTTIME=¶
SyslogIdentifier=spring-mvc
[Install]
WantedBy=multi-user.target
# https://www.freedesktop.org/software/systemd/man/journalctl.html
#check logs --- journalctl -u spring-mvc -f -o cat
rsyslog - redirect syslog input from app to specific folder/file
cat /etc/rsyslog.d/30-spring-mvc.conf
if $programname == 'spring-mvc' then /var/log/spring-mvc/spring-mvc.log
& stop
logrotate
cat /etc/logrotate.d/spring-mvc.conf
/var/log/spring-mvc/spring-mvc.log
{
daily
rotate 30
maxage 30
copytruncate
missingok
notifempty
compress
dateext
dateformat _%Y-%m-%d_%H-%M
delaycompress
create 644 spring-mvc syslog
su spring-mvc syslog
}
logrotate gc
cat /etc/logrotate.d/spring-mvc-gc.conf
/var/log/spring-mvc/gc.log
{
daily
rotate 30
maxage 30
copytruncate
missingok
notifempty
compress
dateext
dateformat _%Y-%m-%d_%H-%M
delaycompress
create 644 spring-mvc syslog
su spring-mvc syslog
}
I use a method that first filters the fields and then combines them.
reference Exclude property from type
interface A {
x: string
}
export type B = Omit<A, 'x'> & { x: number };
for interface:
interface A {
x: string
}
interface B extends Omit<A, 'x'> {
x: number
}
I use this for a couple built-in primitive functions that I felt were really missing. One example is a find function that has the same usage semantics as filter, map, reduce.
def builtin_find(f, x, d=None):
for i in x:
if f(i):
return i
return d
import __builtin__
__builtin__.find = builtin_find
Once this is run (for instance, by importing near your entry point) all your modules can use find() as though, obviously, it was built in.
find(lambda i: i < 0, [1, 3, 0, -5, -10]) # Yields -5, the first negative.
Note: You can do this, of course, with filter and another line to test for zero length, or with reduce in one sort of weird line, but I always felt it was weird.
/**
* set focus to top level window
* disposes descendant focus
* disposes softInput
* */
public static void topLevelFocus(Context context){
if(Activity.class.isAssignableFrom(context.getClass())){
ViewGroup tlView = (ViewGroup) ((Activity) context).getWindow().getDecorView();
if(tlView!=null){
tlView.setFocusable(true);
tlView.setFocusableInTouchMode(true);
tlView.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
}
}
}
%S
seems to conform to The Single Unix Specification v2 and is also part of the current (2008) POSIX specification.
Equivalent C99 conforming format specifiers would be %s
and %ls
.
For reference, cursor.rowcount
will only return on CREATE
, UPDATE
and DELETE
statements:
| rowcount
| This read-only attribute specifies the number of rows the last DML statement
| (INSERT, UPDATE, DELETE) affected. This is set to -1 for SELECT statements.
Doing flutter clean
actually worked for me
Have you tried this??
$("Textbox").rules("add", { regex: "^[a-zA-Z'.\\s]{1,40}$", messages: { regex: "The text is invalid..." } })
Note: make sure to escape all the "\" of ur regex by adding another "\" in front of them else the regex wont work as expected.
Here is another way by using UIBezierPath (maybe it's too late ^^) Create a circle and mask UIView with it, as follows:
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
view.backgroundColor = [UIColor blueColor];
CAShapeLayer *shape = [CAShapeLayer layer];
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:view.center radius:(view.bounds.size.width / 2) startAngle:0 endAngle:(2 * M_PI) clockwise:YES];
shape.path = path.CGPath;
view.layer.mask = shape;
There is another way to solve this problem. Let us say you want to access directory "subphp" which exist at /var/www/html/subphp
, and you want to access it using 127.0.0.1/subphp
and you receive error like this:
You don't have permission to access /subphp/ on this server.
Then change the directory permissions from "None" to "access files". A command-line user can use the chmod command to change the permission.
Enter
git log .
from the specific directory, it also gives commits in that directory.
Usually I would say it is overkill, but there are occasionally reasons for writing unit tests for enums.
Sometimes the values assigned to enumeration members must never change or the loading of legacy persisted data will fail. Similarly, apparently unused members must not be deleted. Unit tests can be used to guard against a developer making changes without realising the implications.
You can't specify the width of an element with display inline. You could put something in it like a non-breaking space ( ) and then set the padding to give it some more width but you can't control it directly.
You could use display inline-block but that isn't widely supported.
A real hack would be to put an image inside and then set the width of that. Something like a transparent 1 pixel GIF. Not the recommended approach however.
Use a convert function to get all entries for a particular day.
Select * from tblErrorLog where convert(date,errorDate,101) = '12/20/2008'
See CAST and CONVERT for more info
I have two demos, one with jQuery
and one without. Neither use date functions and are about as simple as it gets.
function startTimer(duration, display) {_x000D_
var timer = duration, minutes, seconds;_x000D_
setInterval(function () {_x000D_
minutes = parseInt(timer / 60, 10);_x000D_
seconds = parseInt(timer % 60, 10);_x000D_
_x000D_
minutes = minutes < 10 ? "0" + minutes : minutes;_x000D_
seconds = seconds < 10 ? "0" + seconds : seconds;_x000D_
_x000D_
display.textContent = minutes + ":" + seconds;_x000D_
_x000D_
if (--timer < 0) {_x000D_
timer = duration;_x000D_
}_x000D_
}, 1000);_x000D_
}_x000D_
_x000D_
window.onload = function () {_x000D_
var fiveMinutes = 60 * 5,_x000D_
display = document.querySelector('#time');_x000D_
startTimer(fiveMinutes, display);_x000D_
};
_x000D_
<body>_x000D_
<div>Registration closes in <span id="time">05:00</span> minutes!</div>_x000D_
</body>
_x000D_
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.text(minutes + ":" + seconds);
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
jQuery(function ($) {
var fiveMinutes = 60 * 5,
display = $('#time');
startTimer(fiveMinutes, display);
});
However if you want a more accurate timer that is only slightly more complicated:
function startTimer(duration, display) {_x000D_
var start = Date.now(),_x000D_
diff,_x000D_
minutes,_x000D_
seconds;_x000D_
function timer() {_x000D_
// get the number of seconds that have elapsed since _x000D_
// startTimer() was called_x000D_
diff = duration - (((Date.now() - start) / 1000) | 0);_x000D_
_x000D_
// does the same job as parseInt truncates the float_x000D_
minutes = (diff / 60) | 0;_x000D_
seconds = (diff % 60) | 0;_x000D_
_x000D_
minutes = minutes < 10 ? "0" + minutes : minutes;_x000D_
seconds = seconds < 10 ? "0" + seconds : seconds;_x000D_
_x000D_
display.textContent = minutes + ":" + seconds; _x000D_
_x000D_
if (diff <= 0) {_x000D_
// add one second so that the count down starts at the full duration_x000D_
// example 05:00 not 04:59_x000D_
start = Date.now() + 1000;_x000D_
}_x000D_
};_x000D_
// we don't want to wait a full second before the timer starts_x000D_
timer();_x000D_
setInterval(timer, 1000);_x000D_
}_x000D_
_x000D_
window.onload = function () {_x000D_
var fiveMinutes = 60 * 5,_x000D_
display = document.querySelector('#time');_x000D_
startTimer(fiveMinutes, display);_x000D_
};
_x000D_
<body>_x000D_
<div>Registration closes in <span id="time"></span> minutes!</div>_x000D_
</body>
_x000D_
Now that we have made a few pretty simple timers we can start to think about re-usability and separating concerns. We can do this by asking "what should a count down timer do?"
So with these things in mind lets write a better (but still very simple) CountDownTimer
function CountDownTimer(duration, granularity) {
this.duration = duration;
this.granularity = granularity || 1000;
this.tickFtns = [];
this.running = false;
}
CountDownTimer.prototype.start = function() {
if (this.running) {
return;
}
this.running = true;
var start = Date.now(),
that = this,
diff, obj;
(function timer() {
diff = that.duration - (((Date.now() - start) / 1000) | 0);
if (diff > 0) {
setTimeout(timer, that.granularity);
} else {
diff = 0;
that.running = false;
}
obj = CountDownTimer.parse(diff);
that.tickFtns.forEach(function(ftn) {
ftn.call(this, obj.minutes, obj.seconds);
}, that);
}());
};
CountDownTimer.prototype.onTick = function(ftn) {
if (typeof ftn === 'function') {
this.tickFtns.push(ftn);
}
return this;
};
CountDownTimer.prototype.expired = function() {
return !this.running;
};
CountDownTimer.parse = function(seconds) {
return {
'minutes': (seconds / 60) | 0,
'seconds': (seconds % 60) | 0
};
};
So why is this implementation better than the others? Here are some examples of what you can do with it. Note that all but the first example can't be achieved by the startTimer
functions.
An example that displays the time in XX:XX format and restarts after reaching 00:00
An example that displays the time in two different formats
An example that has two different timers and only one restarts
An example that starts the count down timer when a button is pressed
<script type="text/javascript">_x000D_
function validateForm() {_x000D_
var a = document.forms["Form"]["answer_a"].value;_x000D_
var b = document.forms["Form"]["answer_b"].value;_x000D_
var c = document.forms["Form"]["answer_c"].value;_x000D_
var d = document.forms["Form"]["answer_d"].value;_x000D_
if (a == null || a == "", b == null || b == "", c == null || c == "", d == null || d == "") {_x000D_
alert("Please Fill All Required Field");_x000D_
return false;_x000D_
}_x000D_
}_x000D_
</script>_x000D_
_x000D_
<form method="post" name="Form" onsubmit="return validateForm()" action="">_x000D_
<textarea cols="30" rows="2" name="answer_a" id="a"></textarea>_x000D_
<textarea cols="30" rows="2" name="answer_b" id="b"></textarea>_x000D_
<textarea cols="30" rows="2" name="answer_c" id="c"></textarea>_x000D_
<textarea cols="30" rows="2" name="answer_d" id="d"></textarea>_x000D_
</form>
_x000D_
It's not an official release yet, but the coming up Gulp 4.0 lets you easily do synchronous tasks with gulp.series. You can simply do it like this:
gulp.task('develop', gulp.series('clean', 'coffee'))
I found a good blog post introducing how to upgrade and make a use of those neat features: migrating to gulp 4 by example
Hi to use the thread pool in Python you can use this library :
from multiprocessing.dummy import Pool as ThreadPool
and then for use, this library do like that :
pool = ThreadPool(threads)
results = pool.map(service, tasks)
pool.close()
pool.join()
return results
The threads are the number of threads that you want and tasks are a list of task that most map to the service.
Two native solutions
performance.now
--> Call to ... took 6.414999981643632
milliseconds.console.time
--> Call to ... took 5.815
millisecondsThe difference between both is precision.
For usage and explanation read on.
Performance.now
(For microsecond precision use)
var t0 = performance.now();
doSomething();
var t1 = performance.now();
console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.");
function doSomething(){
for(i=0;i<1000000;i++){var x = i*i;}
}
_x000D_
Unlike other timing data available to JavaScript (for example Date.now), the timestamps returned by Performance.now() are not limited to one-millisecond resolution. Instead, they represent times as floating-point numbers with up to microsecond precision.
Also unlike Date.now(), the values returned by Performance.now() always increase at a constant rate, independent of the system clock (which might be adjusted manually or skewed by software like NTP). Otherwise, performance.timing.navigationStart + performance.now() will be approximately equal to Date.now().
console.time
Example: (timeEnd
wrapped in setTimeout
for simulation)
console.time('Search page');
doSomething();
console.timeEnd('Search page');
function doSomething(){
for(i=0;i<1000000;i++){var x = i*i;}
}
_x000D_
You can change the Timer-Name for different operations.
If you define the ListView
in XAML:
<ListView x:Name="listView"/>
Then you can add columns and populate it in C#:
public Window()
{
// Initialize
this.InitializeComponent();
// Add columns
var gridView = new GridView();
this.listView.View = gridView;
gridView.Columns.Add(new GridViewColumn {
Header = "Id", DisplayMemberBinding = new Binding("Id") });
gridView.Columns.Add(new GridViewColumn {
Header = "Name", DisplayMemberBinding = new Binding("Name") });
// Populate list
this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}
See definition of MyItem
below.
However, it's easier to define the columns in XAML (inside the ListView
definition):
<ListView x:Name="listView">
<ListView.View>
<GridView>
<GridViewColumn Header="Id" DisplayMemberBinding="{Binding Id}"/>
<GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/>
</GridView>
</ListView.View>
</ListView>
And then just populate the list in C#:
public Window()
{
// Initialize
this.InitializeComponent();
// Populate list
this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}
See definition of MyItem
below.
MyItem
DefinitionMyItem
is defined like this:
public class MyItem
{
public int Id { get; set; }
public string Name { get; set; }
}
Another example of the same concept - but say - you have 2 different columns - and you want to apply different agg functions to each of them i.e
f.groupBy("col1").agg(sum("col2").alias("col2"), avg("col3").alias("col3"), ...)
Here is the way to achieve it - though I do not yet know how to add the alias in this case
See the example below - Using Maps
val Claim1 = StructType(Seq(StructField("pid", StringType, true),StructField("diag1", StringType, true),StructField("diag2", StringType, true), StructField("allowed", IntegerType, true), StructField("allowed1", IntegerType, true)))
val claimsData1 = Seq(("PID1", "diag1", "diag2", 100, 200), ("PID1", "diag2", "diag3", 300, 600), ("PID1", "diag1", "diag5", 340, 680), ("PID2", "diag3", "diag4", 245, 490), ("PID2", "diag2", "diag1", 124, 248))
val claimRDD1 = sc.parallelize(claimsData1)
val claimRDDRow1 = claimRDD1.map(p => Row(p._1, p._2, p._3, p._4, p._5))
val claimRDD2DF1 = sqlContext.createDataFrame(claimRDDRow1, Claim1)
val l = List("allowed", "allowed1")
val exprs = l.map((_ -> "sum")).toMap
claimRDD2DF1.groupBy("pid").agg(exprs) show false
val exprs = Map("allowed" -> "sum", "allowed1" -> "avg")
claimRDD2DF1.groupBy("pid").agg(exprs) show false
I know this is an old question but why can't you do it like:
db.OrderLineItems.Where(o => o.OrderId == currentOrder.OrderId).Sum(o => o.WishListItem.Price);
I am not sure how to do this using query expressions.
Today, I've got a similar error:
Servlet.service() for servlet [remoting] in context with path [/***] threw exception [Request processing failed; nested exception is java.lang.RuntimeException: buildDocument failed.] with root cause
org.xml.sax.SAXParseException; lineNumber: 19; columnNumber: 91; An invalid XML character (Unicode: 0xc) was found in the value of attribute "text" and element is "label".
After my first encouter with the error, I had re-typed the entire line by hand, so that there was no way for a special character to creep in, and Notepad++ didn't show any non-printable characters (black on white), nevertheless I got the same error over and over.
When I looked up what I've done different than my predecessors, it turned out it was one additional space just before the closing /> (as I've heard was recommended for older parsers, but it shouldn't make any difference anyway, by the XML standards):
<label text="this label's text" layout="cell 0 0, align left" />
When I removed the space:
<label text="this label's text" layout="cell 0 0, align left"/>
everything worked just fine.
So it's definitely a misleading error message.
The naming convention is part of the well-established JavaBeans specification and is supported by the classes in the java.beans package.
I suggest using PhantomJS. For more information, you may visit the Phantom Official Website.
As far as I know PhantomJS works only with Firefox...
After downloading PhantomJs.exe you need to import it to your project as you can see in the picture below PhantomJS.
I have placed mine inside: common ? Library ? phantomjs.exe
Now all you have to do inside your Selenium code is to change the line
browser = webdriver.Firefox()
To something like
import os
path2phantom = os.getcwd() + "\common\Library\phantomjs.exe"
browser = webdriver.PhantomJS(path2phantom)
The path to PhantomJS may be different... change as you like :)
This hack worked for me, and I'm pretty sure it will work for u too ;)
For those getting an empty object in req.body
I had forgotten to set
headers: {"Content-Type": "application/json"}
in the request. Changing it solved the problem.
You can use names
directly in the read_csv
names : array-like, default None List of column names to use. If file contains no header row, then you should explicitly pass header=None
Cov = pd.read_csv("path/to/file.txt",
sep='\t',
names=["Sequence", "Start", "End", "Coverage"])
The best script to do this: http://benalman.com/projects/javascript-linkify-process-lin/
Well, you might look at System.Threading.Semaphore
class. Other than that - no, you have to make this yourself. AFAIK there is no such built-in collection.
The best way to do this would be with filter()
:
$("nav>ul>li>a").filter("[data-page-id]");
It would still be nice to have .hasAttr(), but as it doesn't exist there is this way.
The same as David's, but without attr()
$('<input>', {
type: 'hidden',
id: 'foo',
name: 'foo',
value: 'bar'
}).appendTo('form');
A simpler way would be to create a link called cudart64_101.dll
to point to cudart64_102.dll
. This is not very orthodox but since TensorFlow is looking for cudart64_101.dll
exported symbols and the nvidia folks are not amateurs, they would most likely not remove symbols from 101 to 102. It works, based on this assumption (mileage may vary).
Put simply, an lvalue is something that can appear on the left-hand side of an assignment, typically a variable or array element.
So if you define int *p
, then p
is an lvalue. p+1
, which is a valid expression, is not an lvalue.
If you're trying to add 1 to p
, the correct syntax is:
p = p + 1;
Just put all of the symbols in this order (I only tested it in this order since it makes the most sense code-wise to me).
Notice for the body link... I just put... ;?&body=
. Also, notice that I have found I needed to use %20
for any spaces.
I have tested it on my iphone (v. 9.2) and another android and it works just fine.
This will solve the issue with having to hack it for different devices. I have no artifacts when I tested it in the SMS.
<a href="sms:19131234567;?&body=Question%20from%20mywebsite.com.%20%20MY%20MESSAGE%20-%20" title="Click here to TEXT US gallery token needs updating!">Send me SMS</a>
Try like this.
On change event,
$('input[type=checkbox]').on('change', function (e) {
if ($('input[type=checkbox]:checked').length > 3) {
$(this).prop('checked', false);
alert("allowed only 3");
}
});
Check this in JSFiddle
As error shows that path can not be imported.
So here we will use the url instead of path as shown below:-
first import the url package then replace the path with url
from django.conf.urls import url
urlpatterns = [
url('admin/', admin.site.urls),
]
for more information you can take the reference of this link.
Dao clases are used to reuse the jdbc logic & Dao(Data Access Object) is a design pattern. dao is a simple java class which contains JDBC logic .
Data Access Layer has proven good in separate business logic layer and persistent layer. The DAO design pattern completely hides the data access implementation from its clients
The Java Data Access Object (Java DAO) is an important component in business applications. Business applications almost always need access to data from relational or object databases and the Java platform offers many techniques for accessingthis data. The oldest and most mature technique is to use the Java Database Connectivity (JDBC)API, which provides the capability to execute SQL queries against a databaseand then fetch the results, one column at a time.
In Windows, it's possible. You will need to install: Visual C++ Redistributable for Visual Studio 2015. I had the same problem and I installed both version (Windows x86 and Windows x64). Apparently both are necessary to make it work.
Based on previous solutions, I have created bookmark with JavaScript code:
javascript: { var toAppend = "trvhpqi=" + (new Date()).getTime(); var links = document.getElementsByTagName("link"); for (var i = 0; i < links.length;i++) { var link = links[i]; if (link.rel === "stylesheet") { if (link.href.indexOf("?") === -1) { link.href += "?" + toAppend; } else { if (link.href.indexOf("trvhpqi") === -1) { link.href += "&" + toAppend; } else { link.href = link.href.replace(/trvhpqi=\d{13}/, toAppend)} }; } } }; void(0);
Image from Firefox:
What does it do?
It reloads CSS by adding query string params (as solutions above):
here is more detailed information -> [1]: https://crunchify.com/simplest-spring-mvc-hello-world-example-tutorial-spring-model-view-controller-tips/
Mysql Client version : Please beware this doesn't returns server version, this gives mysql client utility version
mysql -version
Mysql server version : There are many ways to find
SELECT version();
SHOW VARIABLES LIKE "%version%";
mysqld --version
This Solution is of O(n^2) complexity. O(1) is the space complexity.
public class longestPalindromeInAString {
public static void main(String[] args) {
String a = "xyMADAMpRACECARwl";
String res = "";
//String longest = a.substring(0,1);
//System.out.println("longest => " +longest);
for (int i = 0; i < a.length(); i++) {
String temp = helper(a,i,i);//even palindrome
if(temp.length() > res.length()) {res = temp ;}
temp = helper(a,i,i+1);// odd length palindrome
if(temp.length() > res.length()) { res = temp ;}
}//for
System.out.println(res);
System.out.println("length of " + res + " is " + res.length());
}
private static String helper(String a, int left, int right) {
while(left>= 0 && right <= a.length() -1 && a.charAt(left) == a.charAt(right)) {
left-- ;right++ ;
}
String curr = a.substring(left + 1 , right);
System.out.println("curr =>" +curr);
return curr ;
}
}
While UNC path is supported since Git 2.21 (Feb. 2019, see below), Git 2.24 (Q4 2019) will allow
git clone file://192.168.10.51/code
No more file:////xxx
, 'file://
' is enough to refer to an UNC path share.
See "Git Fetch Error with UNC".
Note, since 2016 and the MingW-64 git.exe
packaged with Git for Windows, an UNC path is supported.
(See "How are msys, msys2, and MinGW-64 related to each other?")
And with Git 2.21 (Feb. 2019), this support extends even in in an msys2 shell (with quotes around the UNC path).
See commit 9e9da23, commit 5440df4 (17 Jan 2019) by Johannes Schindelin (dscho
).
Helped-by: Kim Gybels (Jeff-G
).
(Merged by Junio C Hamano -- gitster
-- in commit f5dd919, 05 Feb 2019)
Before Git 2.21, due to a quirk in Git's method to spawn git-upload-pack
, there is a
problem when passing paths with backslashes in them: Git will force the
command-line through the shell, which has different quoting semantics in
Git for Windows (being an MSYS2 program) than regular Win32 executables
such as git.exe
itself.
The symptom is that the first of the two backslashes in UNC paths of the
form \\myserver\folder\repository.git
is stripped off.
This is mitigated now:
mingw: special-case arguments to
sh
The MSYS2 runtime does its best to emulate the command-line wildcard expansion and de-quoting which would be performed by the calling Unix shell on Unix systems.
Those Unix shell quoting rules differ from the quoting rules applying to Windows' cmd and Powershell, making it a little awkward to quote command-line parameters properly when spawning other processes.
In particular,
git.exe
passes arguments to subprocesses that are not intended to be interpreted as wildcards, and if they contain backslashes, those are not to be interpreted as escape characters, e.g. when passing Windows paths.Note: this is only a problem when calling MSYS2 executables, not when calling MINGW executables such as git.exe. However, we do call MSYS2 executables frequently, most notably when setting the
use_shell
flag in the child_process structure.There is no elegant way to determine whether the
.exe
file to be executed is an MSYS2 program or a MINGW one.
But since the use case of passing a command line through the shell is so prevalent, we need to work around this issue at least when executingsh.exe
.Let's introduce an ugly, hard-coded test whether
argv[0]
is "sh
", and whether it refers to the MSYS2 Bash, to determine whether we need to quote the arguments differently than usual.That still does not fix the issue completely, but at least it is something.
Incidentally, this also fixes the problem where
git clone \\server\repo
failed due to incorrect handling of the backslashes when handing the path to thegit-upload-pack
process.Further, we need to take care to quote not only whitespace and backslashes, but also curly brackets.
As aliases frequently go through the MSYS2 Bash, and as aliases frequently get parameters such asHEAD@{yesterday}
, this is really important.
Try this.
class User < ActiveRecord::Base
validate do |user|
user.errors.add_to_base("Country can't be blank") if user.country_iso.blank?
end
end
I found this here.
Update for Rails 3 to 6:
validate do |user|
user.errors.add(:base, "Country can't be blank") if user.country_iso.blank?
end
Here is another way to do it. What you do is define a human_attribute_name method on the model class. The method is passed the column name as a string and returns the string to use in validation messages.
class User < ActiveRecord::Base
HUMANIZED_ATTRIBUTES = {
:email => "E-mail address"
}
def self.human_attribute_name(attr)
HUMANIZED_ATTRIBUTES[attr.to_sym] || super
end
end
The above code is from here
Instead of:
var host = req.get('host');
var origin = req.get('origin');
you can also use:
var host = req.headers.host;
var origin = req.headers.origin;
select *
from MyTable
where CAST(Created as time) not between '07:00' and '22:59:59 997'
xrange from Python 2 is a generator and implements iterator while range is just a function. In Python3 I don't know why was dropped off the xrange.
Here is also the code to handle the result:
def foo (a):
x=a
y=a*2
return (x,y)
(x,y) = foo(50)
Simply call the ordinal()
method on an enum value, to retrieve its corresponding number. There's no need to declare an addition attribute with its value, each enumerated value gets its own number by default, assigned starting from zero, incrementing by one for each value in the same order they were declared.
You shouldn't depend on the int
value of an enum
, only on its actual value. Enums in Java are a different kind of monster and are not like enums in C, where you depend on their integer code.
Regarding the example you provided in the question, Font.PLAIN
works because that's just an integer constant of the Font class. If you absolutely need a (possibly changing) numeric code, then an enum
is not the right tool for the job, better stick to numeric constants.
You may find this query useful:
SELECT *
FROM sys.dm_exec_requests
WHERE DB_NAME(database_id) = 'YourDBName'
AND blocking_session_id <> 0
Interesting discussion regarding Designing REST API for returning count of multiple objects: https://groups.google.com/g/api-craft/c/qbI2QRrpFew/m/h30DYnrqEwAJ?pli=1
As an API consumer, I would expect each count value to be represented either as a subresource to the countable resource (i.e. GET /tasks/count for a count of tasks), or as a field in a bigger aggregation of metadata related to the concerned resource (i.e. GET /tasks/metadata). By scoping related endpoints under the same parent resource (i.e. /tasks), the API becomes intuitive, and the purpose of an endpoint can (usually) be inferred from its path and HTTP method.
Additional thoughts:
- If each individual count is only useful in combination with other counts (for a statistics dashboard, for example), you could possibly expose a single endpoint which aggregates and returns all counts at once.
- If you have an existing endpoint for listing all resources (i.e. GET /tasks for listing all tasks), the count could be included in the response as metadata, either as HTTP headers or in the response body. Doing this will incur unnecessary load on the API, which might be negligible depending on your use case.
Filtering an array to contain unique values can be achieved using the JavaScript Set and Array.from method, as shown below:
Array.from(new Set(arrayOfNonUniqueValues));
The Set object lets you store unique values of any type, whether primitive values or object references.
Return value A new Set object.
The Array.from() method creates a new Array instance from an array-like or iterable object.
Return value A new Array instance.
Example Code:
const array = ["X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11"]_x000D_
_x000D_
const uniqueArray = Array.from(new Set(array));_x000D_
_x000D_
console.log("uniqueArray: ", uniqueArray);
_x000D_
ExecutorService is newer and more general. A timer is just a thread that periodically runs stuff you have scheduled for it.
An ExecutorService may be a thread pool, or even spread out across other systems in a cluster and do things like one-off batch execution, etc...
Just look at what each offers to decide.
We can bypass execution policy in a nice way (inside command prompt):
type file.ps1 | powershell -command -
Or inside powershell:
gc file.ps1|powershell -c -
I like prettyPhoto, IMHO it's the one that looks the best.
You can use a basic prepend operation on each line:
ls -1 | while read line ; do echo $line ; done
Or you can pipe the output to sed for more complex operations:
ls -1 | sed 's/^\(.*\)$/echo \1/'
I also put dsym, app bundle, and crash log together in the same directory before running symbolicate crash
Then I use this function defined in my .profile to simplify running symbolicatecrash:
function desym
{
/Developer/Platforms/iPhoneOS.platform/Developer/Library/PrivateFrameworks/DTDeviceKit.framework/Versions/A/Resources/symbolicatecrash -A -v $1 | more
}
The arguments added there may help you.
You can check to make sure spotlight "sees" your dysm files by running the command:
mdfind 'com_apple_xcode_dsym_uuids = *'
Look for the dsym you have in your directory.
NOTE: As of the latest Xcode, there is no longer a Developer directory. You can find this utility here:
/Applications/Xcode.app/Contents/SharedFrameworks/DTDeviceKitBase.framework/Vers??ions/A/Resources/symbolicatecrash
Right click 'libraries' in the project list, then click add.
almost all the solutions above doesn't work with git version 2
mine : git version = 2.28.0
solution of the difftool : git config --global diff.tool vimdiff
after it you can use it without any problems
I think you have to include jQuery to use responseJSON
.
Without jQuery, you could try with responseText and try like eval("("+req.responseText+")");
UPDATE:Please read the comment regarding eval
, you can test with eval, but don't use it in working extension.
OR
use json_parse : it does not use eval
In my case, the issue was that I had another element in the center of the div with a conflicting z-index.
.wrapper {_x000D_
color: white;_x000D_
width: 320px;_x000D_
position: relative;_x000D_
border: 1px dashed gray;_x000D_
height: 40px_x000D_
}_x000D_
_x000D_
.parent {_x000D_
position: absolute;_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
top: 20px;_x000D_
left: 0;_x000D_
right: 0;_x000D_
/* This z-index override is needed to display on top of the other_x000D_
div. Or, just swap the order of the HTML tags. */_x000D_
z-index: 1;_x000D_
}_x000D_
_x000D_
.child {_x000D_
background: green;_x000D_
}_x000D_
_x000D_
.conflicting {_x000D_
position: absolute;_x000D_
left: 120px;_x000D_
height: 40px;_x000D_
background: red;_x000D_
margin: 0 auto;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="parent">_x000D_
<div class="child">_x000D_
Centered_x000D_
</div>_x000D_
</div>_x000D_
<div class="conflicting">_x000D_
Conflicting_x000D_
</div>_x000D_
</div>
_x000D_
import re
pattern = re.compile("<(\d{4,5})>")
for i, line in enumerate(open('test.txt')):
for match in re.finditer(pattern, line):
print 'Found on line %s: %s' % (i+1, match.group())
A couple of notes about the regex:
?
at the end and the outer (...)
if you don't want to match the number with the angle brackets, but only want the number itselfUpdate: It's important to understand that the match and capture in a regex can be quite different. The regex in my snippet above matches the pattern with angle brackets, but I ask to capture only the internal number, without the angle brackets.
More about regex in python can be found here : Regular Expression HOWTO
The solution
func scrollViewDidScroll(scrollView: UIScrollView) {
if(scrollView.panGestureRecognizer.translationInView(scrollView.superview).y > 0)
{
print("up")
}
else
{
print("down")
}
}
This should work (if spring is not an option):
public static List<String> getFilenamesForDirnameFromCP(String directoryName) throws URISyntaxException, UnsupportedEncodingException, IOException {
List<String> filenames = new ArrayList<>();
URL url = Thread.currentThread().getContextClassLoader().getResource(directoryName);
if (url != null) {
if (url.getProtocol().equals("file")) {
File file = Paths.get(url.toURI()).toFile();
if (file != null) {
File[] files = file.listFiles();
if (files != null) {
for (File filename : files) {
filenames.add(filename.toString());
}
}
}
} else if (url.getProtocol().equals("jar")) {
String dirname = directoryName + "/";
String path = url.getPath();
String jarPath = path.substring(5, path.indexOf("!"));
try (JarFile jar = new JarFile(URLDecoder.decode(jarPath, StandardCharsets.UTF_8.name()))) {
Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
String name = entry.getName();
if (name.startsWith(dirname) && !dirname.equals(name)) {
URL resource = Thread.currentThread().getContextClassLoader().getResource(name);
filenames.add(resource.toString());
}
}
}
}
}
return filenames;
}
If your're looking to set the current datetime for a dateTime column (like i was when I googled), use this way
$table->dateTime('signed_when')->useCurrent();
If you need a unique ID, you must first decide on your definition of unique. If you want/intend to use it for a copy-protection mechanism, then use something simple. This is because if someone really wants to use your software, (s)he will find a way to break your protection, given enough time and skill. In the case of a unique hardware ID, just think about virtual machines and you'll see that it is possible to spoof anything so someone can tamper with your software.
There is not much you can take from a PC and consider it as uniqueness over its whole lifetime. (Hardware changes will most likely require regenerating the ID at some point.) If you need something like that, you should investigate using an authentication USB Dongle which you can send to your customers.
If you just need some unique identifier that is not as hard to obtain, you could take the MAC address (unreliable), the OS serial number or the domain and user's name, but all of them are susceptible to forgery. However, if your main goal is to lock out unauthorised people, you won't sell anything because no one will want to use your software if it is hard to install, register or to move from one PC to another, although the last consideration is part and parcel of per-machine licensing. (This will likely happen quite often.)
As a first step, make it easy: Use something simple which is not easy to spoof in your target group. (For example, domain and user names can't be easily spoofed by enterprise customers, because their PCs are running in a larger environment implementing policies, etc.) Just forget about the others until you have that.
Maybe you can lock them out but that doesn't mean they're going to buy your software; they just won't use it anymore. What you have to consider is how many potential customers won't be or aren't willing to pay because you made it so complicated to use your program.
<?php
//Loading all php files into of functions/ folder
$folder = "./functions/";
$files = glob($folder."*.php"); // return array files
foreach($files as $phpFile){
require_once("$phpFile");
}
so I have a solution that isn't perfect but it worked for me. Use the polygon example from Google, and use the pinpoint on Google Maps to get lat & long locations.
I used what I call "ocular copy & paste" where you look at the screen and then write in the numbers you want ;-)
<style>
#map {
height: 500px;
}
</style>
<script>
// This example creates a simple polygon representing the host city of the
// Greatest Outdoor Show On Earth.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 9,
center: {lat: 51.039, lng: -114.204},
mapTypeId: 'terrain'
});
// Define the LatLng coordinates for the polygon's path.
var triangleCoords = [
{lat: 51.183, lng: -114.234},
{lat: 51.154, lng: -114.235},
{lat: 51.156, lng: -114.261},
{lat: 51.104, lng: -114.259},
{lat: 51.106, lng: -114.261},
{lat: 51.102, lng: -114.272},
{lat: 51.081, lng: -114.271},
{lat: 51.081, lng: -114.234},
{lat: 51.009, lng: -114.236},
{lat: 51.008, lng: -114.141},
{lat: 50.995, lng: -114.142},
{lat: 50.998, lng: -114.160},
{lat: 50.984, lng: -114.163},
{lat: 50.987, lng: -114.141},
{lat: 50.979, lng: -114.141},
{lat: 50.921, lng: -114.141},
{lat: 50.921, lng: -114.210},
{lat: 50.893, lng: -114.210},
{lat: 50.892, lng: -114.140},
{lat: 50.888, lng: -114.139},
{lat: 50.878, lng: -114.094},
{lat: 50.878, lng: -113.994},
{lat: 50.840, lng: -113.954},
{lat: 50.854, lng: -113.905},
{lat: 50.922, lng: -113.906},
{lat: 50.935, lng: -113.877},
{lat: 50.943, lng: -113.877},
{lat: 50.955, lng: -113.912},
{lat: 51.183, lng: -113.910}
];
// Construct the polygon.
var bermudaTriangle = new google.maps.Polygon({
paths: triangleCoords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
bermudaTriangle.setMap(map);
}
</script>
<div id="map"></div>
<script async defer src="https://maps.googleapis.com/maps/api/jskey=YOUR_API_KEY&callback=initMap">
</script>
This gets you the outline for Calgary. I've attached an image here.
The boolean
values are compiled to int
data type in JVM. See here.
You can do it as you do in vi, for example to yank lines from 3020 to the end, execute this command (write the block to a file):
:3020,$ w /tmp/yank
And to write this block in another line/file, go to the desired position and execute next command (insert file written before):
:r /tmp/yank
(Reminder: don't forget to remove file: /tmp/yank)
var arr = [ 'a', 'b', 'c'];
arr.push('d'); // insert as last item
Solution to this problem is simple
Go to build.gradle (module.app) file
It will help us to rebuild gradle for the project, to make it sync again.
Right click on the service
in service.msc and select property
.
You will see a folder path under Path to executable
like C:\Users\Me\Desktop\project\Tor\Tor\tor.exe
Navigate to C:\Users\Me\Desktop\project\Tor and right click on Tor.
Select property
, security
, edit
and then add
.
In the text field enter LOCAL SERVICE
, click ok and then check the box FULL CONTROL
Click on add
again then enter NETWORK SERVICE
, click ok
, check the box FULL CONTROL
Then click ok (at the bottom)
Previous answers cover about ASCII character
at a certain index.
It is a little bit troublesome to get a Unicode character
at a certain index in Python 2.
E.g., with s = '????????'
which is <type 'str'>
,
__getitem__
, e.g., s[i]
, does not lead you to where you desire. It will spit out semething like ?
. (Many Unicode characters are more than 1 byte but __getitem__
in Python 2 is incremented by 1 byte.)
In this Python 2 case, you can solve the problem by decoding:
s = '????????'
s = s.decode('utf-8')
for i in range(len(s)):
print s[i]
You forgot to print
the result. What you get is the P
in RE(P)L
and not the actual printed result.
In Py2.x you should so something like
>>> print "\n".join(['I', 'would', 'expect', 'multiple', 'lines'])
I
would
expect
multiple
lines
and in Py3.X, print is a function, so you should do
print("\n".join(['I', 'would', 'expect', 'multiple', 'lines']))
Now that was the short answer. Your Python Interpreter, which is actually a REPL, always displays the representation of the string rather than the actual displayed output. Representation is what you would get with the repr
statement
>>> print repr("\n".join(['I', 'would', 'expect', 'multiple', 'lines']))
'I\nwould\nexpect\nmultiple\nlines'
You have to put a g
at the end, it stands for "global":
echo dog dog dos | sed -r 's:dog:log:g'
^
.a
files are created with the ar
utility, and they are libraries. To use it with gcc
, collect all .a files
in a lib/
folder and then link with -L lib/
and -l<name of specific library>
.
Collection of all .a files into lib/
is optional. Doing so makes for better looking directories with nice separation of code and libraries, IMHO.
I came across this post while searching for a way to clear the entire form related to the BFCache (back/forward button cache) in Chrome.
In addition to what Sim supplied, my use case required that the details needed to be combined with Clear Form on Back Button?.
I found that the best way to do this is in allow the form to behave as it expects, and to trigger an event:
$(window).bind("pageshow", function() {
var form = $('form');
// let the browser natively reset defaults
form[0].reset();
});
If you are not handling the input
events to generate an object in JavaScript, or something else for that matter, then you are done. However, if you are listening to the events, then at least in Chrome you need to trigger a change
event yourself (or whatever event you care to handle, including a custom one):
form.find(':input').not(':button,:submit,:reset,:hidden').trigger('change');
That must be added after the reset
to do any good.
In Matrix terms, the number of elements always has to equal the product of the number of rows and columns. In this particular case, the condition is not matching.
The reason is that the data doesn't match the datatype. I have come across the same issues that I forgot to make the fields match. Though my case is not same as yours, but it shows the similar error message.
The situation is that I copy a table, but accidently I misspell one field, so I change it using the ALTER
after creating the database. And the order of fields in both table is not identical. so when I use the INSERT INTO TableName SELECT * FROM TableName
, the result showed the similar errors: Operand type clash: datetime is incompatible with uniqueidentifier
This is a simiple example:
use example
go
create table Test1 (
id int primary key,
item uniqueidentifier,
inserted_at datetime
)
go
create table Test2 (
id int primary key,
inserted_at datetime
)
go
alter table Test2 add item uniqueidentifier;
go
--insert into Test1 (id, item, inserted_at) values (1, newid(), getdate()), (2, newid(), getdate());
insert into Test2 select * from Test1;
select * from Test1;
select * from Test2;
The error message is:
Msg 206, Level 16, State 2, Line 24
Operand type clash: uniqueidentifier is incompatible with datetime
For some reason config.timeout doesn't work for me. I used this approach:
let cancelRequest = $q.defer();_x000D_
let cancelPromise = cancelRequest.promise;_x000D_
_x000D_
let httpPromise = $http.get(...);_x000D_
_x000D_
$q.race({ cancelPromise, httpPromise })_x000D_
.then(function (result) {_x000D_
..._x000D_
});
_x000D_
And cancelRequest.resolve() to cancel. Actually it doesn't not cancel a request but you don't get unnecessary response at least.
Hope this helps.
Well, I really don't know why the color assigned to border does not work. But you can control the border color using other border properties of the textfield. They are:
A code snippet is given below:
TextField(
enabled: false, // to trigger disabledBorder
decoration: InputDecoration(
filled: true,
fillColor: Color(0xFFF2F2F2),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(4)),
borderSide: BorderSide(width: 1,color: Colors.red),
),
disabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(4)),
borderSide: BorderSide(width: 1,color: Colors.orange),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(4)),
borderSide: BorderSide(width: 1,color: Colors.green),
),
border: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(4)),
borderSide: BorderSide(width: 1,)
),
errorBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(4)),
borderSide: BorderSide(width: 1,color: Colors.black)
),
focusedErrorBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(4)),
borderSide: BorderSide(width: 1,color: Colors.yellowAccent)
),
hintText: "HintText",
hintStyle: TextStyle(fontSize: 16,color: Color(0xFFB3B1B1)),
errorText: snapshot.error,
),
controller: _passwordController,
onChanged: _authenticationFormBloc.onPasswordChanged,
obscureText: false,
),
Hope it helps you.
This is really old, but <font size="10">
would be about <p style= "font-size:55px">
Use the pandas.DataFrame.round() method like this:
df = df.round({'value1': 0})
Any columns not included will be left as is.