For me, the trick was extraData and drilling down into the item component one more time
state = {
uniqueValue: 0
}
<FlatList
keyExtractor={(item, index) => item + index}
data={this.props.photos}
renderItem={this.renderItem}
ItemSeparatorComponent={this.renderSeparator}
/>
renderItem = (item) => {
if(item.item.selected) {
return ( <Button onPress={this.itemPressed.bind(this, item)}>Selected</Button> );
}
return ( <Button onPress={this.itemPressed.bind(this, item)}>Not selected</Button>);
}
itemPressed (item) {
this.props.photos.map((img, i) => {
if(i === item.index) {
if(img['selected') {
delete img.selected;
} else {
img['selected'] = true;
}
this.setState({ uniqueValue: this.state.uniqueValue +1 });
}
}
}
Open .edmx file any text editor change the Schema="your required schema" and also open the app.config/web.config, change the user id and password from the connection string. you are done.
I had this problem and I realized that I was assuming that Geocoding came with the JS maps API. However, it is a separate API which I hadn't enabled in the cloud console. Enabling it fixed it right away.
You can try this:
@OneToOne(cascade = CascadeType.REFRESH)
or
@OneToMany(cascade = CascadeType.REFRESH)
As an additional note, there is no need for the for loop because of R's vectorization.
This:
P <- 243.51
t <- 31 / 365
n <- 365
for (r in seq(0.15, 0.22, by = 0.01))
A <- P * ((1 + (r/ n))^ (n * t))
interest <- A - P
}
is equivalent to:
P <- 243.51
t <- 31 / 365
n <- 365
r <- seq(0.15, 0.22, by = 0.01)
A <- P * ((1 + (r/ n))^ (n * t))
interest <- A - P
Because r
is a vector, the expression above containing it is performed for all values of the vector.
The @RequestBody
javadoc states
Annotation indicating a method parameter should be bound to the body of the web request.
It uses registered instances of HttpMessageConverter
to deserialize the request body into an object of the annotated parameter type.
And the @RequestParam
javadoc states
Annotation which indicates that a method parameter should be bound to a web request parameter.
Spring binds the body of the request to the parameter annotated with @RequestBody
.
Spring binds request parameters from the request body (url-encoded parameters) to your method parameter. Spring will use the name of the parameter, ie. name
, to map the parameter.
Parameters are resolved in order. The @RequestBody
is processed first. Spring will consume all the HttpServletRequest
InputStream
. When it then tries to resolve the @RequestParam
, which is by default required
, there is no request parameter in the query string or what remains of the request body, ie. nothing. So it fails with 400 because the request can't be correctly handled by the handler method.
The handler for @RequestParam
acts first, reading what it can of the HttpServletRequest
InputStream
to map the request parameter, ie. the whole query string/url-encoded parameters. It does so and gets the value abc
mapped to the parameter name
. When the handler for @RequestBody
runs, there's nothing left in the request body, so the argument used is the empty string.
The handler for @RequestBody
reads the body and binds it to the parameter. The handler for @RequestParam
can then get the request parameter from the URL query string.
The handler for @RequestParam
reads from both the body and the URL query String. It would usually put them in a Map
, but since the parameter is of type String
, Spring will serialize the Map
as comma separated values. The handler for @RequestBody
then, again, has nothing left to read from the body.
If you want something with a dropdown (some list of values) and a user specified value that can be filled into the selected input as well. This custom dropdown in angular also has a filter dropdown list on key value entered. Please check this stackblitzlink -> https://stackblitz.com/edit/angular-l9guzo?embed=1&file=src/app/custom-textarea.component.ts
Here is my rendition....
function get_time_difference(earlierDate, laterDate)
{
var oDiff = new Object();
// Calculate Differences
// ------------------------------------------------------------------- //
var nTotalDiff = laterDate.getTime() - earlierDate.getTime();
oDiff.days = Math.floor(nTotalDiff / 1000 / 60 / 60 / 24);
nTotalDiff -= oDiff.days * 1000 * 60 * 60 * 24;
oDiff.hours = Math.floor(nTotalDiff / 1000 / 60 / 60);
nTotalDiff -= oDiff.hours * 1000 * 60 * 60;
oDiff.minutes = Math.floor(nTotalDiff / 1000 / 60);
nTotalDiff -= oDiff.minutes * 1000 * 60;
oDiff.seconds = Math.floor(nTotalDiff / 1000);
// ------------------------------------------------------------------- //
// Format Duration
// ------------------------------------------------------------------- //
// Format Hours
var hourtext = '00';
if (oDiff.days > 0){ hourtext = String(oDiff.days);}
if (hourtext.length == 1){hourtext = '0' + hourtext};
// Format Minutes
var mintext = '00';
if (oDiff.minutes > 0){ mintext = String(oDiff.minutes);}
if (mintext.length == 1) { mintext = '0' + mintext };
// Format Seconds
var sectext = '00';
if (oDiff.seconds > 0) { sectext = String(oDiff.seconds); }
if (sectext.length == 1) { sectext = '0' + sectext };
// Set Duration
var sDuration = hourtext + ':' + mintext + ':' + sectext;
oDiff.duration = sDuration;
// ------------------------------------------------------------------- //
return oDiff;
}
Extra instructions when following @Luke-West's + @Vaiden's solutions:
Also, I did not have to use step 3 of @Vaiden's solution. Just running rm -rf Pods/
in terminal got rid of all old pod files
I also did not have to use step 9 in @Vaiden's solution, instead I just removed the OLD project named framework under Link Binary Libraries (the NEWLY named framework was already there)
So the updated steps would be as follows:
Step 1 - Rename the project
Step 2 - Rename the Scheme
Step 3 - Rename the folder with your assets
Step 4 - Rename the Build plist data
Step 5 Handling Podfile
pod deintegrate
You should be able to build with no errors after you have followed all of the steps successfully
my solution is quite the same as Pumbaa80's one, but I suggest to use display: table
instead of display:table-row
for li
element.
So it will be something like this:
ol {
counter-reset: foo; /* default display:list-item */
}
ol > li {
counter-increment: foo;
display: table; /* instead of table-row */
}
ol > li::before {
content: counter(foo) ".";
display: table-cell;
text-align: right;
}
So now we can use margins for spacing between li
's
for AND you use
if ($status = 'clear' && $pRent == 0) {
mysql_query("UPDATE rent SET dNo = '$id', status = 'clear', colour = '#3C0' WHERE rent.id = $id");
}
for OR you use
if ($status = 'clear' || $pRent == 0) {
mysql_query("UPDATE rent SET dNo = '$id', status = 'clear', colour = '#3C0' WHERE rent.id = $id");
}
map.getBounds()
is not momentary operation, so I use in similar case event handler. Here is my example in Coffeescript
@map.fitBounds(@bounds)
google.maps.event.addListenerOnce @map, 'bounds_changed', =>
@map.setZoom(12) if @map.getZoom() > 12
According to mysql docs: "to rename TEMPORARY
tables, RENAME TABLE
does not work. Use ALTER TABLE
instead."
So this is the most portable method:
ALTER TABLE `old_name` RENAME `new_name`;
you do this in the SSMS app, not the SQL. In the toolbar select
Query --> Results To --> Results To File
await Promise.all([someCall(), anotherCall()]); as already mention will act as a thread fence (very common in parallel code as CUDA), hence it will allow all the promises in it to run without blocking each other, but will prevent the execution to continue until ALL are resolved.
another approach that is worth to share is the Node.js async that will also allow you to easily control the amount of concurrency that is usually desirable if the task is directly linked to the use of limited resources as API call, I/O operations, etc.
// create a queue object with concurrency 2
var q = async.queue(function(task, callback) {
console.log('Hello ' + task.name);
callback();
}, 2);
// assign a callback
q.drain = function() {
console.log('All items have been processed');
};
// add some items to the queue
q.push({name: 'foo'}, function(err) {
console.log('Finished processing foo');
});
q.push({name: 'bar'}, function (err) {
console.log('Finished processing bar');
});
// add some items to the queue (batch-wise)
q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) {
console.log('Finished processing item');
});
// add some items to the front of the queue
q.unshift({name: 'bar'}, function (err) {
console.log('Finished processing bar');
});
Credits to the Medium article autor (read more)
It may help to categorise prototype chains into two categories.
Consider the constructor:
function Person() {}
The value of Object.getPrototypeOf(Person)
is a function. In fact, it is Function.prototype
. Since Person
was created as a function, it shares the same prototype function object that all functions have. It is the same as Person.__proto__
, but that property should not be used. Anyway, with Object.getPrototypeOf(Person)
you effectively walk up the ladder of what is called the prototype chain.
The chain in upward direction looks like this:
Person
? Function.prototype
? Object.prototype
(end point)
Important is that this prototype chain has little to do with the objects that Person
can construct. Those constructed objects have their own prototype chain, and this chain can potentially have no close ancestor in common with the one mentioned above.
Take for example this object:
var p = new Person();
p has no direct prototype-chain relationship with Person. Their relationship is a different one. The object p has its own prototype chain. Using Object.getPrototypeOf
, you'll find the chain is as follows:
p
? Person.prototype
? Object.prototype
(end point)
There is no function object in this chain (although that could be).
So Person
seems related to two kinds of chains, which live their own lives. To "jump" from one chain to the other, you use:
.prototype
: jump from the constructor's chain to the created-object's chain. This property is thus only defined for function objects (as new
can only be used on functions).
.constructor
: jump from the created-object's chain to the constructor's chain.
Here is a visual presentation of the two prototype chains involved, represented as columns:
To summarise:
The
prototype
property gives no information of the subject's prototype chain, but of objects created by the subject.
It is no surprise that the name of the property prototype
can lead to confusion. It would maybe have been clearer if this property had been named prototypeOfConstructedInstances
or something along that line.
You can jump back and forth between the two prototype chains:
Person.prototype.constructor === Person
This symmetry can be broken by explicitly assigning a different object to the prototype
property (more about that later).
Person.prototype
is an object that was created at the same time the function Person
was created. It has Person
as constructor, even though that constructor did not actually execute yet. So two objects are created at the same time:
Person
itselfBoth are objects, but they have different roles: the function object constructs, while the other object represents the prototype of any object that function will construct. The prototype object will become the parent of the constructed object in its prototype chain.
Since a function is also an object, it also has its own parent in its own prototype chain, but recall that these two chains are about different things.
Here are some equalities that could help grasp the issue -- all of these print true
:
function Person() {};_x000D_
_x000D_
// This is prototype chain info for the constructor (the function object):_x000D_
console.log(Object.getPrototypeOf(Person) === Function.prototype);_x000D_
// Step further up in the same hierarchy:_x000D_
console.log(Object.getPrototypeOf(Function.prototype) === Object.prototype);_x000D_
console.log(Object.getPrototypeOf(Object.prototype) === null);_x000D_
console.log(Person.__proto__ === Function.prototype);_x000D_
// Here we swap lanes, and look at the constructor of the constructor_x000D_
console.log(Person.constructor === Function);_x000D_
console.log(Person instanceof Function);_x000D_
_x000D_
// Person.prototype was created by Person (at the time of its creation)_x000D_
// Here we swap lanes back and forth:_x000D_
console.log(Person.prototype.constructor === Person);_x000D_
// Although it is not an instance of it:_x000D_
console.log(!(Person.prototype instanceof Person));_x000D_
// Instances are objects created by the constructor:_x000D_
var p = new Person();_x000D_
// Similarly to what was shown for the constructor, here we have_x000D_
// the same for the object created by the constructor:_x000D_
console.log(Object.getPrototypeOf(p) === Person.prototype);_x000D_
console.log(p.__proto__ === Person.prototype);_x000D_
// Here we swap lanes, and look at the constructor_x000D_
console.log(p.constructor === Person);_x000D_
console.log(p instanceof Person);
_x000D_
Although a prototype object is created when you create a constructor function, you can ignore that object, and assign another object that should be used as prototype for any subsequent instances created by that constructor.
For instance:
function Thief() { }
var p = new Person();
Thief.prototype = p; // this determines the prototype for any new Thief objects:
var t = new Thief();
Now the prototype chain of t is one step longer than that of p:
t
? p
? Person.prototype
? Object.prototype
(end point)
The other prototype chain is not longer: Thief
and Person
are siblings sharing the same parent in their prototype chain:
Person
}
Thief
} ? Function.prototype
? Object.prototype
(end point)
The earlier presented graphic can then be extended to this (the original Thief.prototype
is left out):
The blue lines represent prototype chains, the other coloured lines represent other relationships:
All we know is "All instances of a any class shares the same java.lang.Class object of that type of class"
e.g)
Student a = new Student();
Student b = new Student();
Then a.getClass() == b.getClass()
is true.
Now assume
Teacher t = new Teacher();
without generics the below is possible.
Class studentClassRef = t.getClass();
But this is wrong now ..?
e.g) public void printStudentClassInfo(Class studentClassRef) {}
can be called with Teacher.class
This can be avoided using generics.
Class<Student> studentClassRef = t.getClass(); //Compilation error.
Now what is T ?? T is type parameters (also called type variables); delimited by angle brackets (<>), follows the class name.
T is just a symbol, like a variable name (can be any name) declared during writing of the class file. Later that T will be substituted with
valid Class name during initialization (HashMap<String> map = new HashMap<String>();
)
e.g) class name<T1, T2, ..., Tn>
So Class<T>
represents a class object of specific class type 'T
'.
Assume that your class methods has to work with unknown type parameters like below
/**
* Generic version of the Car class.
* @param <T> the type of the value
*/
public class Car<T> {
// T stands for "Type"
private T t;
public void set(T t) { this.t = t; }
public T get() { return t; }
}
Here T can be used as String
type as CarName
OR T can be used as Integer
type as modelNumber,
OR T can be used as Object
type as valid car instance.
Now here the above is the simple POJO which can be used differently at runtime.
Collections e.g) List, Set, Hashmap are best examples which will work with different objects as per the declaration of T, but once we declared T as String
e.g) HashMap<String> map = new HashMap<String>();
Then it will only accept String Class instance objects.
Generic Methods
Generic methods are methods that introduce their own type parameters. This is similar to declaring a generic type, but the type parameter's scope is limited to the method where it is declared. Static and non-static generic methods are allowed, as well as generic class constructors.
The syntax for a generic method includes a type parameter, inside angle brackets, and appears before the method's return type. For generic methods, the type parameter section must appear before the method's return type.
class Util {
// Generic static method
public static <K, V, Z, Y> boolean compare(Pair<K, V> p1, Pair<Z, Y> p2) {
return p1.getKey().equals(p2.getKey()) &&
p1.getValue().equals(p2.getValue());
}
}
class Pair<K, V> {
private K key;
private V value;
}
Here <K, V, Z, Y>
is the declaration of types used in the method arguments which should before the return type which is boolean
here.
In the below; type declaration <T>
is not required at method level, since it is already declared at class level.
class MyClass<T> {
private T myMethod(T a){
return a;
}
}
But below is wrong as class-level type parameters K, V, Z, and Y cannot be used in a static context (static method here).
class Util <K, V, Z, Y>{
// Generic static method
public static boolean compare(Pair<K, V> p1, Pair<Z, Y> p2) {
return p1.getKey().equals(p2.getKey()) &&
p1.getValue().equals(p2.getValue());
}
}
OTHER VALID SCENARIOS ARE
class MyClass<T> {
//Type declaration <T> already done at class level
private T myMethod(T a){
return a;
}
//<T> is overriding the T declared at Class level;
//So There is no ClassCastException though a is not the type of T declared at MyClass<T>.
private <T> T myMethod1(Object a){
return (T) a;
}
//Runtime ClassCastException will be thrown if a is not the type T (MyClass<T>).
private T myMethod1(Object a){
return (T) a;
}
// No ClassCastException
// MyClass<String> obj= new MyClass<String>();
// obj.myMethod2(Integer.valueOf("1"));
// Since type T is redefined at this method level.
private <T> T myMethod2(T a){
return a;
}
// No ClassCastException for the below
// MyClass<String> o= new MyClass<String>();
// o.myMethod3(Integer.valueOf("1").getClass())
// Since <T> is undefined within this method;
// And MyClass<T> don't have impact here
private <T> T myMethod3(Class a){
return (T) a;
}
// ClassCastException for o.myMethod3(Integer.valueOf("1").getClass())
// Should be o.myMethod3(String.valueOf("1").getClass())
private T myMethod3(Class a){
return (T) a;
}
// Class<T> a :: a is Class object of type T
//<T> is overriding of class level type declaration;
private <T> Class<T> myMethod4(Class<T> a){
return a;
}
}
And finally Static method always needs explicit <T>
declaration; It wont derive from class level Class<T>
. This is because of Class level T is bound with instance.
Also read Restrictions on Generics
Save sub object first and then call final repository save method.
@PostMapping("/save")
public String save(@ModelAttribute("shortcode") @Valid Shortcode shortcode, BindingResult result) {
Shortcode existingShortcode = shortcodeService.findByShortcode(shortcode.getShortcode());
if (existingShortcode != null) {
result.rejectValue(shortcode.getShortcode(), "This shortode is already created.");
}
if (result.hasErrors()) {
return "redirect:/shortcode/create";
}
**shortcode.setUser(userService.findByUsername(shortcode.getUser().getUsername()));**
shortcodeService.save(shortcode);
return "redirect:/shortcode/create?success";
}
Try this: It will open the default mail directly.
<a href="mailto:[email protected]"><img src="ICON2.png"></a>
I think you are trying to run some utility or shell script from UNIX\LINUX which has some GUI. Anyways
SOLUTION: dude all you need is an XServer & X11 forwarding enabled. I use XMing (XServer). You are already enabling X11 forwarding. Just Install it(XMing) and keep it running when you create the session with PuTTY.
My Solution was to use 2 asp panels:
<asp:Panel ID=”..” DefaultButton=”ID_OF_SHIPPING_SUBMIT_BUTTON”….></asp:Panel>
For the case of simply discarding changes, the git checkout -- path/
or git checkout HEAD -- path/
commands suggested by other answers work great. However, when you wish to reset a directory to a revision other than HEAD, that solution has a significant problem: it doesn't remove files which were deleted in the target revision.
So instead, I have begun using the following command:
This works by finding the diff between the target commit and the index, then applying that diff in reverse to the working directory and index. Basically, this means that it makes the contents of the index match the contents of the revision you specified. The fact that git diff
takes a path argument allows you to limit this effect to a specific file or directory.
Since this command fairly long and I plan on using it frequently, I have set up an alias for it which I named reset-checkout
:
git config --global alias.reset-checkout '!f() { git diff --cached "$@" | git apply -R --index; }; f'
You can use it like this:
git reset-checkout 451a9a4 -- path/to/directory
Or just:
git reset-checkout 451a9a4
The thing you are asking is not popup but lightbox. For this, the trick is to display a semitransparent layer behind (called overlay) and that required div above it.
Hope you are familiar basic javascript. Use the following code. With javascript, change display:block to/from display:none to show/hide popup.
<div style="background-color: rgba(150, 150, 150, 0.5); overflow: hidden; position: fixed; left: 0px; top: 0px; bottom: 0px; right: 0px; z-index: 1000; display:block;">
<div style="background-color: rgb(255, 255, 255); width: 600px; position: static; margin: 20px auto; padding: 20px 30px 0px; top: 110px; overflow: hidden; z-index: 1001; box-shadow: 0px 3px 8px rgba(34, 25, 25, 0.4);">
<iframe src="otherpage.html" width="400px"></iframe>
</div>
</div>
I would like to add a minor comment on Blender solution.
You can do the following:
var link = 'http://example.com?candy_name=' + encodeURIComponent('M&M');
That outputs:
http://example.com?candy_name=M%26M
The great thing about this it does not only work for & but for any especial character.
For instance:
var link = 'http://example.com?candy_name=' + encodeURIComponent('M&M?><')
Outputs:
"http://example.com?candy_name=M%26M%3F%3E%3C"
I use:
ls -ABrt1 --group-directories-first | tail -n1
It gives me just the file name, excluding folders.
The issue with the "one thread per request" model for a server is that they don't scale well for several scenarios compared to the event loop thread model.
Typically, in I/O intensive scenarios the requests spend most of the time waiting for I/O to complete. During this time, in the "one thread per request" model, the resources linked to the thread (such as memory) are unused and memory is the limiting factor. In the event loop model, the loop thread selects the next event (I/O finished) to handle. So the thread is always busy (if you program it correctly of course).
The event loop model as all new things seems shiny and the solution for all issues but which model to use will depend on the scenario you need to tackle. If you have an intensive I/O scenario (like a proxy), the event base model will rule, whereas a CPU intensive scenario with a low number of concurrent processes will work best with the thread-based model.
In the real world most of the scenarios will be a bit in the middle. You will need to balance the real need for scalability with the development complexity to find the correct architecture (e.g. have an event base front-end that delegates to the backend for the CPU intensive tasks. The front end will use little resources waiting for the task result.) As with any distributed system it requires some effort to make it work.
If you are looking for the silver bullet that will fit with any scenario without any effort, you will end up with a bullet in your foot.
The reason you get a Null Pointer Exception is because there is no key likesZZZ in your second example. Try:
def mymap = [name:"Gromit", likes:"cheese", id:1234]
def x = mymap.find{ it.key == "likes" }.value
if(x)
println "x value: ${x}"
Here's the real solution (with other cool CSS3 stuff):
#fixed-square {
position: fixed;
top: 0;
right: 0;
z-index: 9500;
cursor: pointer;
width: 24px;
padding: 18px 18px 14px;
opacity: 0.618;
-webkit-transform: rotate(-90deg);
-moz-transform: rotate(-90deg);
-ms-transform: rotate(-90deg);
transform: rotate(-90deg);
-webkit-transition: all 0.145s ease-out;
-moz-transition: all 0.145s ease-out;
-ms-transition: all 0.145s ease-out;
transition: all 0.145s ease-out;
}
Note the top:0 and right:0. That's what did it for me.
I compared the efficiency of the most popular suggestions to determine if a number is prime. I used python 3.6
on ubuntu 17.10
; I tested with numbers up to 100.000 (you can test with bigger numbers using my code below).
This first plot compares the functions (which are explained further down in my answer), showing that the last functions do not grow as fast as the first one when increasing the numbers.
And in the second plot we can see that in case of prime numbers the time grows steadily, but non-prime numbers do not grow so fast in time (because most of them can be eliminated early on).
Here are the functions I used:
this answer and this answer suggested a construct using all()
:
def is_prime_1(n):
return n > 1 and all(n % i for i in range(2, int(math.sqrt(n)) + 1))
This answer used some kind of while loop:
def is_prime_2(n):
if n <= 1:
return False
if n == 2:
return True
if n == 3:
return True
if n % 2 == 0:
return False
if n % 3 == 0:
return False
i = 5
w = 2
while i * i <= n:
if n % i == 0:
return False
i += w
w = 6 - w
return True
This answer included a version with a for
loop:
def is_prime_3(n):
if n <= 1:
return False
if n % 2 == 0 and n > 2:
return False
for i in range(3, int(math.sqrt(n)) + 1, 2):
if n % i == 0:
return False
return True
And I mixed a few ideas from the other answers into a new one:
def is_prime_4(n):
if n <= 1: # negative numbers, 0 or 1
return False
if n <= 3: # 2 and 3
return True
if n % 2 == 0 or n % 3 == 0:
return False
for i in range(5, int(math.sqrt(n)) + 1, 2):
if n % i == 0:
return False
return True
Here is my script to compare the variants:
import math
import pandas as pd
import seaborn as sns
import time
from matplotlib import pyplot as plt
def is_prime_1(n):
...
def is_prime_2(n):
...
def is_prime_3(n):
...
def is_prime_4(n):
...
default_func_list = (is_prime_1, is_prime_2, is_prime_3, is_prime_4)
def assert_equal_results(func_list=default_func_list, n):
for i in range(-2, n):
r_list = [f(i) for f in func_list]
if not all(r == r_list[0] for r in r_list):
print(i, r_list)
raise ValueError
print('all functions return the same results for integers up to {}'.format(n))
def compare_functions(func_list=default_func_list, n):
result_list = []
n_measurements = 3
for f in func_list:
for i in range(1, n + 1):
ret_list = []
t_sum = 0
for _ in range(n_measurements):
t_start = time.perf_counter()
is_prime = f(i)
t_end = time.perf_counter()
ret_list.append(is_prime)
t_sum += (t_end - t_start)
is_prime = ret_list[0]
assert all(ret == is_prime for ret in ret_list)
result_list.append((f.__name__, i, is_prime, t_sum / n_measurements))
df = pd.DataFrame(
data=result_list,
columns=['f', 'number', 'is_prime', 't_seconds'])
df['t_micro_seconds'] = df['t_seconds'].map(lambda x: round(x * 10**6, 2))
print('df.shape:', df.shape)
print()
print('', '-' * 41)
print('| {:11s} | {:11s} | {:11s} |'.format(
'is_prime', 'count', 'percent'))
df_sub1 = df[df['f'] == 'is_prime_1']
print('| {:11s} | {:11,d} | {:9.1f} % |'.format(
'all', df_sub1.shape[0], 100))
for (is_prime, count) in df_sub1['is_prime'].value_counts().iteritems():
print('| {:11s} | {:11,d} | {:9.1f} % |'.format(
str(is_prime), count, count * 100 / df_sub1.shape[0]))
print('', '-' * 41)
print()
print('', '-' * 69)
print('| {:11s} | {:11s} | {:11s} | {:11s} | {:11s} |'.format(
'f', 'is_prime', 't min (us)', 't mean (us)', 't max (us)'))
for f, df_sub1 in df.groupby(['f', ]):
col = df_sub1['t_micro_seconds']
print('|{0}|{0}|{0}|{0}|{0}|'.format('-' * 13))
print('| {:11s} | {:11s} | {:11.2f} | {:11.2f} | {:11.2f} |'.format(
f, 'all', col.min(), col.mean(), col.max()))
for is_prime, df_sub2 in df_sub1.groupby(['is_prime', ]):
col = df_sub2['t_micro_seconds']
print('| {:11s} | {:11s} | {:11.2f} | {:11.2f} | {:11.2f} |'.format(
f, str(is_prime), col.min(), col.mean(), col.max()))
print('', '-' * 69)
return df
Running the function compare_functions(n=10**5)
(numbers up to 100.000) I get this output:
df.shape: (400000, 5)
-----------------------------------------
| is_prime | count | percent |
| all | 100,000 | 100.0 % |
| False | 90,408 | 90.4 % |
| True | 9,592 | 9.6 % |
-----------------------------------------
---------------------------------------------------------------------
| f | is_prime | t min (us) | t mean (us) | t max (us) |
|-------------|-------------|-------------|-------------|-------------|
| is_prime_1 | all | 0.57 | 2.50 | 154.35 |
| is_prime_1 | False | 0.57 | 1.52 | 154.35 |
| is_prime_1 | True | 0.89 | 11.66 | 55.54 |
|-------------|-------------|-------------|-------------|-------------|
| is_prime_2 | all | 0.24 | 1.14 | 304.82 |
| is_prime_2 | False | 0.24 | 0.56 | 304.82 |
| is_prime_2 | True | 0.25 | 6.67 | 48.49 |
|-------------|-------------|-------------|-------------|-------------|
| is_prime_3 | all | 0.20 | 0.95 | 50.99 |
| is_prime_3 | False | 0.20 | 0.60 | 40.62 |
| is_prime_3 | True | 0.58 | 4.22 | 50.99 |
|-------------|-------------|-------------|-------------|-------------|
| is_prime_4 | all | 0.20 | 0.89 | 20.09 |
| is_prime_4 | False | 0.21 | 0.53 | 14.63 |
| is_prime_4 | True | 0.20 | 4.27 | 20.09 |
---------------------------------------------------------------------
Then, running the function compare_functions(n=10**6)
(numbers up to 1.000.000) I get this output:
df.shape: (4000000, 5)
-----------------------------------------
| is_prime | count | percent |
| all | 1,000,000 | 100.0 % |
| False | 921,502 | 92.2 % |
| True | 78,498 | 7.8 % |
-----------------------------------------
---------------------------------------------------------------------
| f | is_prime | t min (us) | t mean (us) | t max (us) |
|-------------|-------------|-------------|-------------|-------------|
| is_prime_1 | all | 0.51 | 5.39 | 1414.87 |
| is_prime_1 | False | 0.51 | 2.19 | 413.42 |
| is_prime_1 | True | 0.87 | 42.98 | 1414.87 |
|-------------|-------------|-------------|-------------|-------------|
| is_prime_2 | all | 0.24 | 2.65 | 612.69 |
| is_prime_2 | False | 0.24 | 0.89 | 322.81 |
| is_prime_2 | True | 0.24 | 23.27 | 612.69 |
|-------------|-------------|-------------|-------------|-------------|
| is_prime_3 | all | 0.20 | 1.93 | 67.40 |
| is_prime_3 | False | 0.20 | 0.82 | 61.39 |
| is_prime_3 | True | 0.59 | 14.97 | 67.40 |
|-------------|-------------|-------------|-------------|-------------|
| is_prime_4 | all | 0.18 | 1.88 | 332.13 |
| is_prime_4 | False | 0.20 | 0.74 | 311.94 |
| is_prime_4 | True | 0.18 | 15.23 | 332.13 |
---------------------------------------------------------------------
I used the following script to plot the results:
def plot_1(func_list=default_func_list, n):
df_orig = compare_functions(func_list=func_list, n=n)
df_filtered = df_orig[df_orig['t_micro_seconds'] <= 20]
sns.lmplot(
data=df_filtered, x='number', y='t_micro_seconds',
col='f',
# row='is_prime',
markers='.',
ci=None)
plt.ticklabel_format(style='sci', axis='x', scilimits=(3, 3))
plt.show()
If you are using spring boot then add these tags in pom.xml.
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
and
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
`<maven.compiler.release>`10</maven.compiler.release>
</properties>
You can change java version to 11 or 13 as well in <maven.compiler.release>
tag.
Just add below tags in pom.xml
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.release>11</maven.compiler.release>
</properties>
You can change the 11 to 10, 13 as well to change java version. I am using java 13 which is latest. It works for me.
Hi i am same problem and resolve this ways.
windows user and vs cant'create .bowerrc file.
in cmd go any folder
install any packages which is contains .bowerrc file forexample
bower install angular-local-storage
this plugin contains .bowerrc file. copy that and go to your project and paste this file.
and in visual studio - solution explorer - show all files and include project seen .bowerrc file
i resolve this ways :)
Check out CUDA by NVidia, IMO it's the easiest platform to do GPU programming. There are tons of cool materials to read.
http://www.nvidia.com/object/cuda_home.html
Hello world would be to do any kind of calculation using GPU.
Hope that helps.
Since I cannot comment, adding this note in addition to @jethro answer.
I found out that you also need to do the FOREIGN KEY line as the last part of create the table statement, otherwise you will get a syntax error when installing your app. What I mean is, you cannot do something like this:
private static final String TASK_TABLE_CREATE = "create table "
+ TASK_TABLE + " (" + TASK_ID
+ " integer primary key autoincrement, " + TASK_TITLE
+ " text not null, " + TASK_NOTES + " text not null, "
+ TASK_CAT + " integer,"
+ " FOREIGN KEY ("+TASK_CAT+") REFERENCES "+CAT_TABLE+" ("+CAT_ID+"), "
+ TASK_DATE_TIME + " text not null);";
Where I put the TASK_DATE_TIME after the foreign key line.
I struggeld for many hours on this. This is my loop to register command line vars. Example : Register.bat /param1:value1 /param2:value2
What is does, is loop all the commandline params, and that set the variable with the proper name to the value.
After that, you can just use set value=!param1! set value2=!param2!
regardless the sequence the params are given. (so called named parameters). Note the !<>!, instead of the %<>%.
SETLOCAL ENABLEDELAYEDEXPANSION
FOR %%P IN (%*) DO (
call :processParam %%P
)
goto:End
:processParam [%1 - param]
@echo "processparam : %1"
FOR /F "tokens=1,2 delims=:" %%G IN ("%1") DO (
@echo a,b %%G %%H
set nameWithSlash=%%G
set name=!nameWithSlash:~1!
@echo n=!name!
set value=%%H
set !name!=!value!
)
goto :eof
:End
please Press fn +ins key together
If you want to set something on a timer, you can use JavaScript's setTimeout
or setInterval
methods:
setTimeout ( expression, timeout );
setInterval ( expression, interval );
Where expression
is a function and timeout
and interval
are integers in milliseconds. setTimeout
runs the timer once and runs the expression
once whereas setInterval will run the expression
every time the interval
passes.
So in your case it would work something like this:
setInterval(function() {
//call $.ajax here
}, 5000); //5 seconds
As far as the Ajax goes, see jQuery's ajax()
method. If you run an interval, there is nothing stopping you from calling the same ajax()
from other places in your code.
If what you want is for an interval to run every 30 seconds until a user initiates a form submission...and then create a new interval after that, that is also possible:
setInterval()
returns an integer which is the ID of the interval.
var id = setInterval(function() {
//call $.ajax here
}, 30000); // 30 seconds
If you store that ID in a variable, you can then call clearInterval(id)
which will stop the progression.
Then you can reinstantiate the setInterval()
call after you've completed your ajax form submission.
Subscribing to the IUS Community Project Repository
cd ~
curl 'https://setup.ius.io/' -o setup-ius.sh
Run the script:
sudo bash setup-ius.sh
Upgrading mod_php with Apache
This section describes the upgrade process for a system using Apache as the web server and mod_php to execute PHP code. If, instead, you are running Nginx and PHP-FPM, skip ahead to the next section.
Begin by removing existing PHP packages. Press y and hit Enter to continue when prompted.
sudo yum remove php-cli mod_php php-common
Install the new PHP 7 packages from IUS. Again, press y and Enter when prompted.
sudo yum install mod_php70u php70u-cli php70u-mysqlnd
Finally, restart Apache to load the new version of mod_php:
sudo apachectl restart
You can check on the status of Apache, which is managed by the httpd systemd unit, using systemctl:
systemctl status httpd
Here you go:
(new Date()).toLocaleDateString('en-US');
That's it !!
you can use it on any date object
let's say.. you have an object called "currentDate"
var currentDate = new Date(); //use your date here
currentDate.toLocaleDateString('en-US'); // "en-US" gives date in US Format - mm/dd/yy
(or)
If you want it in local format then
currentDate.toLocaleDateString(); // gives date in local Format
Also, you can overwrite some variables:
s = input('UPPER CASE')
lower = s.lower()
If you use like this:
s = "Kilometer"
print(s.lower()) - kilometer
print(s) - Kilometer
It will work just when called.
I've tried Komodo out a bit, and I really like it so far. Aptana, an Eclipse variant, is also rather useful for a wide variety of things. There's always good ole' VI, too!
A quick and easy way is to use jQuery and do this:
var $eles = $(":input[name^='q1_']").css("color","yellow");
That will grab all elements whose name attribute starts with 'q1_'. To convert the resulting collection of jQuery objects to a DOM collection, do this:
var DOMeles = $eles.get();
see http://api.jquery.com/attribute-starts-with-selector/
In pure DOM, you could use getElementsByTagName
to grab all input elements, and loop through the resulting array. Elements with name
starting with 'q1_' get pushed to another array:
var eles = [];
var inputs = document.getElementsByTagName("input");
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].name.indexOf('q1_') == 0) {
eles.push(inputs[i]);
}
}
The main difference is that the output of pip freeze
can be dumped into a requirements.txt file and used later to re-construct the "frozen" environment.
In other words you can run:
pip freeze > frozen-requirements.txt
on one machine and then later on a different machine or on a clean environment you can do:
pip install -r frozen-requirements.txt
and you'll get the an identical environment with the exact same dependencies installed as you had in the original environment where you generated the frozen-requirements.txt.
You may need to repair your mdf file first using some tools. There are lot of tool available in the market. There is tool called SQL Database Recovery Tool Repairs which is very useful to repair the mdf files.
The issue might me because of corrupted transaction logs, you may use tool SQL Database Recovery Tool Repairs to repair your corrupted mdf file.
Also, the ternary operator expects expressions, not statements. Do not use semicolons, only at the end of the ternary op.
$("#blackbox").css({'background':
$("#blackbox").css('background') === 'pink' ? 'black' : 'pink'});
you can just do $scope.todo = Todo.get({ id: 123 })
. .get()
and .query()
on a Resource return an object immediately and fill it with the result of the promise later (to update your template). It's not a typical promise which is why you need to either use a callback or the $promise property if you have some special code you want executed after the call. But there is no need to assign it to your scope in a callback if you are only using it in the template.
As mentioned in Security Considerations section of Marshal documentation,
If you need to deserialize untrusted data, use JSON or another serialization format that is only able to load simple, ‘primitive’ types such as String, Array, Hash, etc.
Here is an example on how to do cloning using JSON in Ruby:
require "json"
original = {"John"=>"Adams","Thomas"=>"Jefferson","Johny"=>"Appleseed"}
cloned = JSON.parse(JSON.generate(original))
# Modify original hash
original["John"] << ' Sandler'
p original
#=> {"John"=>"Adams Sandler", "Thomas"=>"Jefferson", "Johny"=>"Appleseed"}
# cloned remains intact as it was deep copied
p cloned
#=> {"John"=>"Adams", "Thomas"=>"Jefferson", "Johny"=>"Appleseed"}
You can use std::find
for this:
#include <algorithm> // for std::find
#include <iterator> // for std::begin, std::end
int main ()
{
int a[] = {3, 6, 8, 33};
int x = 8;
bool exists = std::find(std::begin(a), std::end(a), x) != std::end(a);
}
std::find
returns an iterator to the first occurrence of x
, or an iterator to one-past the end of the range if x
is not found.
The best place to understand the difference is at the official documentation on values / values_list. It has many useful examples and explains it very clearly. The django docs are very user freindly.
Here's a short snippet to keep SO reviewers happy:
Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable.
And read the section which follows it:
This is similar to values() except that instead of returning dictionaries, it returns tuples when iterated over.
In linuxOS:
sed -i 's/textSerch/textReplace/g' namefile
if "sed" not work try :
perl -i -pe 's/textSerch/textReplace/g' namefile
You might also want to check for Heroku telling you there's a typo in your CSS file.
Read through the long boring messages in the terminal closely after you push. There may be something like this: Invalid CSS after
. It means Heroku has found a typo and you need to fix it in the CSS file.
You can do a find for rake aborted!
and directly after that it should say why the push failed.
I have written a shuffle function on my own . The difference here is it will never repeat a value (checks in the code for this) :-
function shuffleArray(array) {
var newArray = [];
for (var i = 0; i < array.length; i++) {
newArray.push(-1);
}
for (var j = 0; j < array.length; j++) {
var id = Math.floor((Math.random() * array.length));
while (newArray[id] !== -1) {
id = Math.floor((Math.random() * array.length));
}
newArray.splice(id, 1, array[j]);
}
return newArray; }
A Context is a handle to the system; it provides services like resolving resources, obtaining access to databases and preferences, and so on. It is an "interface" that allows access to application specific resources and class and information about application environment. Your activities and services also extend Context to they inherit all those methods to access the environment information in which the application is running.
This means you must have to pass context to the specific class if you want to get/modify some specific information about the resources. You can pass context in the constructor like
public classname(Context context, String s1)
{
...
}
JavaScript's Date object supports the ISO date format, so as long as you have access to the date string, you can do something like this:
> foo = new Date("2012-07-14T01:00:00+01:00")
Sat, 14 Jul 2012 00:00:00 GMT
> foo.toTimeString()
'17:00:00 GMT-0700 (MST)'
If you want the time string without the seconds and the time zone then you can call the getHours() and getMinutes() methods on the Date object and format the time yourself.
Here is a manual way to do git remote set-url origin [new repo URL]
:
git clone <old remote>
Open <repository>/.git/config
$ git config -e
[core]
repositoryformatversion = 0
filemode = false
bare = false
logallrefupdates = true
symlinks = false
ignorecase = true
[remote "origin"]
url = <old remote>
fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
remote = origin
merge = refs/heads/master
and change the remote (the url option)
[remote "origin"]
url = <new remote>
fetch = +refs/heads/*:refs/remotes/origin/*
Push the repository to GitHub: git push
You can also use both/multiple remotes.
Import jquery first before bootstrap:
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/bootstrap.bundle.js"></script>
I had this problem and it took me nearly 2 days to resolve...
I had moved my SDK location, due to the system drive being full, and it seems that someone, somewhere at Android Studio central has hard-coded the path to the HaxM driver installer. As my HamX driver was out of date, the emulator wouldn't start.
Solution: navigate to [your sdk location]\extras\intel\Hardware_Accelerated_Execution_Manager and run the intelhaxm-android.exe installer to update yourself to the latest driver.
Here is a lattice version:
library(lattice)
eq<-function(x) {x*x}
X<-1:1000
xyplot(eq(X)~X,type="l")
The following code assumes no circular references, and assumes subs
is always an array (and not null in leaf nodes):
function find(haystack, needle) {
if (haystack.label === needle) return haystack;
for (var i = 0; i < haystack.subs.length; i ++) {
var result = find(haystack.subs[i], needle);
if (result) return result;
}
return null;
}
Add namespace
using System.Configuration;
and in place of
ConfigurationSettings.AppSettings
you should use
ConfigurationManager.AppSettings
String path = ConfigurationManager.AppSettings["configFile"];
if(session_status()!=PHP_SESSION_ACTIVE) session_start()
info registers
shows all the registers; info registers eax
shows just the register eax
. The command can be abbreviated as i r
I had the same problem, I succeeded by adding:
new \SoapClient(URI WSDL OR NULL if non-WSDL mode, [
'cache_wsdl' => WSDL_CACHE_NONE,
'proxy_host' => 'URL PROXY',
'proxy_port' => 'PORT PROXY'
]);
Hope this help :)
On Click event On webView works in onTouch like this:
imagewebViewNewsChart.setOnTouchListener(new View.OnTouchListener(){
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction()==MotionEvent.ACTION_MOVE){
return false;
}
if (event.getAction()==MotionEvent.ACTION_UP){
startActivity(new Intent(this,Example.class));
}
return false;
}
});
A very simple and elegant solution to this is provided by W3C. Simply use the margin:0 auto declaration as follows:
.top_image img { margin:0 auto; }
More information and examples from W3C.
std::less<>
when using custom classes with operator<
If you are dealing with a set of your custom class that has operator<
defined, then you can just use std::less<>
.
As mentioned at http://en.cppreference.com/w/cpp/container/set/find C++14 has added two new find
APIs:
template< class K > iterator find( const K& x );
template< class K > const_iterator find( const K& x ) const;
which allow you to do:
main.cpp
#include <cassert>
#include <set>
class Point {
public:
// Note that there is _no_ conversion constructor,
// everything is done at the template level without
// intermediate object creation.
//Point(int x) : x(x) {}
Point(int x, int y) : x(x), y(y) {}
int x;
int y;
};
bool operator<(const Point& c, int x) { return c.x < x; }
bool operator<(int x, const Point& c) { return x < c.x; }
bool operator<(const Point& c, const Point& d) {
return c.x < d;
}
int main() {
std::set<Point, std::less<>> s;
s.insert(Point(1, -1));
s.insert(Point(2, -2));
s.insert(Point(0, 0));
s.insert(Point(3, -3));
assert(s.find(0)->y == 0);
assert(s.find(1)->y == -1);
assert(s.find(2)->y == -2);
assert(s.find(3)->y == -3);
// Ignore 1234, find 1.
assert(s.find(Point(1, 1234))->y == -1);
}
Compile and run:
g++ -std=c++14 -Wall -Wextra -pedantic -o main.out main.cpp
./main.out
More info about std::less<>
can be found at: What are transparent comparators?
Tested on Ubuntu 16.10, g++
6.2.0.
jQuery("html,body").animate({scrollTop: jQuery("#your-elemm-id-where you want to scroll").offset().top-<some-number>}, 500, 'swing', function() {
alert("Finished animating");
});
When you want to use pure Markdown (without nested HTML), you can use Emojis to draw attention to some fragment of the file, i.e. ??WARNING??, IMPORTANT? or NEW.
In case you're using Maven I have a great solution for you:
Edit your pom.xml file to include following lines:
<profiles>
<profile>
<id>linux</id>
<activation>
<os>
<family>unix</family>
</os>
</activation>
<properties>
<logDirectory>/var/log/tomcat6</logDirectory>
</properties>
</profile>
<profile>
<id>windows</id>
<activation>
<os>
<family>windows</family>
</os>
</activation>
<properties>
<logDirectory>${catalina.home}/logs</logDirectory>
</properties>
</profile>
</profiles>
Here you define logDirectory
property specifically to OS family.
Use already defined logDirectory
property in log4j.properties
file:
log4j.appender.FILE=org.apache.log4j.RollingFileAppender
log4j.appender.FILE.File=${logDirectory}/mylog.log
log4j.appender.FILE.MaxFileSize=30MB
log4j.appender.FILE.MaxBackupIndex=10
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.ConversionPattern=%d{ISO8601} [%x] %-5p [%t] [%c{1}] %m%n
P.S.: I'm sure this can be achieved using Ant but unfortunately I don't have enough experience with it.
You can use .substring
, which returns a potion of a string:
"abcdefghijklmnopq".substring(0, 8) === "abcdefgh"; // portion from index 0 to 8
As @Richard pointed out above, the onClick needs to have a capital 'C'.
$('#stop').click(function() {
$('next').attr('onClick','stopMoving()');
}
JavaScript now has equivalents for both the Elvis Operator and the Safe Navigation Operator.
Safe Property Access
The optional chaining operator (?.
) is currently a stage 4 ECMAScript proposal. You can use it today with Babel.
// `undefined` if either `a` or `b` are `null`/`undefined`. `a.b.c` otherwise.
const myVariable = a?.b?.c;
The logical AND operator (&&
) is the "old", more-verbose way to handle this scenario.
const myVariable = a && a.b && a.b.c;
Providing a Default
The nullish coalescing operator (??
) is currently a stage 4 ECMAScript proposal. You can use it today with Babel. It allows you to set a default value if the left-hand side of the operator is a nullary value (null
/undefined
).
const myVariable = a?.b?.c ?? 'Some other value';
// Evaluates to 'Some other value'
const myVariable2 = null ?? 'Some other value';
// Evaluates to ''
const myVariable3 = '' ?? 'Some other value';
The logical OR operator (||
) is an alternative solution with slightly different behavior. It allows you to set a default value if the left-hand side of the operator is falsy. Note that the result of myVariable3
below differs from myVariable3
above.
const myVariable = a?.b?.c || 'Some other value';
// Evaluates to 'Some other value'
const myVariable2 = null || 'Some other value';
// Evaluates to 'Some other value'
const myVariable3 = '' || 'Some other value';
Well, you're missing the letter 'd' in url("~/fonts/Lato-Bol.ttf"); - but assuming that's not it, I would open up your page with developer tools in Chrome and make sure there's no errors loading any of the files (you would probably see an issue in the JavaScript console, or you can check the Network tab and see if anything is red).
(I don't see anything obviously wrong with the code you have posted above)
Other things to check: 1) Are you including your CSS file in your html above the lines where you are trying to use the font-family style? 2) What do you see in the CSS panel in the developer tools for that div? Is font-family: lato crossed out?
A mask defines which bits you want to keep, and which bits you want to clear.
Masking is the act of applying a mask to a value. This is accomplished by doing:
Below is an example of extracting a subset of the bits in the value:
Mask: 00001111b
Value: 01010101b
Applying the mask to the value means that we want to clear the first (higher) 4 bits, and keep the last (lower) 4 bits. Thus we have extracted the lower 4 bits. The result is:
Mask: 00001111b
Value: 01010101b
Result: 00000101b
Masking is implemented using AND, so in C we get:
uint8_t stuff(...) {
uint8_t mask = 0x0f; // 00001111b
uint8_t value = 0x55; // 01010101b
return mask & value;
}
Here is a fairly common use-case: Extracting individual bytes from a larger word. We define the high-order bits in the word as the first byte. We use two operators for this, &
, and >>
(shift right). This is how we can extract the four bytes from a 32-bit integer:
void more_stuff(uint32_t value) { // Example value: 0x01020304
uint32_t byte1 = (value >> 24); // 0x01020304 >> 24 is 0x01 so
// no masking is necessary
uint32_t byte2 = (value >> 16) & 0xff; // 0x01020304 >> 16 is 0x0102 so
// we must mask to get 0x02
uint32_t byte3 = (value >> 8) & 0xff; // 0x01020304 >> 8 is 0x010203 so
// we must mask to get 0x03
uint32_t byte4 = value & 0xff; // here we only mask, no shifting
// is necessary
...
}
Notice that you could switch the order of the operators above, you could first do the mask, then the shift. The results are the same, but now you would have to use a different mask:
uint32_t byte3 = (value & 0xff00) >> 8;
Not sure if this counts as dark-corner-ish at all, but I've only just learnt it...
:g/match/y A
will yank (copy) all lines containing "match" into the "a
/@a
register. (The capitalization as A
makes vim append yankings instead of replacing the previous register contents.) I used it a lot recently when making Internet Explorer stylesheets.
private static void DownloadRemoteImageFile(string uri, string fileName)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if ((response.StatusCode == HttpStatusCode.OK ||
response.StatusCode == HttpStatusCode.Moved ||
response.StatusCode == HttpStatusCode.Redirect) &&
response.ContentType.StartsWith("image", StringComparison.OrdinalIgnoreCase))
{
using (Stream inputStream = response.GetResponseStream())
using (Stream outputStream = File.OpenWrite(fileName))
{
byte[] buffer = new byte[4096];
int bytesRead;
do
{
bytesRead = inputStream.Read(buffer, 0, buffer.Length);
outputStream.Write(buffer, 0, bytesRead);
} while (bytesRead != 0);
}
}
}
The .getTimezoneOffset()
method should work. This will get the time between your time zone and GMT. You can then calculate to whatever you want.
There is no such thing like a DateTime
without a year!
From what I gather your design is a bit strange:
I would recommend storing a "start" (DateTime
including year for the FIRST occurence) and a value which designates how to calculate the next event... this could be for example a TimeSpan
or some custom structure esp. since "every year" can mean that the event occurs on a specific date and would not automatically be the same as saysing that it occurs in +365 days.
After the event occurs you calculate the next and store that etc.
<div class="post_category">
<?php $category = get_the_category();
$allcategory = get_the_category();
foreach ($allcategory as $category) {
?>
<a class="btn"><?php echo $category->cat_name;; ?></a>
<?php
}
?>
</div>
what is about this? \D(\d{5})\D
This will do on:
f 23 23453 234 2344 2534 hallo33333 "50000"
23453, 33333 50000
Here's a new automated tool, JSNice, to try to deobfuscate/deminify it. The tool even tries to guess the variable names, which is unbelievably cool. (It mines Javascript on github for this purpose.)
Just create a small delete function which can help you to achieve this task, I have tested this code and it runs perfectly well.
This function deletes files older than 90 days as well as a file with extension .zip to be deleted from a folder.
Private Sub DeleteZip()
Dim eachFileInMydirectory As New DirectoryInfo("D:\Test\")
Dim fileName As IO.FileInfo
Try
For Each fileName In eachFileInMydirectory.GetFiles
If fileName.Extension.Equals("*.zip") AndAlso (Now - fileName.CreationTime).Days > 90 Then
fileName.Delete()
End If
Next
Catch ex As Exception
WriteToLogFile("No Files older than 90 days exists be deleted " & ex.Message)
End Try
End Sub
-webkit-animation-fill-mode: forwards; /* Safari 4.0 - 8.0 */ animation-fill-mode: forwards;
Browser Support
Usage:-
.fadeIn {
animation-name: fadeIn;
-webkit-animation-name: fadeIn;
animation-duration: 1.5s;
-webkit-animation-duration: 1.5s;
animation-timing-function: ease;
-webkit-animation-timing-function: ease;
animation-fill-mode: forwards;
-webkit-animation-fill-mode: forwards;
}
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@-webkit-keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
Add the total row to your data collection that will be bound to the grid.
This will work on both BSD and GNU.
awk '{arr[i++]=$0} END {while (i>0) print arr[--i] }' filename
Base on @Mark answer, I add the constructor to directive and it work with me.
I share a sample to whom concern.
constructor(private el: ElementRef, private renderer: Renderer) {
}
TS file
@Directive({ selector: '[accordion]' })
export class AccordionDirective {
constructor(private el: ElementRef, private renderer: Renderer) {
}
@HostListener('click', ['$event']) onClick($event) {
console.info($event);
this.el.nativeElement.classList.toggle('is-open');
var content = this.el.nativeElement.nextElementSibling;
if (content.style.maxHeight) {
// accordion is currently open, so close it
content.style.maxHeight = null;
} else {
// accordion is currently closed, so open it
content.style.maxHeight = content.scrollHeight + "px";
}
}
}
HTML
<button accordion class="accordion">Accordian #1</button>
<div class="accordion-content">
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quas deleniti molestias necessitatibus quaerat quos incidunt! Quas officiis repellat dolore omnis nihil quo,
ratione cupiditate! Sed, deleniti, recusandae! Animi, sapiente, nostrum?
</p>
</div>
Demo https://stackblitz.com/edit/angular-directive-accordion?file=src/app/app.component.ts
You can wrap the whole connection in a context manager, like the following:
from contextlib import contextmanager
import pyodbc
import sys
@contextmanager
def open_db_connection(connection_string, commit=False):
connection = pyodbc.connect(connection_string)
cursor = connection.cursor()
try:
yield cursor
except pyodbc.DatabaseError as err:
error, = err.args
sys.stderr.write(error.message)
cursor.execute("ROLLBACK")
raise err
else:
if commit:
cursor.execute("COMMIT")
else:
cursor.execute("ROLLBACK")
finally:
connection.close()
Then do something like this where ever you need a database connection:
with open_db_connection("...") as cursor:
# Your code here
The connection will close when you leave the with block. This will also rollback the transaction if an exception occurs or if you didn't open the block using with open_db_connection("...", commit=True)
.
Use the latest X509ExtendedTrustManager instead of X509Certificate as advised here: java.security.cert.CertificateException: Certificates does not conform to algorithm constraints
package javaapplication8;
import java.io.InputStream;
import java.net.Socket;
import java.net.URL;
import java.net.URLConnection;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509ExtendedTrustManager;
/**
*
* @author hoshantm
*/
public class JavaApplication8 {
/**
* @param args the command line arguments
* @throws java.lang.Exception
*/
public static void main(String[] args) throws Exception {
/*
* fix for
* Exception in thread "main" javax.net.ssl.SSLHandshakeException:
* sun.security.validator.ValidatorException:
* PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException:
* unable to find valid certification path to requested target
*/
TrustManager[] trustAllCerts = new TrustManager[]{
new X509ExtendedTrustManager() {
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
@Override
public void checkClientTrusted(X509Certificate[] xcs, String string, Socket socket) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] xcs, String string, Socket socket) throws CertificateException {
}
@Override
public void checkClientTrusted(X509Certificate[] xcs, String string, SSLEngine ssle) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] xcs, String string, SSLEngine ssle) throws CertificateException {
}
}
};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Create all-trusting host name verifier
HostnameVerifier allHostsValid = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
// Install the all-trusting host verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
/*
* end of the fix
*/
URL url = new URL("https://10.52.182.224/cgi-bin/dynamic/config/panel.bmp");
URLConnection con = url.openConnection();
//Reader reader = new ImageStreamReader(con.getInputStream());
InputStream is = new URL(url.toString()).openStream();
// Whatever you may want to do next
}
}
Try powerform-react . It is based upon powerform
which is a super portable Javascript form library. Once learnt, it can be used in any framework. It works even with vanilla Javascript.
Checkout this simple form that uses powerform-react
There is also a complex example.
I noticed a couple of syntax errors, but other than that, it should work fine:
var arr = [
["Blankaholm", "Gamleby"],
["2012-10-23", "2012-10-22"],
["Blankaholm. Under natten har det varit inbrott", "E22 i med Gamleby. Singelolycka. En bilist har."], //<- syntax error here
["57.586174","16.521841"], ["57.893162","16.406090"]
];
console.log(arr[4]); //["57.893162","16.406090"]
console.log(arr[4][0]); //57.893162
I did this for a <div>
on Chrome.
element.scrollTop - is the pixels hidden in top due to the scroll. With no scroll its value is 0.
element.scrollHeight - is the pixels of the whole div.
element.clientHeight - is the pixels that you see in your browser.
var a = element.scrollTop;
will be the position.
var b = element.scrollHeight - element.clientHeight;
will be the maximum value for scrollTop.
var c = a / b;
will be the percent of scroll [from 0 to 1].
You can use like
NOT columnA = 'x'
Or
columnA != 'x'
Or
columnA <> 'x'
And like Jeffly Bake's query, for including null values, you don't have to write like
(NOT columnA = 'x' OR columnA IS NULL)
You can make it simple by
Not columnA <=> 'x'
<=> is the Null Safe equal to Operator, which includes results from even null values.
{=FIND("cell I want to search","list of words I want to search for")}
{=SUM(FIND($A$1:$A$100&"|";A3))}
this ensures spreadsheet will compare strings like "cellvlaue|" againts "pattern1|", "pattern2|" etc. which sorts out conflicts like pattern1="newly added", pattern2="added" (sum of all cells matching "added" would be too high, including the target values for cells matching "newly added", which would be a logical error)Another solution which works better for me than pp
or awesome_print
:
require 'pry' # must install the gem... but you ALWAYS want pry installed anyways
Pry::ColorPrinter.pp(obj)
I believe this answer is cleaner, (based on https://stackoverflow.com/a/3007668/550975)
public ActionResult GetAttachment(long id)
{
FileAttachment attachment;
using (var db = new TheContext())
{
attachment = db.FileAttachments.FirstOrDefault(x => x.Id == id);
}
return File(attachment.FileData, "application/force-download", Path.GetFileName(attachment.FileName));
}
I would prefere
if (!myStr.empty())
{
//do something
}
Also you don't have to write std::string a = "";
. You can just write std::string a;
- it will be empty by default
Just press windows button and type %APPDATA% and type enter.
Above is the location where you can find \npm\node_modules folder. This is where global modules sit in your system.
If you cannot use std::to_string
from C++11, you can write it as it is defined on cppreference.com:
std::string to_string( int value )
Converts a signed decimal integer to a string with the same content as whatstd::sprintf(buf, "%d", value)
would produce for sufficiently large buf.
Implementation
#include <cstdio>
#include <string>
#include <cassert>
std::string to_string( int x ) {
int length = snprintf( NULL, 0, "%d", x );
assert( length >= 0 );
char* buf = new char[length + 1];
snprintf( buf, length + 1, "%d", x );
std::string str( buf );
delete[] buf;
return str;
}
You can do more with it. Just use "%g"
to convert float or double to string, use "%x"
to convert int to hex representation, and so on.
You are getting double free or corruption because first destructor is for object q in this case the memory allocated by new will be free.Next time when detructor will be called for object t at that time the memory is already free (done for q) hence when in destructor delete[] myArray; will execute it will throw double free or corruption. The reason is that both object sharing the same memory so define \copy, assignment, and equal operator as mentioned in above answer.
(This is for the benefit of others who may refer)
You can simply use cin and a char array. The cin input is delimited by the first whitespace it encounters.
#include<iostream>
using namespace std;
main()
{
char word[50];
cin>>word;
while(word){
//Do stuff with word[]
cin>>word;
}
}
Yes, this is possible.
<form id="formName" action="<?php echo $_SERVER['PHP_SELF'];?>" method="get">
<input type ="checkbox" name="cBox[]" value = "3" onchange="document.getElementById('formName').submit()">3</input>
<input type ="checkbox" name="cBox[]" value = "4" onchange="document.getElementById('formName').submit()">4</input>
<input type ="checkbox" name="cBox[]" value = "5" onchange="document.getElementById('formName').submit()">5</input>
<input type="submit" name="submit" value="Search" />
</form>
By adding onchange="document.getElementById('formName').submit()"
to each checkbox, you'll submit any time a checkbox is changed.
If you're OK with jQuery, it's even easier (and unobtrusive):
$(document).ready(function(){
$("#formname").on("change", "input:checkbox", function(){
$("#formname").submit();
});
});
For any number of checkboxes in your form, when the "change" event happens, the form is submitted. This will even work if you dynamically create more checkboxes thanks to the .on()
method.
You can make sure that you do not insert duplicate information by using the EXISTS condition.
For example, if you had a table named clients with a primary key of client_id, you could use the following statement:
INSERT INTO clients
(client_id, client_name, client_type)
SELECT supplier_id, supplier_name, 'advertising'
FROM suppliers
WHERE not exists (select * from clients
where clients.client_id = suppliers.supplier_id);
This statement inserts multiple records with a subselect.
If you wanted to insert a single record, you could use the following statement:
INSERT INTO clients
(client_id, client_name, client_type)
SELECT 10345, 'IBM', 'advertising'
FROM dual
WHERE not exists (select * from clients
where clients.client_id = 10345);
The use of the dual table allows you to enter your values in a select statement, even though the values are not currently stored in a table.
You can use if
expression for this in Kotlin. In Kotlin if
is an expression with a result value. So in Kotlin we can write
fun max(a: Int, b: Int) = if (a > b) a else b
and in Java we can achieve the same but with larger code
int max(int a, int b) {
return a > b ? a : b
}
moment(moment('2015/04/09 16:00:00').add(7, 'd').format('YYYY/MM/DD HH:mm:mm'))
has to format and then convert to moment again.
using System.Web;
var encoded = HttpUtility.HtmlEncode(unencoded);
After several attempts and going deep in Tomcat's source code I found out that the simple property useNaming="false" did the trick!! Now Tomcat resolves names java:/liferay instead of java:comp/env/liferay
There is no unique
method for a df, if the number of unique values for each column were the same then the following would work: df.apply(pd.Series.unique)
but if not then you will get an error. Another approach would be to store the values in a dict which is keyed on the column name:
In [111]:
df = pd.DataFrame({'a':[0,1,2,2,4], 'b':[1,1,1,2,2]})
d={}
for col in df:
d[col] = df[col].unique()
d
Out[111]:
{'a': array([0, 1, 2, 4], dtype=int64), 'b': array([1, 2], dtype=int64)}
The initialize
method is called after all @FXML
annotated members have been injected. Suppose you have a table view you want to populate with data:
class MyController {
@FXML
TableView<MyModel> tableView;
public MyController() {
tableView.getItems().addAll(getDataFromSource()); // results in NullPointerException, as tableView is null at this point.
}
@FXML
public void initialize() {
tableView.getItems().addAll(getDataFromSource()); // Perfectly Ok here, as FXMLLoader already populated all @FXML annotated members.
}
}
I would use this syntax to set the index value into an attribute of the HTML element:
You have to use let
to declare the value rather than #
.
<ul>
<li *ngFor="let item of items; let i = index" [attr.data-index]="i">
{{item}}
</li>
</ul>
<ul>
<li *ngFor="#item of items; #i = index" [attr.data-index]="i">
{{item}}
</li>
</ul>
Here is the updated plunkr: http://plnkr.co/edit/LiCeyKGUapS5JKkRWnUJ?p=preview.
I used to do a simple for
loop. As @A5C1D2H2I1M1N2O1R2T1 answer, lapply
is a nice solution. But if you convert all the columns, you will need a data.frame
before, otherwise you will end up with a list
. Little execution time differences.
mm2N=mm2New[,10:18]
str(mm2N)
'data.frame': 35487 obs. of 9 variables:
$ bb : int 4 6 2 3 3 2 5 2 1 2 ...
$ vabb : int -3 -3 -2 -2 -3 -1 0 0 3 3 ...
$ bb55 : int 7 6 3 4 4 4 9 2 5 4 ...
$ vabb55: int -3 -1 0 -1 -2 -2 -3 0 -1 3 ...
$ zr : num 0 -2 -1 1 -1 -1 -1 1 1 0 ...
$ z55r : num -2 -2 0 1 -2 -2 -2 1 -1 1 ...
$ fechar: num 0 -1 1 0 1 1 0 0 1 0 ...
$ varr : num 3 3 1 1 1 1 4 1 1 3 ...
$ minmax: int 3 0 4 6 6 6 0 6 6 1 ...
# For solution
t1=Sys.time()
for(i in 1:ncol(mm2N)) mm2N[,i]=as.factor(mm2N[,i])
Sys.time()-t1
Time difference of 0.2020121 secs
str(mm2N)
'data.frame': 35487 obs. of 9 variables:
$ bb : Factor w/ 6 levels "1","2","3","4",..: 4 6 2 3 3 2 5 2 1 2 ...
$ vabb : Factor w/ 7 levels "-3","-2","-1",..: 1 1 2 2 1 3 4 4 7 7 ...
$ bb55 : Factor w/ 8 levels "2","3","4","5",..: 6 5 2 3 3 3 8 1 4 3 ...
$ vabb55: Factor w/ 7 levels "-3","-2","-1",..: 1 3 4 3 2 2 1 4 3 7 ...
$ zr : Factor w/ 5 levels "-2","-1","0",..: 3 1 2 4 2 2 2 4 4 3 ...
$ z55r : Factor w/ 5 levels "-2","-1","0",..: 1 1 3 4 1 1 1 4 2 4 ...
$ fechar: Factor w/ 3 levels "-1","0","1": 2 1 3 2 3 3 2 2 3 2 ...
$ varr : Factor w/ 5 levels "1","2","3","4",..: 3 3 1 1 1 1 4 1 1 3 ...
$ minmax: Factor w/ 7 levels "0","1","2","3",..: 4 1 5 7 7 7 1 7 7 2 ...
#lapply solution
mm2N=mm2New[,10:18]
t1=Sys.time()
mm2N <- lapply(mm2N, as.factor)
Sys.time()-t1
Time difference of 0.209012 secs
str(mm2N)
List of 9
$ bb : Factor w/ 6 levels "1","2","3","4",..: 4 6 2 3 3 2 5 2 1 2 ...
$ vabb : Factor w/ 7 levels "-3","-2","-1",..: 1 1 2 2 1 3 4 4 7 7 ...
$ bb55 : Factor w/ 8 levels "2","3","4","5",..: 6 5 2 3 3 3 8 1 4 3 ...
$ vabb55: Factor w/ 7 levels "-3","-2","-1",..: 1 3 4 3 2 2 1 4 3 7 ...
$ zr : Factor w/ 5 levels "-2","-1","0",..: 3 1 2 4 2 2 2 4 4 3 ...
$ z55r : Factor w/ 5 levels "-2","-1","0",..: 1 1 3 4 1 1 1 4 2 4 ...
$ fechar: Factor w/ 3 levels "-1","0","1": 2 1 3 2 3 3 2 2 3 2 ...
$ varr : Factor w/ 5 levels "1","2","3","4",..: 3 3 1 1 1 1 4 1 1 3 ...
$ minmax: Factor w/ 7 levels "0","1","2","3",..: 4 1 5 7 7 7 1 7 7 2 ...
#data.frame lapply solution
mm2N=mm2New[,10:18]
t1=Sys.time()
mm2N <- data.frame(lapply(mm2N, as.factor))
Sys.time()-t1
Time difference of 0.2010119 secs
str(mm2N)
'data.frame': 35487 obs. of 9 variables:
$ bb : Factor w/ 6 levels "1","2","3","4",..: 4 6 2 3 3 2 5 2 1 2 ...
$ vabb : Factor w/ 7 levels "-3","-2","-1",..: 1 1 2 2 1 3 4 4 7 7 ...
$ bb55 : Factor w/ 8 levels "2","3","4","5",..: 6 5 2 3 3 3 8 1 4 3 ...
$ vabb55: Factor w/ 7 levels "-3","-2","-1",..: 1 3 4 3 2 2 1 4 3 7 ...
$ zr : Factor w/ 5 levels "-2","-1","0",..: 3 1 2 4 2 2 2 4 4 3 ...
$ z55r : Factor w/ 5 levels "-2","-1","0",..: 1 1 3 4 1 1 1 4 2 4 ...
$ fechar: Factor w/ 3 levels "-1","0","1": 2 1 3 2 3 3 2 2 3 2 ...
$ varr : Factor w/ 5 levels "1","2","3","4",..: 3 3 1 1 1 1 4 1 1 3 ...
$ minmax: Factor w/ 7 levels "0","1","2","3",..: 4 1 5 7 7 7 1 7 7 2 ...
You can open it by PhpStorm and right-click on your file and click on Remove BOM...
The <Leader>
key is mapped to \ by default. So if you have a map of <Leader>t
, you can execute it by default with \+t. For more detail or re-assigning it using the mapleader
variable, see
:help leader
To define a mapping which uses the "mapleader" variable, the special string "<Leader>" can be used. It is replaced with the string value of "mapleader". If "mapleader" is not set or empty, a backslash is used instead. Example: :map <Leader>A oanother line <Esc> Works like: :map \A oanother line <Esc> But after: :let mapleader = "," It works like: :map ,A oanother line <Esc> Note that the value of "mapleader" is used at the moment the mapping is defined. Changing "mapleader" after that has no effect for already defined mappings.
protected void Page_Init(object sender, EventArgs e)
{
String hostdet = Request.ServerVariables["HTTP_HOST"].ToString();
}
It seems like two different scenarios are being mixed together in this discussion:
Scenario 1
Using my parent repository's pointers to submodules, I want to check out the commit in each submodule that the parent repository is pointing to, possibly after first iterating through all submodules and updating/pulling these from remote.
This is, as pointed out, done with
git submodule foreach git pull origin BRANCH
git submodule update
Scenario 2, which I think is what OP is aiming at
New stuff has happened in one or more submodules, and I want to 1) pull these changes and 2) update the parent repository to point to the HEAD (latest) commit of this/these submodules.
This would be done by
git submodule foreach git pull origin BRANCH
git add module_1_name
git add module_2_name
......
git add module_n_name
git push origin BRANCH
Not very practical, since you would have to hardcode n paths to all n submodules in e.g. a script to update the parent repository's commit pointers.
It would be cool to have an automated iteration through each submodule, updating the parent repository pointer (using git add
) to point to the head of the submodule(s).
For this, I made this small Bash script:
git-update-submodules.sh
#!/bin/bash
APP_PATH=$1
shift
if [ -z $APP_PATH ]; then
echo "Missing 1st argument: should be path to folder of a git repo";
exit 1;
fi
BRANCH=$1
shift
if [ -z $BRANCH ]; then
echo "Missing 2nd argument (branch name)";
exit 1;
fi
echo "Working in: $APP_PATH"
cd $APP_PATH
git checkout $BRANCH && git pull --ff origin $BRANCH
git submodule sync
git submodule init
git submodule update
git submodule foreach "(git checkout $BRANCH && git pull --ff origin $BRANCH && git push origin $BRANCH) || true"
for i in $(git submodule foreach --quiet 'echo $path')
do
echo "Adding $i to root repo"
git add "$i"
done
git commit -m "Updated $BRANCH branch of deployment repo to point to latest head of submodules"
git push origin $BRANCH
To run it, execute
git-update-submodules.sh /path/to/base/repo BRANCH_NAME
Elaboration
First of all, I assume that the branch with name $BRANCH (second argument) exists in all repositories. Feel free to make this even more complex.
The first couple of sections is some checking that the arguments are there. Then I pull the parent repository's latest stuff (I prefer to use --ff (fast-forwarding) whenever I'm just doing pulls. I have rebase off, BTW).
git checkout $BRANCH && git pull --ff origin $BRANCH
Then some submodule initializing, might be necessary, if new submodules have been added or are not initialized yet:
git submodule sync
git submodule init
git submodule update
Then I update/pull all submodules:
git submodule foreach "(git checkout $BRANCH && git pull --ff origin $BRANCH && git push origin $BRANCH) || true"
Notice a few things: First of all, I'm chaining some Git commands using &&
- meaning previous command must execute without error.
After a possible successful pull (if new stuff was found on the remote), I do a push to ensure that a possible merge-commit is not left behind on the client. Again, it only happens if a pull actually brought in new stuff.
Finally, the final || true
is ensuring that script continues on errors. To make this work, everything in the iteration must be wrapped in the double-quotes and the Git commands are wrapped in parentheses (operator precedence).
My favourite part:
for i in $(git submodule foreach --quiet 'echo $path')
do
echo "Adding $i to root repo"
git add "$i"
done
Iterate all submodules - with --quiet
, which removes the 'Entering MODULE_PATH' output. Using 'echo $path'
(must be in single-quotes), the path to the submodule gets written to output.
This list of relative submodule paths is captured in an array ($(...)
) - finally iterate this and do git add $i
to update the parent repository.
Finally, a commit with some message explaining that the parent repository was updated. This commit will be ignored by default, if nothing was done. Push this to origin, and you're done.
I have a script running this in a Jenkins job that chains to a scheduled automated deployment afterwards, and it works like a charm.
I hope this will be of help to someone.
You are passing a dictionary to a function that expects a string.
This syntax:
{"('Hello',)": 6, "('Hi',)": 5}
is both a valid Python dictionary literal and a valid JSON object literal. But loads
doesn't take a dictionary; it takes a string, which it then interprets as JSON and returns the result as a dictionary (or string or array or number, depending on the JSON, but usually a dictionary).
If you pass this string to loads
:
'''{"('Hello',)": 6, "('Hi',)": 5}'''
then it will return a dictionary that looks a lot like the one you are trying to pass to it.
You could also exploit the similarity of JSON object literals to Python dictionary literals by doing this:
json.loads(str({"('Hello',)": 6, "('Hi',)": 5}))
But in either case you would just get back the dictionary that you're passing in, so I'm not sure what it would accomplish. What's your goal?
I have the same error on amazon AMI linux.
I Solved by setting curl.cainfo on /etc/php.d/curl.ini
https://gist.github.com/reinaldomendes/97fb2ce8a606ec813c4b
Addition October 2018
On Amazon Linux v1 edit this file
vi /etc/php.d/20-curl.ini
To add this line
curl.cainfo="/etc/ssl/certs/ca-bundle.crt"
After writing a single activity, there comes a need to transition to another activity to perform another task either with or without information from the first activity.
Android platform allows transition by means of Intent Interface.
Words are taken from here: Using Intent Demo and i suggest you to go through this example because they also have provided a code file as well. so you can use it and easily understand the same.
document.getElementById("fname").style.borderTopColor = 'red';
document.getElementById("fname").style.borderBottomColor = 'red';
var list1 = new List<Type1>();
var list2 = new List<Type2>();
list1.ForEach(item => list2.Add(new Type2() { Prop1 = value1 }));
In your controller, render the new
action from your create action if validation fails, with an instance variable, @car
populated from the user input (i.e., the params
hash). Then, in your view, add a logic check (either an if block around the form
or a ternary on the helpers, your choice) that automatically sets the value of the form fields to the params
values passed in to @car if car exists. That way, the form will be blank on first visit and in theory only be populated on re-render in the case of error. In any case, they will not be populated unless @car
is set.
Either store it in the gridview datakeys collection, or store it in a hidden field inside the same cell, or join the values together. That is the only way. You can't store two values in one link.
The subprocess module will help you out.
Blatantly trivial example:
>>> import subprocess
>>> subprocess.call(['sh', './test.sh']) # Thanks @Jim Dennis for suggesting the []
0
>>>
Where test.sh
is a simple shell script and 0
is its return value for this run.
>>> test = "have it break."
>>> selectiveEscape = "Print percent %% in sentence and not %s" % test
>>> print selectiveEscape
Print percent % in sentence and not have it break.
find /folder -type f -mtime -90 | grep -E "(.txt|.php|.inc|.root|.gif)" | xargs ls -l > WWWlastActivity.log
You can insert multiple records by inserting from a result:
insert into db (@names,@email,@password)
select 'abc','def','mypassword' union all
select 'abc','def','mypassword' union all
select 'abc','def','mypassword' union all
select 'abc','def','mypassword' union all
select 'abc','def','mypassword' union all
select 'abc','def','mypassword'
Just add as many records you like. There may be limitations on the complexity of the query though, so it might not be possible to add as many as 1000 records at once.
@Nikola Milicevic
Here is the screenshot of the indentation issue. This is very minor, but it is strange that it seems to work so well, in your example visual.
I am also adding a screenshot of my Automator set-up...
Thanks
Update:
If I change the script slightly to:
And then select full lines in XCode, I get the desired outcome:
I agree with Duncan ...I have tried it with mutable object but still get the same problem... I got a simple solution to this... use ListIterator instead Iterator and use set method of ListIterator
ListIterator<Integer> i = a.listIterator();
//changed the value of first element in List
Integer x =null;
if(i.hasNext()) {
x = i.next();
x = Integer.valueOf(9);
}
//set method sets the recent iterated element in ArrayList
i.set(x);
//initialized the iterator again and print all the elements
i = a.listIterator();
while(i.hasNext())
System.out.print(i.next());
But this constraints me to use this only for ArrayList only which can use ListIterator...i will have same problem with any other Collection
If you want to write unit per meter (m^-1)
, use $m^{-1}$)
, which means -1
inbetween {}
Example:
plt.ylabel("Specific Storage Values ($m^{-1}$)", fontsize = 12 )
The return type of a lambda (in C++11) can be deduced, but only when there is exactly one statement, and that statement is a return
statement that returns an expression (an initializer list is not an expression, for example). If you have a multi-statement lambda, then the return type is assumed to be void.
Therefore, you should do this:
remove_if(rawLines.begin(), rawLines.end(), [&expression, &start, &end, &what, &flags](const string& line) -> bool
{
start = line.begin();
end = line.end();
bool temp = boost::regex_search(start, end, what, expression, flags);
return temp;
})
But really, your second expression is a lot more readable.
You probably don't want to do it that way. By putting an explicit sleep()
in your button-clicked event handler, you would actually lock up the whole UI for a second. One alternative is to use some sort of single-shot Timer. Create a TimerTask to change the background color back to the default color, and schedule it on the Timer.
Another possibility is to use a Handler. There's a tutorial about somebody who switched from using a Timer to using a Handler.
Incidentally, you can't pause a process. A Java (or Android) process has at least 1 thread, and you can only sleep threads.
O(1) means the time to access something is independent of the number of items in the collection.
O(N) would mean the time to access an item is a proportional to the number (N) of items in the collection.
This is a late addition but I was looking for information on the scale function myself and though it might help somebody else as well.
To modify the response from Ricardo Saporta a little bit.
Scaling is not done using standard deviation, at least not in version 3.6.1 of R, I base this on "Becker, R. (2018). The new S language. CRC Press." and my own experimentation.
X.man.scaled <- X/sqrt(sum(X^2)/(length(X)-1))
X.aut.scaled <- scale(X, center = F)
The result of these rows are exactly the same, I show it without centering because of simplicity.
I would respond in a comment but did not have enough reputation.
For Windows Server 2012, the solution is very similar to faester's (see above). From the Server Manager, click on Add roles and features
, select the appropriate server, then select Features
. Under .NET Framework 4.5 Features
, you'll see WCF Services
, and under that, you'll find HTTP Activation
.
We can all see that the code you provided won't work at run time. That's because we know that the expression new A()
can never be an object of type B
.
But that's not how the compiler sees it. By the time the compiler is checking whether the cast is allowed, it just sees this:
variable_of_type_B = (B)expression_of_type_A;
And as others have demonstrated, that sort of cast is perfectly legal. The expression on the right could very well evaluate to an object of type B
. The compiler sees that A
and B
have a subtype relation, so with the "expression" view of the code, the cast might work.
The compiler does not consider the special case when it knows exactly what object type expression_of_type_A
will really have. It just sees the static type as A
and considers the dynamic type could be A
or any descendant of A
, including B
.
I experienced a similar problem. Initially, adding the GCC bin folder to my system path did not resolve the problem. I found two solutions.
The first was to run a batch file I found in the root of the MinGW install, mingwbuilds.bat. It (apparently) launches a command prompt configured correctly to run GCC. The second was to remove double-quotation marks from the GCC install bin folder that I had added to my user path variable. I tried this after noticing the batch file not using double-quotes around the install bin path.
Extra Details
I found the batch file accidentally while browsing the install folder tree trying to locate the various executables that weren't launching (according to the -v output). I found some information on the MinGW wiki, http://www.mingw.org/wiki/Getting_Started, in the Cautions and Environment Settings sections, that indicates why the MinGW installer does not set up the system or user path to include the install folder. These seem to confirm the batch file is intended to launch a command prompt suitable for running GCC from a Windows prompt.
This seems like the easiest (but not most robust) way to me. Simply compute the sum from row 6 to the maximum allowed row number, as specified by Excel. According to this site, the maximum is currently 1048576, so the following should work for you:
=sum(c6:c1048576)
For more robust solutions, see the other answers.
Unlike in Python 2, the zip
function in Python 3 returns an iterator. Iterators can only be exhausted (by something like making a list out of them) once. The purpose of this is to save memory by only generating the elements of the iterator as you need them, rather than putting it all into memory at once. If you want to reuse your zipped object, just create a list out of it as you do in your second example, and then duplicate the list by something like
test2 = list(zip(lis1,lis2))
zipped_list = test2[:]
zipped_list_2 = list(test2)
If you're looking for the Hierarchy Viewer tool, it has been changed to Layout Inspector:
https://developer.android.com/studio/debug/layout-inspector.html
<input type='text'
name='t1'
id='t1'
maxlength=10
placeholder='typing some text' >
<p></p>
This is the text box, it has a fixed length of 10 characters, and if you can try but this text box does not contain maximum length 10 character
I would take Jon's suggestion and use Ant, since this is a pretty complex task.
However, if you are determined to get it all in one line in the Terminal, on Linux you could use the find command. But I don't recommend this at all, since there's no guarantee that, say, Foo.java will be compiled after Bar.java, even though Foo
uses Bar
. An example would be:
find . -type f -name "*.java" -exec javac {} \;
If all of your classes haven't been compiled yet, if there's one main harness or driver class (basically the one containing your main method), compiling that main class individually should compile most of project, even if they are in different folders, since Javac will try to the best of its abilities to resolve dependency issues.
You used %H
(24 hour format) instead of %I
(12 hour format).
let's assume your environment name is 'demo' and you are using anaconda and want to create a virtual environment:
(if you want python3)
conda create -n demo python=3
(if you want python2)
conda create -n demo python=2
After running above command you have to activate the environment by bellow command:
source activate demo
So I had a project that required downloading assets from firebase storage, so I had to solve this problem myself. Here is How :
1- First, make a model data for example class Choice{}
, In that class defines a String variable called image Name so it will be like that
class Choice {
.....
String imageName;
}
2- from a database/firebase database, go and hardcode the image names to the objects, so if you have image name called Apple.png, create the object to be
Choice myChoice = new Choice(...,....,"Apple.png");
3- Now, get the link for the assets in your firebase storage which will be something like that
gs://your-project-name.appspot.com/
4- finally, initialize your firebase storage reference and start getting the files by a loop like that
storageRef = storage.getReferenceFromUrl(firebaseRefURL).child(imagePath);
File localFile = File.createTempFile("images", "png");
storageRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
@Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
//Dismiss Progress Dialog\\
}
5- that's it
git pull
= git fetch
+ git merge origin/branch
git pull
and git pull origin branch
only differ in that the latter will only "update" origin/branch and not all origin/* as git pull
does.
git pull origin/branch
will just not work because it's trying to do a git fetch origin/branch
which is invalid.
Question related: git fetch + git merge origin/master vs git pull origin/master
invoke run()
is executing on the calling thread, like any other method call. whereas Thread.start()
creates a new thread.
invoking run()
is a programmatic bug.
Try something like this
jQuery
$('#toggle_icon').toggle(function() {
$('#toggle_icon').text('-');
$('#toggle_text').slideToggle();
}, function() {
$('#toggle_icon').text('+');
$('#toggle_text').slideToggle();
});
HTML
<a href="#" id="toggle_icon">+</a>
<div id="toggle_text" style="display: none">
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s
</div>
To remove the file from the index, use:
git reset myfile
This should not affect your local copy or anyone else's.
Typical usage for conditional removal of error from Model State:
Example:
public ActionResult MyAction(MyViewModel vm)
{
// perform conditional test
// if true, then remove from ModelState (e.g. ModelState.Remove("MyKey")
// Do typical model state validation, inside following if:
// if (!ModelState.IsValid)
// Do rest of logic (e.g. fetching, saving
In your example, keep everything as is and add the logic suggested to your Controller's Action. I'm assuming your ViewModel passed to the controller action has the Person and Senior Person objects with data populated in them from the UI.
Let me report a very simple solution I found, that is not written in previous answers. I also wanted to set background in an SVG, but I also want that this works in a standalone SVG file.
Well, this solution is really simple, in fact SVG supports style tags, so you can do something like
<svg xmlns="http://www.w3.org/2000/svg" width="50" height="50">
<style>svg { background-color: red; }</style>
<text>hello</text>
</svg>
I came up with a much simpler solution instead.
I built a .dll
file using Javascript and then compiled it using the Javascript compiler which is available in a VS2013 developer command prompt.
Once we have the .dll
we simply add it to the \Support
folder and then referenced it in the project which needed to eval Javascript statements.
Detailed Steps to create a .dll
:
Create a file in Notepad with only these contents:
class EvalClass { function Evaluate(expression: String) { return eval(expression); } }
Save the file as C:\MyEval.js
Open a VS2005 Command Prompt (Start, Programs, VS2005, VS2005 Tools)
Type Cd\
to get to C:\
Type
jsc /t:library C:\MyEval.js
A new file is created named MyEval.dll
.
Copy MyEval.dll
to the project and reference it (also reference Microsoft.Jscript.dll
).
Then you should be able to call it like this:
Dim jScriptEvaluator As New EvalClass
Dim objResult As Object
objResult = jScriptEvaluator.Evaluate(“1==1 && 2==2”)
objResult is True
.
This probably will solve your problem:
<?php print_r(array_rand(range(1,50), 5)); ?>
I suggest to have array of buffers and concat to resulting buffer only once at the end. Its easy to do manually, or one could use node-buffers
Firstly, in general:
If these .h
files are indeed typical C-style header files (as opposed to being something completely different that just happens to be named with .h
extension), then no, there's no reason to "compile" these header files independently. Header files are intended to be included into implementation files, not fed to the compiler as independent translation units.
Since a typical header file usually contains only declarations that can be safely repeated in each translation unit, it is perfectly expected that "compiling" a header file will have no harmful consequences. But at the same time it will not achieve anything useful.
Basically, compiling hello.h
as a standalone translation unit equivalent to creating a degenerate dummy.c
file consisting only of #include "hello.h"
directive, and feeding that dummy.c
file to the compiler. It will compile, but it will serve no meaningful purpose.
Secondly, specifically for GCC:
Many compilers will treat files differently depending on the file name extension. GCC has special treatment for files with .h
extension when they are supplied to the compiler as command-line arguments. Instead of treating it as a regular translation unit, GCC creates a precompiled header file for that .h
file.
You can read about it here: http://gcc.gnu.org/onlinedocs/gcc/Precompiled-Headers.html
So, this is the reason you might see .h
files being fed directly to GCC.
Either !=
or ne
will work, but you need to get the accessor syntax and nested quotes sorted out.
<c:if test="${content.contentType.name ne 'MCE'}">
<%-- snip --%>
</c:if>
By the looks of it you need to actually pass drawImage an image object like so
var canvas = document.getElementById("c");_x000D_
var ctx = canvas.getContext("2d");_x000D_
_x000D_
var image = new Image();_x000D_
image.onload = function() {_x000D_
ctx.drawImage(image, 0, 0);_x000D_
};_x000D_
image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oMCRUiMrIBQVkAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAADElEQVQI12NgoC4AAABQAAEiE+h1AAAAAElFTkSuQmCC";
_x000D_
<canvas id="c"></canvas>
_x000D_
I've tried it in chrome and it works fine.
You can use localStorage and its "storage" eventListener to transfer sessionStorage data from one tab to another.
This code would need to exist on ALL tabs. It should execute before your other scripts.
// transfers sessionStorage from one tab to another
var sessionStorage_transfer = function(event) {
if(!event) { event = window.event; } // ie suq
if(!event.newValue) return; // do nothing if no value to work with
if (event.key == 'getSessionStorage') {
// another tab asked for the sessionStorage -> send it
localStorage.setItem('sessionStorage', JSON.stringify(sessionStorage));
// the other tab should now have it, so we're done with it.
localStorage.removeItem('sessionStorage'); // <- could do short timeout as well.
} else if (event.key == 'sessionStorage' && !sessionStorage.length) {
// another tab sent data <- get it
var data = JSON.parse(event.newValue);
for (var key in data) {
sessionStorage.setItem(key, data[key]);
}
}
};
// listen for changes to localStorage
if(window.addEventListener) {
window.addEventListener("storage", sessionStorage_transfer, false);
} else {
window.attachEvent("onstorage", sessionStorage_transfer);
};
// Ask other tabs for session storage (this is ONLY to trigger event)
if (!sessionStorage.length) {
localStorage.setItem('getSessionStorage', 'foobar');
localStorage.removeItem('getSessionStorage', 'foobar');
};
I tested this in chrome, ff, safari, ie 11, ie 10, ie9
This method "should work in IE8" but i could not test it as my IE was crashing every time i opened a tab.... any tab... on any website. (good ol IE) PS: you'll obviously need to include a JSON shim if you want IE8 support as well. :)
Credit goes to this full article: http://blog.guya.net/2015/06/12/sharing-sessionstorage-between-tabs-for-secure-multi-tab-authentication/
There are no difference between ProcessBuilder.start()
and Runtime.exec()
because implementation of Runtime.exec()
is:
public Process exec(String command) throws IOException {
return exec(command, null, null);
}
public Process exec(String command, String[] envp, File dir)
throws IOException {
if (command.length() == 0)
throw new IllegalArgumentException("Empty command");
StringTokenizer st = new StringTokenizer(command);
String[] cmdarray = new String[st.countTokens()];
for (int i = 0; st.hasMoreTokens(); i++)
cmdarray[i] = st.nextToken();
return exec(cmdarray, envp, dir);
}
public Process exec(String[] cmdarray, String[] envp, File dir)
throws IOException {
return new ProcessBuilder(cmdarray)
.environment(envp)
.directory(dir)
.start();
}
So code:
List<String> list = new ArrayList<>();
new StringTokenizer(command)
.asIterator()
.forEachRemaining(str -> list.add((String) str));
new ProcessBuilder(String[])list.toArray())
.environment(envp)
.directory(dir)
.start();
should be the same as:
Runtime.exec(command)
Thanks dave_thompson_085 for comment
As I see no similar answer here - it is worth pointing out that with the usage of a (list / generator) comprehension, you can unpack those multiple values and assign them to multiple variables in a single line of code:
first_val, second_val = (myDict.get(key) for key in [first_key, second_key])
I don't think you can - there is a W3C draft API to get audio or video, but there is no implementation yet on any of the major mobile OSs.
Second best The only option is to go with Dennis' suggestion to use PhoneGap. This will mean you need to create a native app and add it to the mobile app store/marketplace.
If you've got V3, you can take advantage of auto-enumeration, the -Raw switch in Get-Content, and some of the new line contiunation syntax to simply it to this, using the string .replace() method instead of the -replace operator:
(Get-ChildItem "[FILEPATH]" -recurse).FullName |
Foreach-Object {
(Get-Content $_ -Raw).
Replace('abt7d9epp4','w2svuzf54f').
Replace('AccountName=adtestnego','AccountName=zadtestnego').
Replace('AccountKey=eKkij32jGEIYIEqAR5RjkKgf4OTiMO6SAyF68HsR/Zd/KXoKvSdjlUiiWyVV2+OUFOrVsd7jrzhldJPmfBBpQA==','AccountKey=DdOegAhDmLdsou6Ms6nPtP37bdw6EcXucuT47lf9kfClA6PjGTe3CfN+WVBJNWzqcQpWtZf10tgFhKrnN48lXA==') |
Set-Content $_
}
Using the .replace() method uses literal strings for the replaced text argument (not regex), so you don't need to worry about escaping regex metacharacters in the text-to-replace argument.
For me, it was happen due to a miss configuration
Docker port (9093)
Kafka command port "bin/kafka-console-producer.sh --broker-list localhost:9092 --topic TopicName"
I checked my configuration to match port and now everything is ok
SQL Server is not case sensitive. SELECT * FROM SomeTable
is the same as SeLeCT * frOM soMetaBLe
.
I was in the same boat. Installed Eclipse, realized need CDT.
sudo apt-get install eclipse eclipse-cdt g++
This just adds the CDT package on top of existing installation - no un-installation etc. required.
Simple & Easy answer,
The %2C means , comma in URL. when you add the String "abc,defg" in the url as parameter then that comma in the string which is abc , defg is changed to abc%2Cdefg .There is no need to worry about it.
System.Convert works fine by me.
using System;
...
Bool fixed = Convert.ToBoolean(NullableBool);
If you want a solution that also works in /bin/sh
try
first_arg="$1"
shift
echo First argument: "$first_arg"
echo Remaining arguments: "$@"
shift [n]
shifts the positional parameters n times. A shift
sets the value of $1
to the value of $2
, the value of $2
to the value of $3
, and so on, decreasing the value of $#
by one.
As in Oracle you can use NVL function in MySQL you can use IFNULL(columnaName, newValue) to achieve your desired result as in this example
SELECT column_name from table_name WHERE IFNULL(column_name,'') NOT LIKE '%_%';
From what I've read (and please correct me if Im wrong):
Phonegap claim that they started trying to make this but couldn't, so they passed it to the Apache Software Foundation.
Apache in their awesomeness (Long live Apache) fixed it, developed it, and made it supremely awesome.
Now Phonegap are trying to maintain and enhance a copy they took back, but keep stuffing it up.
So, by my thinking, I want a solid and trustworthy dev platform made by seasoned professionals that I can trust, rather than a patched upon sub-version of said. Therefore Id say I am a Cordova developer NOT a Phonegap developer.
Iv also read that in a second desperate attempt to gain popularity and control over the great works of Apache, Phonegap has now been sold under the Adobe flag. You know Adobe, they are the guys who do nothing for free and are so bad at maintaining software life-cycles that their apps need to perform updates every time you blink, and for some reason each of their apps are about 100 times the size you would expect.
I guess that is the summary of my research if I didn't read it wrongly.
And if true, then lets all drop this whole Phonegap nonsense and just stick with Cordova.
The best option in my opinion is to compile a custom LESS file including bootstrap.less, a custom variables.less file and your own rules :
git clone https://github.com/twbs/bootstrap.git
@icon-font-path: "../bootstrap/fonts/";
npm install
grunt watch
Now you can modify the variables any way you want, override bootstrap rules in your custom style.less file, and if some day you want to update bootstrap, you can replace the whole bootstrap folder !
EDIT: I created a Bootstrap boilerplate using this technique : https://github.com/jide/bootstrap-boilerplate
I've recently been struggling with a related issue, discussed at length here: Order of legend entries in ggplot2 barplots with coord_flip() .
As it happens, the reason I had a hard time explaining my issue clearly, involved the relation between (the order of) factors and coord_flip(), as seems to be the case here.
I get the desired result by adding + xlim(rev(levels(x$variable)))
to the ggplot statement:
ggplot(x, aes(x=variable,y=value)) + geom_bar() +
scale_y_continuous("",formatter="percent") + coord_flip()
+ xlim(rev(levels(x$variable)))
This reverses the order of factors as found in the original data frame in the x-axis, which will become the y-axis with coord_flip(). Notice that in this particular example, the variable also happen to be in alphabetical order, but specifying an arbitrary order of levels within xlim()
should work in general.
Yeah I agree with your approach. To merge mobiledevicesupport into master you can use
git checkout master
git pull origin master //Get all latest commits of master branch
git merge mobiledevicesupport
Similarly you can also merge master in mobiledevicesupport.
Q. If cross merging is an issue or not.
A. Well it depends upon the commits made in mobile* branch and master branch from the last time they were synced. Take this example: After last sync, following commits happen to these branches
Master branch: A -> B -> C [where A,B,C are commits]
Mobile branch: D -> E
Now, suppose commit B made some changes to file a.txt and commit D also made some changes to a.txt. Let us have a look at the impact of each operation of merging now,
git checkout master //Switches to master branch
git pull // Get the commits you don't have. May be your fellow workers have made them.
git merge mobiledevicesupport // It will try to add D and E in master branch.
Now, there are two types of merging possible
Git will first try to make FF merge and if it finds any conflicts are not resolvable by git. It fails the merge and asks you to merge. In this case, a new commit will occur which is responsible for resolving conflicts in a.txt.
So Bottom line is Cross merging is not an issue and ultimately you have to do it and that is what syncing means. Make sure you dirty your hands in merging branches before doing anything in production.
When you use EF 6.x code first
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
and initialize a database table, it will put a
(newsequentialid())
inside the table properties under the header Default Value or Binding, allowing the ID to be populated as it is inserted.
The problem is if you create a table and add the
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
part later, future update-databases won't add back the (newsequentialid())
To fix the proper way is to wipe migration, delete database and re-migrate... or you can just add (newsequentialid()) into the table designer.
Make SymbolIndexer( const SymbolIndexer& )
private. If you're assigning to a reference, you're not copying.
I think this is non-restful. I do not think the restful service should handle the requirement of forcing the user to confirm a delete. I would handle this in the UI.
Does specifying force_delete=true make sense if this were a program's API? If someone was writing a script to delete this resource, would you want to force them to specify force_delete=true to actually delete the resource?
if(document.readyState === 'complete') {
DoStuffFunction();
} else {
if (window.addEventListener) {
window.addEventListener('load', DoStuffFunction, false);
} else {
window.attachEvent('onload', DoStuffFunction);
}
}
Here's a solution that keeps things within a dplyr pipe chain. You sort the data in advance, and then using mutate_at to convert to a factor. I've modified the data slightly to show how this solution can be applied generally, given data that can be sensibly sorted:
# the data
temp <- data.frame(type=rep(c("T", "F", "P"), 4),
size=rep(c("50%", "100%", "200%", "150%"), each=3), # cannot sort this
size_num = rep(c(.5, 1, 2, 1.5), each=3), # can sort this
amount=c(48.4, 48.1, 46.8,
25.9, 26.0, 24.9,
20.8, 21.5, 16.5,
21.1, 21.4, 20.1))
temp %>%
arrange(size_num) %>% # sort
mutate_at(vars(size), funs(factor(., levels=unique(.)))) %>% # convert to factor
ggplot() +
geom_bar(aes(x = type, y=amount, fill=type),
position="dodge", stat="identity") +
facet_grid(~ size)
You can apply this solution to arrange the bars within facets, too, though you can only choose a single, preferred order:
temp %>%
arrange(size_num) %>%
mutate_at(vars(size), funs(factor(., levels=unique(.)))) %>%
arrange(desc(amount)) %>%
mutate_at(vars(type), funs(factor(., levels=unique(.)))) %>%
ggplot() +
geom_bar(aes(x = type, y=amount, fill=type),
position="dodge", stat="identity") +
facet_grid(~ size)
ggplot() +
geom_bar(aes(x = type, y=amount, fill=type),
position="dodge", stat="identity") +
facet_grid(~ size)
you can use raiserror
. Read more details here
--from MSDN
BEGIN TRY
-- RAISERROR with severity 11-19 will cause execution to
-- jump to the CATCH block.
RAISERROR ('Error raised in TRY block.', -- Message text.
16, -- Severity.
1 -- State.
);
END TRY
BEGIN CATCH
DECLARE @ErrorMessage NVARCHAR(4000);
DECLARE @ErrorSeverity INT;
DECLARE @ErrorState INT;
SELECT
@ErrorMessage = ERROR_MESSAGE(),
@ErrorSeverity = ERROR_SEVERITY(),
@ErrorState = ERROR_STATE();
-- Use RAISERROR inside the CATCH block to return error
-- information about the original error that caused
-- execution to jump to the CATCH block.
RAISERROR (@ErrorMessage, -- Message text.
@ErrorSeverity, -- Severity.
@ErrorState -- State.
);
END CATCH;
EDIT
If you are using SQL Server 2012+ you can use throw
clause. Here are the details.
I have created the package to-precision that does what you want. It allows you to give your numbers more or less significant figures.
It also outputs standard, scientific, and engineering notation with a specified number of significant figures.
In the accepted answer there is the line
>>> round_to_1(1234243)
1000000.0
That actually specifies 8 sig figs. For the number 1234243 my library only displays one significant figure:
>>> from to_precision import to_precision
>>> to_precision(1234243, 1, 'std')
'1000000'
>>> to_precision(1234243, 1, 'sci')
'1e6'
>>> to_precision(1234243, 1, 'eng')
'1e6'
It will also round the last significant figure and can automatically choose what notation to use if a notation isn't specified:
>>> to_precision(599, 2)
'600'
>>> to_precision(1164, 2)
'1.2e3'
With GCC 4.1.2, to print the whole of a std::vector<int> called myVector, do the following:
print *(myVector._M_impl._M_start)@myVector.size()
To print only the first N elements, do:
print *(myVector._M_impl._M_start)@N
Explanation
This is probably heavily dependent on your compiler version, but for GCC 4.1.2, the pointer to the internal array is:
myVector._M_impl._M_start
And the GDB command to print N elements of an array starting at pointer P is:
print P@N
Or, in a short form (for a standard .gdbinit):
p P@N
I've decided to post my own answer here because I've lost a few hours on this and I think that, although the accepted answer is very good and pointed me in the right direction (yes, it got a voteup), it was not detailed enough to explain what was wrong with my application, at least in my case.
I'm running a BPEL module in OpenESB 2.2 and the Test Case of my Composite Application was failing with the following error:
Caused by: System.Web.Services.Protocols.SoapException: Server did not recognize the value of HTTP Header SOAPAction: .
After doing some research I've noticed that the external WSDL has all the clues we need to fix this problem, e.g., I'm using the following web service to validate a credit card number through a orchestration of Web Services: http://www.webservicex.net/CreditCard.asmx?WSDL
If you check the <wsdl:operation
elements you will see that it clearly states the soapAction
for that operation:
<wsdl:binding name="CCCheckerSoap" type="tns:CCCheckerSoap">
<soap:binding transport="http://schemas.xmlsoap.org/soap/http"/>
<wsdl:operation name="ValidateCardNumber">
<soap:operation soapAction="http://www.webservicex.net/ValidateCardNumber" style="document"/>
<wsdl:input>
<soap:body use="literal"/>
</wsdl:input>
...
But, once you create the Composite Application and build the project with the BPEL that invokes this external WSDL service, for some reason (bug?), the XML of the Composite Application Service Assembly (CASA) binding is generated with an empty soapAction
parameter:
<binding name="casaBinding1" type="ns:CCCheckerSoap">
<soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="ValidateCardNumber">
<soap:operation soapAction="" style="document"/>
<input>
<soap:body use="literal"/>
</input>
Once you copy the proper soapAction (http://www.webservicex.net/ValidateCardNumber) into this parameter, the application's Test Case will correctly and return the expected Soap response.
<soap:operation soapAction="http://www.webservicex.net/ValidateCardNumber" style="document"/>
So, it's a more specific solution that I decided to document based on the information found in this blog post: http://bluebones.net/2003/07/server-did-not-recognize-http-header-soapaction/.
It means (at least in my case) that you are accessing a web service with SOAP and passing a SOAPAction parameter in the HTTP request that does not match what the service is expecting.
As seen here,
$ git remote rm origin
$ git remote add origin [email protected]:aplikacjainfo/proj1.git
$ git config master.remote origin
$ git config master.merge refs/heads/master
I write a code to read file line by line to meet my demand which different line have different data type follow articles: read-line-by-line-of-a-file-in-r and determining-number-of-linesrecords. And it should be a better solution for big file, I think. My R version (3.3.2).
con = file("pathtotargetfile", "r")
readsizeof<-2 # read size for one step to caculate number of lines in file
nooflines<-0 # number of lines
while((linesread<-length(readLines(con,readsizeof)))>0) # calculate number of lines. Also a better solution for big file
nooflines<-nooflines+linesread
con = file("pathtotargetfile", "r") # open file again to variable con, since the cursor have went to the end of the file after caculating number of lines
typelist = list(0,'c',0,'c',0,0,'c',0) # a list to specific the lines data type, which means the first line has same type with 0 (e.g. numeric)and second line has same type with 'c' (e.g. character). This meet my demand.
for(i in 1:nooflines) {
tmp <- scan(file=con, nlines=1, what=typelist[[i]], quiet=TRUE)
print(is.vector(tmp))
print(tmp)
}
close(con)
char ch='A';
System.out.println((int)ch);
public class Demo1 {
Object printType(Object o)
{
return o;
}
public static void main(String[] args) {
Demo1 d=new Demo1();
Object o1=d.printType('C');
System.out.println(o1.getClass().getSimpleName());
}
}
I suggest you to start with simple polynomial fit, scipy.optimize.curve_fit
tries to fit a function f
that you must know to a set of points.
This is a simple 3 degree polynomial fit using numpy.polyfit
and poly1d
, the first performs a least squares polynomial fit and the second calculates the new points:
import numpy as np
import matplotlib.pyplot as plt
points = np.array([(1, 1), (2, 4), (3, 1), (9, 3)])
# get x and y vectors
x = points[:,0]
y = points[:,1]
# calculate polynomial
z = np.polyfit(x, y, 3)
f = np.poly1d(z)
# calculate new x's and y's
x_new = np.linspace(x[0], x[-1], 50)
y_new = f(x_new)
plt.plot(x,y,'o', x_new, y_new)
plt.xlim([x[0]-1, x[-1] + 1 ])
plt.show()
conda info
will display information about the current install, including the active env location which is what you want.
Here's my output:
(base) C:\Users\USERNAME>conda info
active environment : base
active env location : C:\ProgramData\Miniconda3
shell level : 1
user config file : C:\Users\USERNAME\.condarc
populated config files :
conda version : 4.8.2
conda-build version : not installed
python version : 3.7.6.final.0
virtual packages : __cuda=10.2
base environment : C:\ProgramData\Miniconda3 (read only)
channel URLs : https://repo.anaconda.com/pkgs/main/win-64
https://repo.anaconda.com/pkgs/main/noarch
https://repo.anaconda.com/pkgs/r/win-64
https://repo.anaconda.com/pkgs/r/noarch
https://repo.anaconda.com/pkgs/msys2/win-64
https://repo.anaconda.com/pkgs/msys2/noarch
package cache : C:\ProgramData\Miniconda3\pkgs
C:\Users\USERNAME\.conda\pkgs
C:\Users\USERNAME\AppData\Local\conda\conda\pkgs
envs directories : C:\Users\USERNAME\.conda\envs
C:\ProgramData\Miniconda3\envs
C:\Users\USERNAME\AppData\Local\conda\conda\envs
platform : win-64
user-agent : conda/4.8.2 requests/2.22.0 CPython/3.7.6 Windows/10 Windows/10.0.18362
administrator : False
netrc file : None
offline mode : False
If your shell/prompt complains that it cannot find the command, it likely means that you installed Anaconda without adding it to the PATH environment variable.
If that's the case find and open the Anaconda Prompt and do it from there.
Alternatively reinstall Anaconda choosing to add it to the PATH. Or add the variable manually.
Anaconda Prompt should be available in your Start Menu (Win) or Applications Menu (macos)
It's perhaps surprising to note that you don't need to know how many days or months there are in a year or how many days are in those months, likewise, you don't need to know about leap years, leap seconds, or any of that stuff using this simple, 100% accurate method:
public static int age(Date birthday, Date date) {
DateFormat formatter = new SimpleDateFormat("yyyyMMdd");
int d1 = Integer.parseInt(formatter.format(birthday));
int d2 = Integer.parseInt(formatter.format(date));
int age = (d2-d1)/10000;
return age;
}
What I did to solve the problem was:
git pull origin [branch]
git push origin [branch]
Also make sure that you are pointing to the right branch by running:
git remote set-url origin [url]
# >>> conda init >>>
# !! Contents within this block are managed by 'conda init' !!
__conda_setup="$(CONDA_REPORT_ERRORS=false '/anaconda3/bin/conda' shell.bash hook 2> /dev/null)" if [ $? -eq 0 ]; then
\eval "$__conda_setup" else
if [ -f "/anaconda3/etc/profile.d/conda.sh" ]; then
. "/anaconda3/etc/profile.d/conda.sh"
CONDA_CHANGEPS1=false conda activate base
else
\export PATH="/anaconda3/bin:$PATH"
fi fi unset __conda_setup
# <<< conda init <<<
Try:
import simplejson
data = {'apple': 'cat', 'banana':'dog', 'pear':'fish'}
data_json = "{'apple': 'cat', 'banana':'dog', 'pear':'fish'}"
simplejson.loads(data_json) # outputs data
simplejson.dumps(data) # outputs data_joon
NB: Based on Paolo's answer.
You can also look in the registry.
using System.IO;
using Microsoft.Win32;
string GetMimeType(FileInfo fileInfo)
{
string mimeType = "application/unknown";
RegistryKey regKey = Registry.ClassesRoot.OpenSubKey(
fileInfo.Extension.ToLower()
);
if(regKey != null)
{
object contentType = regKey.GetValue("Content Type");
if(contentType != null)
mimeType = contentType.ToString();
}
return mimeType;
}
One way or another you're going to have to tap into a database of MIMEs - whether they're mapped from extensions or magic numbers is somewhat trivial - windows registry is one such place. For a platform independent solution though one would have to ship this DB with the code (or as a standalone library).
The syntax of ng-style
is not quite that. It accepts a dictionary of keys (attribute names) and values (the value they should take, an empty string unsets them) rather than only a string. I think what you want is this:
<div ng-style="{ 'width' : width, 'background' : bgColor }"></div>
And then in your controller:
$scope.width = '900px';
$scope.bgColor = 'red';
This preserves the separation of template and the controller: the controller holds the semantic values while the template maps them to the correct attribute name.
Simply navigate to directory and run following command:
du -a --max-depth=1 | sort -n
OR add -h for human readable sizes and -r to print bigger directories/files first.
du -a -h --max-depth=1 | sort -hr
The PyPA recommended tool for installing and managing Python packages is pip
. pip
is included with Python 3.4 (PEP 453), but for older versions here's how to install it (on Windows, using Python 3.3):
Download https://bootstrap.pypa.io/get-pip.py
>c:\Python33\python.exe get-pip.py
Downloading/unpacking pip
Downloading/unpacking setuptools
Installing collected packages: pip, setuptools
Successfully installed pip setuptools
Cleaning up...
Sample usage:
>c:\Python33\Scripts\pip.exe install pymysql
Downloading/unpacking pymysql
Installing collected packages: pymysql
Successfully installed pymysql
Cleaning up...
In your case it would be this (it appears that pip
caches independent of Python version):
C:\Python27>python.exe \code\Python\get-pip.py
Requirement already up-to-date: pip in c:\python27\lib\site-packages
Collecting wheel
Downloading wheel-0.29.0-py2.py3-none-any.whl (66kB)
100% |################################| 69kB 255kB/s
Installing collected packages: wheel
Successfully installed wheel-0.29.0
C:\Python27>cd Scripts
C:\Python27\Scripts>pip install twilio
Collecting twilio
Using cached twilio-5.3.0.tar.gz
Collecting httplib2>=0.7 (from twilio)
Using cached httplib2-0.9.2.tar.gz
Collecting six (from twilio)
Using cached six-1.10.0-py2.py3-none-any.whl
Collecting pytz (from twilio)
Using cached pytz-2015.7-py2.py3-none-any.whl
Building wheels for collected packages: twilio, httplib2
Running setup.py bdist_wheel for twilio ... done
Stored in directory: C:\Users\Cees.Timmerman\AppData\Local\pip\Cache\wheels\e0\f2\a7\c57f6d153c440b93bd24c1243123f276dcacbf43cc43b7f906
Running setup.py bdist_wheel for httplib2 ... done
Stored in directory: C:\Users\Cees.Timmerman\AppData\Local\pip\Cache\wheels\e1\a3\05\e66aad1380335ee0a823c8f1b9006efa577236a24b3cb1eade
Successfully built twilio httplib2
Installing collected packages: httplib2, six, pytz, twilio
Successfully installed httplib2-0.9.2 pytz-2015.7 six-1.10.0 twilio-5.3.0
UPDATED
I've updated your demo: http://jsfiddle.net/terryyounghk/QS56z/18/
Also, I've changed two ^=
to *=
. See http://api.jquery.com/category/selectors/
And note the :checked
selector. See http://api.jquery.com/checked-selector/
function createcodes() {
//run through each row
$('.authors-list tr').each(function (i, row) {
// reference all the stuff you need first
var $row = $(row),
$family = $row.find('input[name*="family"]'),
$grade = $row.find('input[name*="grade"]'),
$checkedBoxes = $row.find('input:checked');
$checkedBoxes.each(function (i, checkbox) {
// assuming you layout the elements this way,
// we'll take advantage of .next()
var $checkbox = $(checkbox),
$line = $checkbox.next(),
$size = $line.next();
$line.val(
$family.val() + ' ' + $size.val() + ', ' + $grade.val()
);
});
});
}
Just set the container to display:table
and then the inner items to display:table-cell
. Set a height
on the container, and then set vertical-align:middle
on the inner items. This has broad compatibility back as far as the days of IE9.
Just note that the vertical alignment will depend on the height of the parent container.
.cn_x000D_
{_x000D_
display:table;_x000D_
height:80px;_x000D_
background-color:#555;_x000D_
}_x000D_
_x000D_
.inner_x000D_
{_x000D_
display:table-cell;_x000D_
vertical-align:middle;_x000D_
color:#FFF;_x000D_
padding-left:10px;_x000D_
padding-right:10px;_x000D_
}
_x000D_
<div class="cn">_x000D_
<div class="inner">Item 1</div>_x000D_
<div class="inner">Item 2</div>_x000D_
</div>
_x000D_
Goto the SDK manager in your IDE and install the latest "Intel HAXM" and start the emulator.
If it is throwing the error as
Starting emulator for AVD 'X86'
emulator: ERROR: x86 emulation currently requires hardware acceleration!
Please ensure Intel HAXM is properly installed and usable.
CPU acceleration status: HAX is not installed on this machine (/dev/HAX is missing).
It means that some hardware graphical features are to be assigned.So to overcome this problem just go to the path where you have your Adroid SDK
installed.
C:\Android\SDK\extras\intel\Hardware_Accelerated_Execution_Manager
There you can find the file intelhaxm-android.exe
.
On Mac OSXthere is a IntelHAXM_X.X.X.dmg
file, mount it and you'll find an mpkg-file.
Install the file and restart all the applications using android emulator such as(android studio,cmd etc..,).
Now try to open the emulator it will work fine
iOS WebKit debug proxy is the simpliest solution - debug and live preview directly in Chrome.
The %
operator is for integers. You're looking for the fmod()
function.
#include <cmath>
int main()
{
double x = 6.3;
double y = 2.0;
double z = std::fmod(x,y);
}