solution is easy:
replace
mask = (50 < df['heart rate'] < 101 &
140 < df['systolic blood pressure'] < 160 &
90 < df['dyastolic blood pressure'] < 100 &
35 < df['temperature'] < 39 &
11 < df['respiratory rate'] < 19 &
95 < df['pulse oximetry'] < 100
, "excellent", "critical")
by
mask = ((50 < df['heart rate'] < 101) &
(140 < df['systolic blood pressure'] < 160) &
(90 < df['dyastolic blood pressure'] < 100) &
(35 < df['temperature'] < 39) &
(11 < df['respiratory rate'] < 19) &
(95 < df['pulse oximetry'] < 100)
, "excellent", "critical")
http://www.w3schools.com/cssref/css3_pr_animation-keyframes.asp
it is actually a browser issue... use -webkit- for chrome
Your calls are made recursively which pushes functions on to the stack infinitely that causes max call stack exceeded error due to recursive behavior. Instead try using setTimeout which is a callback.
Also based on your markup your selector is wrong. it should be #advisersDiv
function fadeIn() {
$('#pulseDiv').find('div#advisersDiv').delay(400).addClass("pulse");
setTimeout(fadeOut,1); //<-- Provide any delay here
};
function fadeOut() {
$('#pulseDiv').find('div#advisersDiv').delay(400).removeClass("pulse");
setTimeout(fadeIn,1);//<-- Provide any delay here
};
fadeIn();
Here's an example:
#Create a data frame
> d<- data.frame(a=1:3, b=2:4)
> d
a b
1 1 2
2 2 3
3 3 4
#currently, there are no levels in the `a` column, since it's numeric as you point out.
> levels(d$a)
NULL
#Convert that column to a factor
> d$a <- factor(d$a)
> d
a b
1 1 2
2 2 3
3 3 4
#Now it has levels.
> levels(d$a)
[1] "1" "2" "3"
You can also handle this when reading in your data. See the colClasses
and stringsAsFactors
parameters in e.g. readCSV()
.
Note that, computationally, factoring such columns won't help you much, and may actually slow down your program (albeit negligibly). Using a factor will require that all values are mapped to IDs behind the scenes, so any print of your data.frame requires a lookup on those levels -- an extra step which takes time.
Factors are great when storing strings which you don't want to store repeatedly, but would rather reference by their ID. Consider storing a more friendly name in such columns to fully benefit from factors.
You have a lot of unnecessary keyframes. Don't think of keyframes as individual frames, think of them as "steps" in your animation and the computer fills in the frames between the keyframes.
Here is a solution that cleans up a lot of code and makes the animation start from the center:
.gps_ring {
border: 3px solid #999;
-webkit-border-radius: 30px;
height: 18px;
width: 18px;
position: absolute;
left:20px;
top:214px;
-webkit-animation: pulsate 1s ease-out;
-webkit-animation-iteration-count: infinite;
opacity: 0.0
}
@-webkit-keyframes pulsate {
0% {-webkit-transform: scale(0.1, 0.1); opacity: 0.0;}
50% {opacity: 1.0;}
100% {-webkit-transform: scale(1.2, 1.2); opacity: 0.0;}
}
You can see it in action here: http://jsfiddle.net/Fy8vD/
The string in quotes after "[submodule" doesn't matter. You can change it to "foobar" if you want. It's used to find the matching entry in ".git/config".
Therefore, if you make the change before you run "git submodule init", it'll work fine. If you make the change (or pick up the change through a merge), you'll need to either manually edit .git/config or run "git submodule init" again. If you do the latter, you'll be left with a harmless "stranded" entry with the old name in .git/config.
I implemented this code in JavaScript using the HTML Canvas element, and it produced wonderful simulations at 60 frames per second. I started the simulation off with a collection of a dozen balls at random positions and velocities. I found that at higher velocities, a glancing collision between a small ball and a much larger one caused the small ball to appear to STICK to the edge of the larger ball, and moved up to around 90 degrees around the larger ball before separating. (I wonder if anyone else observed this behavior.)
Some logging of the calculations showed that the Minimum Translation Distance in these cases was not large enough to prevent the same balls from colliding in the very next time step. I did some experimenting and found that I could solve this problem by scaling up the MTD based on the relative velocities:
dot_velocity = ball_1.velocity.dot(ball_2.velocity);
mtd_factor = 1. + 0.5 * Math.abs(dot_velocity * Math.sin(collision_angle));
mtd.multplyScalar(mtd_factor);
I verified that before and after this fix, the total kinetic energy was conserved for every collision. The 0.5 value in the mtd_factor was the approximately the minumum value found to always cause the balls to separate after a collision.
Although this fix introduces a small amount of error in the exact physics of the system, the tradeoff is that now very fast balls can be simulated in a browser without decreasing the time step size.
Yes. You can use reflection. Something like this:
Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);
$('#mytable tr').each(function() {
var customerId = $(this).find("td:first").html();
});
What you are doing is iterating through all the trs in the table, finding the first td in the current tr in the loop, and extracting its inner html.
To select a particular cell, you can reference them with an index:
$('#mytable tr').each(function() {
var customerId = $(this).find("td").eq(2).html();
});
In the above code, I will be retrieving the value of the third row (the index is zero-based, so the first cell index would be 0)
Here's how you can do it without jQuery:
var table = document.getElementById('mytable'),
rows = table.getElementsByTagName('tr'),
i, j, cells, customerId;
for (i = 0, j = rows.length; i < j; ++i) {
cells = rows[i].getElementsByTagName('td');
if (!cells.length) {
continue;
}
customerId = cells[0].innerHTML;
}
?
#For scheduling task execution
import schedule
import time
def job():
print("I'm working...")
schedule.every(1).minutes.do(job)
#schedule.every().hour.do(job)
#schedule.every().day.at("10:30").do(job)
#schedule.every(5).to(10).minutes.do(job)
#schedule.every().monday.do(job)
#schedule.every().wednesday.at("13:15").do(job)
#schedule.every().minute.at(":17").do(job)
while True:
schedule.run_pending()
time.sleep(1)
Since Java 8, the best answer is to use Consumer<T>
:
https://docs.oracle.com/javase/8/docs/api/java/util/function/Consumer.html
It's one of the functional interfaces, which means you can call it as a lambda expression:
void doSomething(Consumer<String> something) {
something.accept("hello!");
}
...
doSomething( (something) -> System.out.println(something) )
...
Considering there might be several img
tags I would recommend re.findall
:
import re
with open("sample.txt", 'r') as f_in, open('writetest.txt', 'w') as f_out:
for line in f_in:
for img in re.findall('<img[^>]+>', line):
print >> f_out, "yo it's a {}".format(img)
I faced the same error when displaying YouTube links.
For example: https://www.youtube.com/watch?v=8WkuChVeL0s
I replaced watch?v=
with embed/
so the valid link will be:
https://www.youtube.com/embed/8WkuChVeL0s
It works well.
Try to apply the same rule on your case.
There are many ways to do what you're asking for:
float
property: <div style="width: 100%; overflow: hidden;">
<div style="width: 600px; float: left;"> Left </div>
<div style="margin-left: 620px;"> Right </div>
</div>
_x000D_
display
property - which can be used to make div
s act like a table
:<div style="width: 100%; display: table;">
<div style="display: table-row">
<div style="width: 600px; display: table-cell;"> Left </div>
<div style="display: table-cell;"> Right </div>
</div>
</div>
_x000D_
There are more methods, but those two are the most popular.
Depending on your development environment you may not even have the choice what encoding your string data type will use internally.
But for storing and exchanging data I would always use UTF-8, if you have the choice. If you have mostly ASCII data this will give you the smallest amount of data to transfer, while still being able to encode everything. Optimizing for the least I/O is the way to go on modern machines.
The example below is based on the html5rocks solution. It uses the browser's FileReader() function. Newer browsers only.
See http://www.html5rocks.com/en/tutorials/file/dndfiles/#toc-reading-files
In this example, the user selects an HTML file. It uploaded into the <textarea>
.
<form enctype="multipart/form-data">
<input id="upload" type=file accept="text/html" name="files[]" size=30>
</form>
<textarea class="form-control" rows=35 cols=120 id="ms_word_filtered_html"></textarea>
<script>
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// use the 1st file from the list
f = files[0];
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
jQuery( '#ms_word_filtered_html' ).val( e.target.result );
};
})(f);
// Read in the image file as a data URL.
reader.readAsText(f);
}
document.getElementById('upload').addEventListener('change', handleFileSelect, false);
</script>
Instance methods need to be called from an instance. Your setLoanItem
method is an instance method (it doesn't have the modifier static
), which it needs to be in order to function (because it is setting a value on the instance that it's called on (this
)).
You need to create an instance of the class before you can call the method on it:
Media media = new Media();
media.setLoanItem("Yes");
(Btw it would be better to use a boolean instead of a string containing "Yes".)
#applyCSS > * {
/* Your style */
}
Check this JSfiddle
It will style all children and grandchildren, but will exclude loosely flying text in the div itself and only target wrapped (by tags) content.
In R the equivalent function is seq
and you can use it with the option by
:
seq(from = 5, to = 100, by = 5)
# [1] 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100
In addition to by
you can also have other options such as length.out
and along.with
.
length.out: If you want to get a total of 10 numbers between 0 and 1, for example:
seq(0, 1, length.out = 10)
# gives 10 equally spaced numbers from 0 to 1
along.with: It takes the length of the vector you supply as input and provides a vector from 1:length(input).
seq(along.with=c(10,20,30))
# [1] 1 2 3
Although, instead of using the along.with
option, it is recommended to use seq_along
in this case. From the documentation for ?seq
seq
is generic, and only the default method is described here. Note that it dispatches on the class of the first argument irrespective of argument names. This can have unintended consequences if it is called with just one argument intending this to be taken as along.with: it is much better to useseq_along
in that case.
seq_along: Instead of seq(along.with(.))
seq_along(c(10,20,30))
# [1] 1 2 3
Hope this helps.
Some basic differences can be written in short:
MVC:
Traditional MVC is where there is a
MVP:
Similar to traditional MVC but Controller is replaced by Presenter. But the Presenter, unlike Controller is responsible for changing the view as well. The view usually does not call the presenter.
MVVM
The difference here is the presence of View Model. It is kind of an implementation of Observer Design Pattern, where changes in the model are represented in the view as well, by the VM. Eg: If a slider is changed, not only the model is updated but the data which may be a text, that is displayed in the view is updated as well. So there is a two-way data binding.
For Best solution, Use async/await statement for ecma script 2017
await can use only inside of async function
function sleep(time) {
return new Promise((resolve) => {
setTimeout(resolve, time || 1000);
});
}
await sleep(10000); //this method wait for 10 sec.
Note : async / await not actualy stoped thread like Thread.sleep but simulate it
List indexes of -x mean the xth item from the end of the list, so n[-1]
means the last item in the list n
. Any good Python tutorial should have told you this.
It's an unusual convention that only a few other languages besides Python have adopted, but it is extraordinarily useful; in any other language you'll spend a lot of time writing n[n.length-1]
to access the last item of a list.
None of these were working for me, couldn't delete or disconnect current users. Also couldn't see any active connections to the DB. Restarting SQL Server (Right click and select Restart) allowed me to do it.
Yes, its a typing error.
Write
autoPlay
not
autoplay
The autoplay-plugin code defines the variable as "autoPlay".
import numpy as np
df['New_ID']=np.arange(880,880+len(df.Fruit))
df=df.reindex(columns=['New_ID','ID','Fruit'])
Quite logical the difference between PUT & PATCH w.r.t sending full & partial data for replacing/updating respectively. However, just couple of points as below
Modification from @veeresh i
var data=[
{ id: 1, color: 'yellow' },
{ id: 2, color: 'blue' },
{ id: 3, color: 'red' }
]; //parameter
var para={};
para.datav=data; //datav from View
$.ajax({
traditional: true,
url: "/Conroller/MethodTest",
type: "POST",
contentType: "application/json; charset=utf-8",
data:para,
success: function (data) {
$scope.DisplayError(data.requestStatus);
}
});
In MVC
public class Thing
{
public int id { get; set; }
public string color { get; set; }
}
public JsonResult MethodTest(IEnumerable<Thing> datav)
{
//now datav is having all your values
}
Try this.For swift.
func checkCardValidation(number : String) -> Bool
{
let reversedInts = number.characters.reversed().map { Int(String($0)) }
return reversedInts.enumerated().reduce(0, {(sum, val) in
let odd = val.offset % 2 == 1
return sum + (odd ? (val.element! == 9 ? 9 : (val.element! * 2) % 9) : val.element!)
}) % 10 == 0
}
Use.
if (self.checkCardValidation(number: "yourNumber") == true) {
print("Card Number valid")
}else{
print("Card Number not valid")
}
If you want them both on the same page and they'll both take up basically the whole page, then the best idea is to tell LaTeX to put them both on a page of their own!
\begin{figure}[p]
It would probably be against sound typographic principles (e.g., ugly) to have two figures on a page with only a few lines of text above or below them.
By the way, the reason that [!h]
works is because it's telling LaTeX to override its usual restrictions on how much space should be devoted to floats on a page with text. As implied above, there's a reason the restrictions are there. Which isn't to say they can be loosened somewhat; see the FAQ on doing that.
Put sleep. It will work. I have tried. The reason is that the page wasn't loaded yet. Check this question to know how to wait for load - Wait for page load in Selenium
The CSS table model is based on the HTML table model http://www.w3.org/TR/CSS21/tables.html
A table is divided into ROWS, and each row contains one or more cells. Cells are children of ROWS, they are NEVER children of columns.
"display: table-column" does NOT provide a mechanism for making columnar layouts (e.g. newspaper pages with multiple columns, where content can flow from one column to the next).
Rather, "table-column" ONLY sets attributes that apply to corresponding cells within the rows of a table. E.g. "The background color of the first cell in each row is green" can be described.
The table itself is always structured the same way it is in HTML.
In HTML (observe that "td"s are inside "tr"s, NOT inside "col"s):
<table ..>
<col .. />
<col .. />
<tr ..>
<td ..></td>
<td ..></td>
</tr>
<tr ..>
<td ..></td>
<td ..></td>
</tr>
</table>
Corresponding HTML using CSS table properties (Note that the "column" divs do not contain any contents -- the standard does not allow for contents directly in columns):
.mytable {_x000D_
display: table;_x000D_
}_x000D_
.myrow {_x000D_
display: table-row;_x000D_
}_x000D_
.mycell {_x000D_
display: table-cell;_x000D_
}_x000D_
.column1 {_x000D_
display: table-column;_x000D_
background-color: green;_x000D_
}_x000D_
.column2 {_x000D_
display: table-column;_x000D_
}
_x000D_
<div class="mytable">_x000D_
<div class="column1"></div>_x000D_
<div class="column2"></div>_x000D_
<div class="myrow">_x000D_
<div class="mycell">contents of first cell in row 1</div>_x000D_
<div class="mycell">contents of second cell in row 1</div>_x000D_
</div>_x000D_
<div class="myrow">_x000D_
<div class="mycell">contents of first cell in row 2</div>_x000D_
<div class="mycell">contents of second cell in row 2</div>_x000D_
</div>_x000D_
</div>
_x000D_
OPTIONAL: both "rows" and "columns" can be styled by assigning multiple classes to each row and cell as follows. This approach gives maximum flexibility in specifying various sets of cells, or individual cells, to be styled:
//Useful css declarations, depending on what you want to affect, include:_x000D_
_x000D_
/* all cells (that have "class=mycell") */_x000D_
.mycell {_x000D_
}_x000D_
_x000D_
/* class row1, wherever it is used */_x000D_
.row1 {_x000D_
}_x000D_
_x000D_
/* all the cells of row1 (if you've put "class=mycell" on each cell) */_x000D_
.row1 .mycell {_x000D_
}_x000D_
_x000D_
/* cell1 of row1 */_x000D_
.row1 .cell1 {_x000D_
}_x000D_
_x000D_
/* cell1 of all rows */_x000D_
.cell1 {_x000D_
}_x000D_
_x000D_
/* row1 inside class mytable (so can have different tables with different styles) */_x000D_
.mytable .row1 {_x000D_
}_x000D_
_x000D_
/* all the cells of row1 of a mytable */_x000D_
.mytable .row1 .mycell {_x000D_
}_x000D_
_x000D_
/* cell1 of row1 of a mytable */_x000D_
.mytable .row1 .cell1 {_x000D_
}_x000D_
_x000D_
/* cell1 of all rows of a mytable */_x000D_
.mytable .cell1 {_x000D_
}
_x000D_
<div class="mytable">_x000D_
<div class="column1"></div>_x000D_
<div class="column2"></div>_x000D_
<div class="myrow row1">_x000D_
<div class="mycell cell1">contents of first cell in row 1</div>_x000D_
<div class="mycell cell2">contents of second cell in row 1</div>_x000D_
</div>_x000D_
<div class="myrow row2">_x000D_
<div class="mycell cell1">contents of first cell in row 2</div>_x000D_
<div class="mycell cell2">contents of second cell in row 2</div>_x000D_
</div>_x000D_
</div>
_x000D_
In today's flexible designs, which use <div>
for multiple purposes, it is wise to put some class on each div, to help refer to it. Here, what used to be <tr>
in HTML became class myrow
, and <td>
became class mycell
. This convention is what makes the above CSS selectors useful.
PERFORMANCE NOTE: putting class names on each cell, and using the above multi-class selectors, is better performance than using selectors ending with *
, such as .row1 *
or even .row1 > *
. The reason is that selectors are matched last first, so when matching elements are being sought, .row1 *
first does *
, which matches all elements, and then checks all the ancestors of each element, to find if any ancestor has class row1
. This might be slow in a complex document on a slow device. .row1 > *
is better, because only the immediate parent is examined. But it is much better still to immediately eliminate most elements, via .row1 .cell1
. (.row1 > .cell1
is an even tighter spec, but it is the first step of the search that makes the biggest difference, so it usually isn't worth the clutter, and the extra thought process as to whether it will always be a direct child, of adding the child selector >
.)
The key point to take away re performance is that the last item in a selector should be as specific as possible, and should never be *
.
Another way would by to use another loc utility, like LocMetrics for instance.
It also lists many other loc tools.
The integration with Eclipse wouldn't be always there (as it would be with Metrics2, which you can check out because it is a more recent version than Metrics), but at least those tools can reason in term of logical lines (computed by summing the terminal semicolons and terminal curly braces).
You can also check with eclipse-metrics is more adapted to what you expect.
Here is a better script:
$('#mainimage').click(function(e)
{
var offset_t = $(this).offset().top - $(window).scrollTop();
var offset_l = $(this).offset().left - $(window).scrollLeft();
var left = Math.round( (e.clientX - offset_l) );
var top = Math.round( (e.clientY - offset_t) );
alert("Left: " + left + " Top: " + top);
});
It's generally considered bad practice. The problem is that the constants are part of the public "interface" (for want of a better word) of the implementing class. This means that the implementing class is publishing all of these values to external classes even when they are only required internally. The constants proliferate throughout the code. An example is the SwingConstants interface in Swing, which is implemented by dozens of classes that all "re-export" all of its constants (even the ones that they don't use) as their own.
But don't just take my word for it, Josh Bloch also says it's bad:
The constant interface pattern is a poor use of interfaces. That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class's exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them. Worse, it represents a commitment: if in a future release the class is modified so that it no longer needs to use the constants, it still must implement the interface to ensure binary compatibility. If a nonfinal class implements a constant interface, all of its subclasses will have their namespaces polluted by the constants in the interface.
An enum may be a better approach. Or you could simply put the constants as public static fields in a class that cannot be instantiated. This allows another class to access them without polluting its own API.
This is related to the semantics of the code. By naming the value assigning it to a variable that has a meaningful name (even if it is used only at one place) you give it a meaning. When somebody is reading the code that person will know what that value means.
In general is not a good practice to use constant values across the code. Imagine a code full of string, integer, etc. values. After a time nobody will know what those constants are. Also a typo in a value can be a problem when the value is used on more than one place.
if (value == "") {
// it is empty
}
How about "TIMESTAMPDIFF":
SELECT TIMESTAMPDIFF(SECOND,'2009-05-18','2009-07-29') from `post_statistics`
https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_timestampdiff
I made the following module called unicoder to be able to do the transformation on variables:
import sys
import os
def ustr(string):
string = 'u"%s"'%string
with open('_unicoder.py', 'w') as script:
script.write('# -*- coding: utf-8 -*-\n')
script.write('_ustr = %s'%string)
import _unicoder
value = _unicoder._ustr
del _unicoder
del sys.modules['_unicoder']
os.system('del _unicoder.py')
os.system('del _unicoder.pyc')
return value
Then in your program you could do the following:
# -*- coding: utf-8 -*-
from unicoder import ustr
txt = 'Hello, Unicode World'
txt = ustr(txt)
print type(txt) # <type 'unicode'>
queryParams
queryParams
is another input of routerLink
where they can be passed like
<a [routerLink]="['../']" [queryParams]="{prop: 'xxx'}">Somewhere</a>
fragment
<a [routerLink]="['../']" [queryParams]="{prop: 'xxx'}" [fragment]="yyy">Somewhere</a>
routerLinkActiveOptions
To also get routes active class set on parent routes:
[routerLinkActiveOptions]="{ exact: false }"
To pass query parameters to this.router.navigate(...)
use
let navigationExtras: NavigationExtras = {
queryParams: { 'session_id': sessionId },
fragment: 'anchor'
};
// Navigate to the login page with extras
this.router.navigate(['/login'], navigationExtras);
See also https://angular.io/guide/router#query-parameters-and-fragments
As integers are comparable we can use the following one liner in:
List<Integer> ints = Stream.of(22,44,11,66,33,55).collect(Collectors.toList());
Integer max = ints.stream().mapToInt(i->i).max().orElseThrow(NoSuchElementException::new); //66
Integer min = ints.stream().mapToInt(i->i).min().orElseThrow(NoSuchElementException::new); //11
Another point to note is we cannot use Funtion.identity()
in place of i->i
as mapToInt
expects ToIntFunction
which is a completely different interface and is not related to Function
. Moreover this interface has only one method applyAsInt
and no identity()
method.
You may want to check out Eclipse CDT. It provides a C/C++ IDE that runs on multiple platforms (e.g. Windows, Linux, Mac OS X, etc.). Debugging with Eclipse CDT is comparable to using other tools such as Visual Studio.
You can check out the Eclipse CDT Debug tutorial that also includes a number of screenshots.
Especially if you use a copy-on-write filesystem like BTRFS or ZFS, rsync
is much better.
I use BTRFS, and I have this in my ~/.bashrc
:
alias cp="rsync -ah --inplace --no-whole-file --info=progress2"
The important flag here for CoW FSs like BTRFS is --inplace
because it only copies the changed part of the files, doesn't create new for small changes between files inodes, etc. See this.
INSERT INTO Table2 SELECT DISTINCT ID,Data = STUFF((SELECT ', ' + AA.Data FROM Table1 AS AA WHERE AA.ID = BB.ID FOR XML PATH(''), TYPE).value('.','nvarchar(max)'), 1, 2, '') FROM Table1 AS BB
GROUP BY ID,Data
ORDER BY ID;
You can use the new Bootstrap cards:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>_x000D_
_x000D_
<div class="card-group">_x000D_
<div class="card">_x000D_
<img class="card-img-top" src="..." alt="Card image cap">_x000D_
<div class="card-block">_x000D_
<h4 class="card-title">Card title</h4>_x000D_
<p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>_x000D_
</div>_x000D_
<div class="card-footer">_x000D_
<small class="text-muted">Last updated 3 mins ago</small>_x000D_
</div>_x000D_
</div>_x000D_
<div class="card">_x000D_
<img class="card-img-top" src="..." alt="Card image cap">_x000D_
<div class="card-block">_x000D_
<h4 class="card-title">Card title</h4>_x000D_
<p class="card-text">This card has supporting text below as a natural lead-in to additional content.</p>_x000D_
</div>_x000D_
<div class="card-footer">_x000D_
<small class="text-muted">Last updated 3 mins ago</small>_x000D_
</div>_x000D_
</div>_x000D_
<div class="card">_x000D_
<img class="card-img-top" src="..." alt="Card image cap">_x000D_
<div class="card-block">_x000D_
<h4 class="card-title">Card title</h4>_x000D_
<p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.</p>_x000D_
</div>_x000D_
<div class="card-footer">_x000D_
<small class="text-muted">Last updated 3 mins ago</small>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Link: Click here
regards,
No fancy shiz required:
HTML:
<form method="post" action="/api/admin/image" enctype="multipart/form-data">
<input type="hidden" name="url" value="<%= boxes[i].url %>" />
<input class="image-file-chosen" type="text" />
<br />
<input class="btn image-file-button" value="Choose Image" />
<input class="image-file hide" type="file" name="image"/> <!-- Hidden -->
<br />
<br />
<input class="btn" type="submit" name="image" value="Upload" />
<br />
</form>
JS:
$('.image-file-button').each(function() {
$(this).off('click').on('click', function() {
$(this).siblings('.image-file').trigger('click');
});
});
$('.image-file').each(function() {
$(this).change(function () {
$(this).siblings('.image-file-chosen').val(this.files[0].name);
});
});
CAUTION: The three form elements in question MUST be siblings of each other (.image-file-chosen, .image-file-button, .image-file)
Well, better late than never. Google maps API v3 now provides address autocompletion.
API docs are here: http://code.google.com/apis/maps/documentation/javascript/reference.html#Autocomplete
A good example is here: http://code.google.com/apis/maps/documentation/javascript/examples/places-autocomplete.html
As mentioned in comments, this is a scoping issue. Specifically, $con
is not in scope within your getPosts
function.
You should pass your connection object in as a dependency, eg
function getPosts(mysqli $con) {
// etc
I would also highly recommend halting execution if your connection fails or if errors occur. Something like this should suffice
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // throw exceptions
$con=mysqli_connect("localhost","xxxx","xxxx","xxxxx");
getPosts($con);
You should use the Android AccountManager. It's purpose-built for this scenario. It's a little bit cumbersome but one of the things it does is invalidate the local credentials if the SIM card changes, so if somebody swipes your phone and throws a new SIM in it, your credentials won't be compromised.
This also gives the user a quick and easy way to access (and potentially delete) the stored credentials for any account they have on the device, all from one place.
SampleSyncAdapter (like @Miguel mentioned) is an example that makes use of stored account credentials.
Start an Android Emulator (make sure that all supported APIs are included when you created the emulator, we needed to have the Google APIs for instance).
Then simply email yourself a link to the .apk file, and download it directly in the emulator, and click the downloaded file to install it.
Date is not an Integer in VB(A), it is a Double.
You can get a Date's value by passing it to CDbl()
.
CDbl(Now()) ' 40877.8052662037
From the documentation:
The 1900 Date System
In the 1900 date system, the first day that is supported is January 1, 1900. When you enter a date, the date is converted into a serial number that represents the number of elapsed days starting with 1 for January 1, 1900. For example, if you enter July 5, 1998, Excel converts the date to the serial number 35981.
So in the 1900 system, 40877.805...
represents 40,876 days after January 1, 1900 (29 November 2011), and ~80.5% of one day (~19:19h). There is a setting for 1904-based system in Excel, numbers will be off when this is in use (that's a per-workbook setting).
To get the integer part, use
Int(CDbl(Now())) ' 40877
which would return a LongDouble with no decimal places (i.e. what Floor()
would do in other languages).
Using CLng()
or Round()
would result in rounding, which will return a "day in the future" when called after 12:00 noon, so don't do that.
I threw together some code modified from various sources that will get the results you want, and do a lot more besides. I've allowed for negative int values, int values that exceed the length of the string, and for end index being less than the start index. In that last case, the method returns a reverse-order substring. There are plenty of comments, but let me know if anything is unclear or just crazy. I was playing around with this to see what all I might use it for.
/// <summary>
/// Returns characters slices from string between two indexes.
///
/// If start or end are negative, their indexes will be calculated counting
/// back from the end of the source string.
/// If the end param is less than the start param, the Slice will return a
/// substring in reverse order.
///
/// <param name="source">String the extension method will operate upon.</param>
/// <param name="startIndex">Starting index, may be negative.</param>
/// <param name="endIndex">Ending index, may be negative).</param>
/// </summary>
public static string Slice(this string source, int startIndex, int endIndex = int.MaxValue)
{
// If startIndex or endIndex exceeds the length of the string they will be set
// to zero if negative, or source.Length if positive.
if (source.ExceedsLength(startIndex)) startIndex = startIndex < 0 ? 0 : source.Length;
if (source.ExceedsLength(endIndex)) endIndex = endIndex < 0 ? 0 : source.Length;
// Negative values count back from the end of the source string.
if (startIndex < 0) startIndex = source.Length + startIndex;
if (endIndex < 0) endIndex = source.Length + endIndex;
// Calculate length of characters to slice from string.
int length = Math.Abs(endIndex - startIndex);
// If the endIndex is less than the startIndex, return a reversed substring.
if (endIndex < startIndex) return source.Substring(endIndex, length).Reverse();
return source.Substring(startIndex, length);
}
/// <summary>
/// Reverses character order in a string.
/// </summary>
/// <param name="source"></param>
/// <returns>string</returns>
public static string Reverse(this string source)
{
char[] charArray = source.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
/// <summary>
/// Verifies that the index is within the range of the string source.
/// </summary>
/// <param name="source"></param>
/// <param name="index"></param>
/// <returns>bool</returns>
public static bool ExceedsLength(this string source, int index)
{
return Math.Abs(index) > source.Length ? true : false;
}
So if you have a string like "This is an extension method", here are some examples and results to expect.
var s = "This is an extension method";
// If you want to slice off end characters, just supply a negative startIndex value
// but no endIndex value (or an endIndex value >= to the source string length).
Console.WriteLine(s.Slice(-5));
// Returns "ethod".
Console.WriteLine(s.Slice(-5, 10));
// Results in a startIndex of 22 (counting 5 back from the end).
// Since that is greater than the endIndex of 10, the result is reversed.
// Returns "m noisnetxe"
Console.WriteLine(s.Slice(2, 15));
// Returns "is is an exte"
Hopefully this version is helpful to someone. It operates just like normal if you don't use any negative numbers, and provides defaults for out of range params.
It represents the speed of an algorithm in the long run.
To take a literal analogy, you don't care how fast a runner can sprint a 100m dash, or even a 5k run. You care more about marathoners, and preferably ultra marathoners (beyond which the analogy to running breaks down and you have to revert to the metaphorical meaning of "the long run").
You can safely stop reading here.
I'm adding this answer because I'm surprised how mathematical and technical the rest of the answers are. The notion of the "long run" in first sentence is related to the arbitrarily time-consuming computational tasks. Unlike running, which is limited by human capacity, computational tasks can take even more than millions of years for certain algorithms to complete.
What about all those mathematical logarithms and polynomials? It turns out that algorithms are intrinsically related to these mathematical terms. If you are measuring the heights of all the kids on the block, it will take you as much time as there are kids. This is intrinsically related to the notion of n^1 or just n where n is nothing more than the number of kids on the block. In the ultra-marathon case, you are measuring the heights of all the kids in your city, but you then have to ignore travel times and assume they are all available to you in a line (otherwise we jump ahead of the current explanation).
Suppose then you are trying to arrange the list that you made of of kids heights in order of shortest height to longest height. If it is just the kids in your neighborhood you might just eyeball it and come up with the ordered list. This is the "sprint" analogy, and we truly don't care about sprints in computer science because why use a computer when you can eyeball something?
But if you were arranging the list of the heights of all kids in your city, or better yet, your country, then you will find that how you do it is intrinsically tied to the mathematical log and n^2. Going through your list to find the shortest kid, writing his name in a separate notebook, and crossing it out from the original notebook is intrinsically tied to the mathematical n^2. If you think of arranging half your notebook, then the other half, and then combining the results, you will arrive at a method that is intrinsically tied to the logarithm.
Finally, suppose you first had to go to the store to buy a measuring tape. This is an example of an effort that is of consequence in short sprints, such as measuring the kids on the block, but when you are measuring all the kids in the city you can safely ignore this cost. This is the intrinsic connection to the mathematical dropping of say lower order polynomial terms.
I hope I have explained that the big-O notation is merely about the long run, that the mathematics is inherently connected to ways of computation, and that the dropping of mathematical terms and other simplifications are connected to the long run in a rather common sense way.
Once you realize this, you'll find the big-O is really super-easy because all the hard high school math just drops out easily. The only difficult part is analyzing an algorithm to identify the mathematical terms, but with some practice you can start dropping terms during the analysis itself and safely ignore chunks of the algorithm to focus only on the part that is relevant to the big-O. I. e. you should be able to eyeball most situations.
Happy big-O-ing, it was my favorite thing about Computer Science -- finding that something was way easier than I thought, and then being able to show off at Google interviews when the uninitiated would be intimidated, lol.
Here's a succinct and generic solution to use a seaborn color palette.
First find a color palette you like and optionally visualize it:
sns.palplot(sns.color_palette("Set2", 8))
Then you can use it with matplotlib
doing this:
# Unique category labels: 'D', 'F', 'G', ...
color_labels = df['color'].unique()
# List of RGB triplets
rgb_values = sns.color_palette("Set2", 8)
# Map label to RGB
color_map = dict(zip(color_labels, rgb_values))
# Finally use the mapped values
plt.scatter(df['carat'], df['price'], c=df['color'].map(color_map))
Another approach in 2020 could be using document.querySelector()
:
const myInput = document.querySelector('input[name="exampleInput"]');
myInput.addEventListener("change", (e) => {
// here we do something
});
There is a (somewhat) related question on StackOverflow:
Here the problem was that an array of shape (nx,ny,1) is still considered a 3D array, and must be squeeze
d or sliced into a 2D array.
More generally, the reason for the Exception
TypeError: Invalid dimensions for image data
is shown here: matplotlib.pyplot.imshow()
needs a 2D array, or a 3D array with the third dimension being of shape 3 or 4!
You can easily check this with (these checks are done by imshow
, this function is only meant to give a more specific message in case it's not a valid input):
from __future__ import print_function
import numpy as np
def valid_imshow_data(data):
data = np.asarray(data)
if data.ndim == 2:
return True
elif data.ndim == 3:
if 3 <= data.shape[2] <= 4:
return True
else:
print('The "data" has 3 dimensions but the last dimension '
'must have a length of 3 (RGB) or 4 (RGBA), not "{}".'
''.format(data.shape[2]))
return False
else:
print('To visualize an image the data must be 2 dimensional or '
'3 dimensional, not "{}".'
''.format(data.ndim))
return False
In your case:
>>> new_SN_map = np.array([1,2,3])
>>> valid_imshow_data(new_SN_map)
To visualize an image the data must be 2 dimensional or 3 dimensional, not "1".
False
The np.asarray
is what is done internally by matplotlib.pyplot.imshow
so it's generally best you do it too. If you have a numpy array it's obsolete but if not (for example a list
) it's necessary.
In your specific case you got a 1D array, so you need to add a dimension with np.expand_dims()
import matplotlib.pyplot as plt
a = np.array([1,2,3,4,5])
a = np.expand_dims(a, axis=0) # or axis=1
plt.imshow(a)
plt.show()
or just use something that accepts 1D arrays like plot
:
a = np.array([1,2,3,4,5])
plt.plot(a)
plt.show()
Simply you can do like this:
var formData = new FormData();
formData.append('array[key1]', this.array.key1);
formData.append('array[key2]', this.array.key2);
find($id)
takes an id and returns a single model. If no matching model exist, it returns null
.
findOrFail($id)
takes an id and returns a single model. If no matching model exist, it throws an error1.
first()
returns the first record found in the database. If no matching model exist, it returns null
.
firstOrFail()
returns the first record found in the database. If no matching model exist, it throws an error1.
get()
returns a collection of models matching the query.
pluck($column)
returns a collection of just the values in the given column. In previous versions of Laravel this method was called lists
.
toArray()
converts the model/collection into a simple PHP array.
Note: a collection is a beefed up array. It functions similarly to an array, but has a lot of added functionality, as you can see in the docs.
Unfortunately, PHP doesn't let you use a collection object everywhere you can use an array. For example, using a collection in a foreach
loop is ok, put passing it to array_map
is not. Similarly, if you type-hint an argument as array
, PHP won't let you pass it a collection. Starting in PHP 7.1, there is the iterable
typehint, which can be used to accept both arrays and collections.
If you ever want to get a plain array from a collection, call its all()
method.
1 The error thrown by the findOrFail
and firstOrFail
methods is a ModelNotFoundException
. If you don't catch this exception yourself, Laravel will respond with a 404, which is what you want most of the time.
var moment = require("moment");
var momentDurationFormatSetup = require("moment-duration-format")
var now = "2015-07-16T16:33:39.113Z";
var then = "2015-06-16T22:33:39.113Z";
var ms = moment(now,"YYYY-MM-DD'T'HH:mm:ss:SSSZ").diff(moment(then,"YYYY-MM-DD'T'HH:mm:ss:SSSZ"));
var d = moment.duration(ms);
var s = d.format("dd:hh:mm:ss");
console.log(s);
To create list of lists, you need to separate them with commas, like this
coin_args = [
["pennies", '2.5', '50.0', '.01'],
["nickles", '5.0', '40.0', '.05'],
["dimes", '2.268', '50.0', '.1'],
["quarters", '5.67', '40.0', '.25']
]
From Laravel 5.6 you can use whereDate:
$users = Users::where('status_id', 'active')
->whereDate( 'created_at', '>', now()->subDays(30))
->get();
You also have whereMonth / whereDay / whereYear / whereTime
This is old question, but if somebody finds it today chances are php will be run via php-fpm and mod_fastcgi. In that case nothing here will help with extending execution time because Apache will terminate connection to a process which does not output anything for 30 seconds. Only way to extend it is to change -idle-timeout in apache (module/site/vhost) config.
FastCgiExternalServer /usr/lib/cgi-bin/php7-fcgi -socket /run/php/php7.0-fpm.sock -idle-timeout 900 -pass-header Authorization
More details - Increase PHP-FPM idle timeout setting
During the preflight request, you should see the following two headers: Access-Control-Request-Method and Access-Control-Request-Headers. These request headers are asking the server for permissions to make the actual request. Your preflight response needs to acknowledge these headers in order for the actual request to work.
For example, suppose the browser makes a request with the following headers:
Origin: http://yourdomain.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: X-Custom-Header
Your server should then respond with the following headers:
Access-Control-Allow-Origin: http://yourdomain.com
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: X-Custom-Header
Pay special attention to the Access-Control-Allow-Headers response header. The value of this header should be the same headers in the Access-Control-Request-Headers request header, and it can not be '*'.
Once you send this response to the preflight request, the browser will make the actual request. You can learn more about CORS here: http://www.html5rocks.com/en/tutorials/cors/
Basically the scope of workspace(s) is divided in two points.
First point (and primary) is the eclipse it self and is related with the settings and metadata configurations (plugin ctr). Each time you create a project, eclipse collects all the configurations and stores them on that workspace and if somehow in the same workspace a conflicting project is present you might loose some functionality or even stability of eclipse it self.
And second (secondary) the point of development strategy one can adopt. Once the primary scope is met (and mastered) and there's need for further adjustments regarding project relations (as libraries, perspectives ctr) then initiate separate workspace(s) could be appropriate based on development habits or possible language/frameworks "behaviors". DLTK for examples is a beast that should be contained in a separate cage. Lots of complains at forums for it stopped working (properly or not at all) and suggested solution was to clean the settings of the equivalent plugin from the current workspace.
Personally, I found myself lean more to language distinction when it comes to separate workspaces which is relevant to known issues that comes with the current state of the plugins are used. Preferably I keep them in the minimum numbers as this is leads to less frustration when the projects are become... plenty and version control is not the only version you keep your projects. Finally, loading speed and performance is an issue that might come up if lots of (unnecessary) plugins are loaded due to presents of irrelevant projects. Bottom line; there is no one solution to every one, no master blue print that solves the issue. It's something that grows with experience, Less is more though!
Google Custom Search (as advocated in the top rated answers) works well, but is very expensive, compared to its competitors (below) or compared to other Google API's. It has a small free tier (100 queries/day) and a very high price of $5 per 1000 query.
They offer the option to upgrade to Site Search, which has slightly better prices, but that is meant for searching one site (your own), so it is really something quite different - not an upgrade.
The main alternatives seem to be:
Bing Search API
https://datamarket.azure.com/dataset/5BA839F1-12CE-4CCE-BF57-A49D98D29A44
Which has a free tier of 5000q/month, and prices starting at 5 query per penny, and no hard limit.
UPDATE: At the end of 2016 this API was shutdown in favour of its Azure counterpart "Cognitive Services Bing Search API":
https://azure.microsoft.com/en-us/services/cognitive-services/search/
See here for a pricing chart, which starts at US$3/m for 1,000 transactions. Unless I'm missing something it is quite expensive.
Yahoo BOSS Search API
UPDATE: Was discontinued on March 31, 2016.
http://developer.yahoo.com/boss/search/
With prices starting at about 12 queries/penny for whole web searches.
And some I haven't heard of before:
http://www.gigablast.com/searchfeed.html
http://www.faroo.com/hp/api/api.html
http://www.entireweb.com/search_api/implementation/
[discontinued - as pointed out below]
There is a bit of discussion of some of these on this SO post.
[got closed for being off-topic and is now gone]
Use a CipherOutputStream
or CipherInputStream
with a Cipher
and your FileInputStream
/ FileOutputStream
.
I would suggest something like Cipher.getInstance("AES/CBC/PKCS5Padding")
for creating the Cipher
class. CBC mode is secure and does not have the vulnerabilities of ECB mode for non-random plaintexts. It should be present in any generic cryptographic library, ensuring high compatibility.
Don't forget to use a Initialization Vector (IV) generated by a secure random generator if you want to encrypt multiple files with the same key. You can prefix the plain IV at the start of the ciphertext. It is always exactly one block (16 bytes) in size.
If you want to use a password, please make sure you do use a good key derivation mechanism (look up password based encryption or password based key derivation). PBKDF2 is the most commonly used Password Based Key Derivation scheme and it is present in most Java runtimes, including Android. Note that SHA-1 is a bit outdated hash function, but it should be fine in PBKDF2, and does currently present the most compatible option.
Always specify the character encoding when encoding/decoding strings, or you'll be in trouble when the platform encoding differs from the previous one. In other words, don't use String.getBytes()
but use String.getBytes(StandardCharsets.UTF_8)
.
To make it more secure, please add cryptographic integrity and authenticity by adding a secure checksum (MAC or HMAC) over the ciphertext and IV, preferably using a different key. Without an authentication tag the ciphertext may be changed in such a way that the change cannot be detected.
Be warned that CipherInputStream
may not report BadPaddingException
, this includes BadPaddingException
generated for authenticated ciphers such as GCM. This would make the streams incompatible and insecure for these kind of authenticated ciphers.
Please try this one works for me:
<ImageView android:id="@+id/image_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:maxWidth="60dp"
android:layout_gravity="center"
android:maxHeight="60dp"
android:scaleType="fitCenter"
android:src="@drawable/icon"
/>
Even though a bit old thread, for those who still looking for the differences:
Aside from layout (space) taken in Hidden and not taken in Collapsed, there is another difference.
If we have custom controls inside this 'Collapsed' main control, the next time we set it to Visible, it will "load" all custom controls. It will not pre-load when window is started.
As for 'Hidden', it will load all custom controls + main control which we set as hidden when the "window" is started.
update your CSS to the following: this should fix
.page {
width: 280px;
border:solid 1px blue;
overflow-x: auto;
}
That solution from the official wiki:
vzctl set $CTID --netfilter full --save
https://openvz.org/VPN_via_the_TUN/TAP_device#Troubleshooting
Maybe this can help:
On Red Hat this worked for me:
export TERM=xterm
further info here: http://www.cloudfarm.it/fix-error-opening-terminal-xterm-256color-unknown-terminal-type/
For testing purposes I use the following:
//return assoc array when called from outside the class it will only contain public properties and values
var_dump(get_object_vars($obj));
Here's are three examples of functions I have in my ~/.bashrc
, that are essentially aliases that accept a parameter:
#Utility required by all below functions.
#https://stackoverflow.com/questions/369758/how-to-trim-whitespace-from-bash-variable#comment21953456_3232433
alias trim="sed -e 's/^[[:space:]]*//g' -e 's/[[:space:]]*\$//g'"
.
:<<COMMENT
Alias function for recursive deletion, with are-you-sure prompt.
Example:
srf /home/myusername/django_files/rest_tutorial/rest_venv/
Parameter is required, and must be at least one non-whitespace character.
Short description: Stored in SRF_DESC
With the following setting, this is *not* added to the history:
export HISTIGNORE="*rm -r*:srf *"
- https://superuser.com/questions/232885/can-you-share-wisdom-on-using-histignore-in-bash
See:
- y/n prompt: https://stackoverflow.com/a/3232082/2736496
- Alias w/param: https://stackoverflow.com/a/7131683/2736496
COMMENT
#SRF_DESC: For "aliaf" command (with an 'f'). Must end with a newline.
SRF_DESC="srf [path]: Recursive deletion, with y/n prompt\n"
srf() {
#Exit if no parameter is provided (if it's the empty string)
param=$(echo "$1" | trim)
echo "$param"
if [ -z "$param" ] #http://tldp.org/LDP/abs/html/comparison-ops.html
then
echo "Required parameter missing. Cancelled"; return
fi
#Actual line-breaks required in order to expand the variable.
#- https://stackoverflow.com/a/4296147/2736496
read -r -p "About to
sudo rm -rf \"$param\"
Are you sure? [y/N] " response
response=${response,,} # tolower
if [[ $response =~ ^(yes|y)$ ]]
then
sudo rm -rf "$param"
else
echo "Cancelled."
fi
}
.
:<<COMMENT
Delete item from history based on its line number. No prompt.
Short description: Stored in HX_DESC
Examples
hx 112
hx 3
See:
- https://unix.stackexchange.com/questions/57924/how-to-delete-commands-in-history-matching-a-given-string
COMMENT
#HX_DESC: For "aliaf" command (with an 'f'). Must end with a newline.
HX_DESC="hx [linenum]: Delete history item at line number\n"
hx() {
history -d "$1"
}
.
:<<COMMENT
Deletes all lines from the history that match a search string, with a
prompt. The history file is then reloaded into memory.
Short description: Stored in HXF_DESC
Examples
hxf "rm -rf"
hxf ^source
Parameter is required, and must be at least one non-whitespace character.
With the following setting, this is *not* added to the history:
export HISTIGNORE="*hxf *"
- https://superuser.com/questions/232885/can-you-share-wisdom-on-using-histignore-in-bash
See:
- https://unix.stackexchange.com/questions/57924/how-to-delete-commands-in-history-matching-a-given-string
COMMENT
#HXF_DESC: For "aliaf" command (with an 'f'). Must end with a newline.
HXF_DESC="hxf [searchterm]: Delete all history items matching search term, with y/n prompt\n"
hxf() {
#Exit if no parameter is provided (if it's the empty string)
param=$(echo "$1" | trim)
echo "$param"
if [ -z "$param" ] #http://tldp.org/LDP/abs/html/comparison-ops.html
then
echo "Required parameter missing. Cancelled"; return
fi
read -r -p "About to delete all items from history that match \"$param\". Are you sure? [y/N] " response
response=${response,,} # tolower
if [[ $response =~ ^(yes|y)$ ]]
then
#Delete all matched items from the file, and duplicate it to a temp
#location.
grep -v "$param" "$HISTFILE" > /tmp/history
#Clear all items in the current sessions history (in memory). This
#empties out $HISTFILE.
history -c
#Overwrite the actual history file with the temp one.
mv /tmp/history "$HISTFILE"
#Now reload it.
history -r "$HISTFILE" #Alternative: exec bash
else
echo "Cancelled."
fi
}
References:
Implicit Wait: During Implicit wait if the Web Driver cannot find it immediately because of its availability, the WebDriver will wait for mentioned time and it will not try to find the element again during the specified time period. Once the specified time is over, it will try to search the element once again the last time before throwing exception. The default setting is zero. Once we set a time, the Web Driver waits for the period of the WebDriver object instance.
Explicit Wait: There can be instance when a particular element takes more than a minute to load. In that case you definitely not like to set a huge time to Implicit wait, as if you do this your browser will going to wait for the same time for every element. To avoid that situation you can simply put a separate time on the required element only. By following this your browser implicit wait time would be short for every element and it would be large for specific element.
Kotlin:
If you needed to draw a bitmap in a View, scaled to FIT.
You can do the proper calculations to set bm the height equal to the container and adjust width, in the case bm width to height ratio is less than container width to height ratio, or the inverse in the opposite scenario.
Images:
// binding.fragPhotoEditDrawCont is the RelativeLayout where is your view
// bm is the Bitmap
val ch = binding.fragPhotoEditDrawCont.height
val cw = binding.fragPhotoEditDrawCont.width
val bh = bm.height
val bw = bm.width
val rc = cw.toFloat() / ch.toFloat()
val rb = bw.toFloat() / bh.toFloat()
if (rb < rc) {
// Bitmap Width to Height ratio is less than Container ratio
// Means, bitmap should pin top and bottom, and have some space on sides.
// _____ ___
// container = |_____| bm = |___|
val bmHeight = ch - 4 //4 for container border
val bmWidth = rb * bmHeight //new width is bm_ratio * bm_height
binding.fragPhotoEditDraw.layoutParams = RelativeLayout.LayoutParams(bmWidth.toInt(), bmHeight)
}
else {
val bmWidth = cw - 4 //4 for container border
val bmHeight = 1f/rb * cw
binding.fragPhotoEditDraw.layoutParams = RelativeLayout.LayoutParams(bmWidth, bmHeight.toInt())
}
This makes sure that redirects work for all combinations of intransparent proxies.
This includes the case client <http> proxy <https> webserver.
# behind proxy
RewriteCond %{HTTP:X-FORWARDED-PROTO} ^http$
RewriteRule (.*) https://%{HTTP_HOST}/$1 [R=301,L]
# plain
RewriteCond %{HTTP:X-FORWARDED-PROTO} ^$
RewriteCond %{REQUEST_SCHEME} ^http$ [NC,OR]
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}/$1 [R=301,L]
It was not asked precisely to remove accent (only special characters), but I needed to.
The solutions givens here works but they don’t remove accent: é, è, etc.
So, before doing epascarello’s solution, you can also do:
var newString = "développeur & intégrateur";_x000D_
_x000D_
newString = replaceAccents(newString);_x000D_
newString = newString.replace(/[^A-Z0-9]+/ig, "_");_x000D_
alert(newString);_x000D_
_x000D_
/**_x000D_
* Replaces all accented chars with regular ones_x000D_
*/_x000D_
function replaceAccents(str) {_x000D_
// Verifies if the String has accents and replace them_x000D_
if (str.search(/[\xC0-\xFF]/g) > -1) {_x000D_
str = str_x000D_
.replace(/[\xC0-\xC5]/g, "A")_x000D_
.replace(/[\xC6]/g, "AE")_x000D_
.replace(/[\xC7]/g, "C")_x000D_
.replace(/[\xC8-\xCB]/g, "E")_x000D_
.replace(/[\xCC-\xCF]/g, "I")_x000D_
.replace(/[\xD0]/g, "D")_x000D_
.replace(/[\xD1]/g, "N")_x000D_
.replace(/[\xD2-\xD6\xD8]/g, "O")_x000D_
.replace(/[\xD9-\xDC]/g, "U")_x000D_
.replace(/[\xDD]/g, "Y")_x000D_
.replace(/[\xDE]/g, "P")_x000D_
.replace(/[\xE0-\xE5]/g, "a")_x000D_
.replace(/[\xE6]/g, "ae")_x000D_
.replace(/[\xE7]/g, "c")_x000D_
.replace(/[\xE8-\xEB]/g, "e")_x000D_
.replace(/[\xEC-\xEF]/g, "i")_x000D_
.replace(/[\xF1]/g, "n")_x000D_
.replace(/[\xF2-\xF6\xF8]/g, "o")_x000D_
.replace(/[\xF9-\xFC]/g, "u")_x000D_
.replace(/[\xFE]/g, "p")_x000D_
.replace(/[\xFD\xFF]/g, "y");_x000D_
}_x000D_
_x000D_
return str;_x000D_
}
_x000D_
I faced exactly same issue. Here is my setting which worked.
'ENGINE': 'django.db.backends.sqlite3',
'NAME': '/home/path/to/your/db/data.sqlite3'
Other setting in case of sqlite3 will be same/default.
And you need to create data.sqlite3.
You don't have JSON. You have a JavaScript data structure consisting of objects, an array, some strings and some numbers.
Use JSON.stringify(object)
to turn it into (a string of) JSON text.
tar.gz file is just a tar file that's been gzipped. Both tar and gzip are available for windows.
If you like GUIs (Graphical user interface), 7zip can pack with both tar and gzip.
For adding multiple query params, this is what worked for me (from here https://forum.vuejs.org/t/vue-router-programmatically-append-to-querystring/3655/5).
an answer above was close … though with Object.assign it will mutate this.$route.query which is not what you want to do … make sure the first argument is {} when doing Object.assign
this.$router.push({ query: Object.assign({}, this.$route.query, { newKey: 'newValue' }) });
No, not all browsers support the sizes
attribute:
Note that some platforms define specific sizes:
manifest.json
if it is present. Plus, Chrome uses the Apple Touch icon for bookmarks.You might want to try screenfly. It worked great for me.
You can also use the pipeline
stage to perform checks on a sub-docunment array
Here's the example using python
(sorry I'm snake people).
db.products.aggregate([
{ '$lookup': {
'from': 'products',
'let': { 'pid': '$products' },
'pipeline': [
{ '$match': { '$expr': { '$in': ['$_id', '$$pid'] } } }
// Add additional stages here
],
'as':'productObjects'
}
])
The catch here is to match all objects in the ObjectId
array
(foreign _id
that is in local
field/prop products
).
You can also clean up or project the foreign records with additional stage
s, as indicated by the comment above.
may be you can write like this:
#graphic {
background-image: url(image.jpg);
background-position: 0 -50px;
width: 200px;
height: 100px;
}
for everything related to Python's style guide: i'd recommend you read PEP8.
To answer your question:
Function names should be lowercase, with words separated by underscores as necessary to improve readability.
The accepted solution is probably the best bet for your purposes, but to actually answer the question in the subject line:
In my app, I have to get the path from URIs and get the URI from paths. The former:
/**
* Gets the corresponding path to a file from the given content:// URI
* @param selectedVideoUri The content:// URI to find the file path from
* @param contentResolver The content resolver to use to perform the query.
* @return the file path as a string
*/
private String getFilePathFromContentUri(Uri selectedVideoUri,
ContentResolver contentResolver) {
String filePath;
String[] filePathColumn = {MediaColumns.DATA};
Cursor cursor = contentResolver.query(selectedVideoUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
filePath = cursor.getString(columnIndex);
cursor.close();
return filePath;
}
The latter (which I do for videos, but can also be used for Audio or Files or other types of stored content by substituting MediaStore.Audio (etc) for MediaStore.Video):
/**
* Gets the MediaStore video ID of a given file on external storage
* @param filePath The path (on external storage) of the file to resolve the ID of
* @param contentResolver The content resolver to use to perform the query.
* @return the video ID as a long
*/
private long getVideoIdFromFilePath(String filePath,
ContentResolver contentResolver) {
long videoId;
Log.d(TAG,"Loading file " + filePath);
// This returns us content://media/external/videos/media (or something like that)
// I pass in "external" because that's the MediaStore's name for the external
// storage on my device (the other possibility is "internal")
Uri videosUri = MediaStore.Video.Media.getContentUri("external");
Log.d(TAG,"videosUri = " + videosUri.toString());
String[] projection = {MediaStore.Video.VideoColumns._ID};
// TODO This will break if we have no matching item in the MediaStore.
Cursor cursor = contentResolver.query(videosUri, projection, MediaStore.Video.VideoColumns.DATA + " LIKE ?", new String[] { filePath }, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(projection[0]);
videoId = cursor.getLong(columnIndex);
Log.d(TAG,"Video ID is " + videoId);
cursor.close();
return videoId;
}
Basically, the DATA
column of MediaStore
(or whichever sub-section of it you're querying) stores the file path, so you use that info to look it up.
Quick summary, you can do either:
Include the JavaFX modules via --module-path
and --add-modules
like in José's answer.
OR
Once you have JavaFX libraries added to your project (either manually or via maven/gradle import), add the module-info.java
file similar to the one specified in this answer. (Note that this solution makes your app modular, so if you use other libraries, you will also need to add statements to require their modules inside the module-info.java
file).
This answer is a supplement to Jose's answer.
The situation is this:
IllegalAccessError
involving an "unnamed module" when trying to launch the app.Excerpt for a stack trace generating an IllegalAccessError
when trying to run a JavaFX app from Intellij Idea:
Exception in Application start method
java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:464)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:363)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)
Caused by: java.lang.RuntimeException: Exception in Application start method
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:900)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
at java.base/java.lang.Thread.run(Thread.java:830)
Caused by: java.lang.IllegalAccessError: class com.sun.javafx.fxml.FXMLLoaderHelper (in unnamed module @0x45069d0e) cannot access class com.sun.javafx.util.Utils (in module javafx.graphics) because module javafx.graphics does not export com.sun.javafx.util to unnamed module @0x45069d0e
at com.sun.javafx.fxml.FXMLLoaderHelper.<clinit>(FXMLLoaderHelper.java:38)
at javafx.fxml.FXMLLoader.<clinit>(FXMLLoader.java:2056)
at org.jewelsea.demo.javafx.springboot.Main.start(Main.java:13)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:846)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:455)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
Exception running application org.jewelsea.demo.javafx.springboot.Main
OK, now you are kind of stuck and have no clue what is going on.
What has actually happened is this:
So it seems everything should be OK. BUT, when you run your application, the code in the JavaFX modules is failing when trying to use reflection to instantiate instances of your application class (when you invoke launch) and your FXML controller classes (when you load FXML). Without some help, this use of reflection can fail in some cases, generating the obscure IllegalAccessError
. This is due to a Java module system security feature which does not allow code from other modules to use reflection on your classes unless you explicitly allow it (and the JavaFX application launcher and FXMLLoader both require reflection in their current implementation in order for them to function correctly).
This is where some of the other answers to this question, which reference module-info.java
, come into the picture.
So let's take a crash course in Java modules:
The key part is this:
4.9. Opens
If we need to allow reflection of private types, but we don't want all of our code exposed, we can use the opens directive to expose specific packages.
But remember, this will open the package up to the entire world, so make sure that is what you want:
module my.module { opens com.my.package; }
So, perhaps you don't want to open your package to the entire world, then you can do:
4.10. Opens … To
Okay, so reflection is great sometimes, but we still want as much security as we can get from encapsulation. We can selectively open our packages to a pre-approved list of modules, in this case, using the opens…to directive:
module my.module { opens com.my.package to moduleOne, moduleTwo, etc.; }
So, you end up creating a src/main/java/module-info.java class which looks like this:
module org.jewelsea.demo.javafx.springboot {
requires javafx.fxml;
requires javafx.controls;
requires javafx.graphics;
opens org.jewelsea.demo.javafx.springboot to javafx.graphics,javafx.fxml;
}
Where, org.jewelsea.demo.javafx.springboot
is the name of the package which contains the JavaFX Application class and JavaFX Controller classes (replace this with the appropriate package name for your application). This tells the Java runtime that it is OK for classes in the javafx.graphics
and javafx.fxml
to invoke reflection on the classes in your org.jewelsea.demo.javafx.springboot
package. Once this is done, and the application is compiled and re-run things will work fine and the IllegalAccessError
generated by JavaFX's use of reflection will no longer occur.
But what if you don't want to create a module-info.java file
If instead of using the the Run button in the top toolbar of IDE to run your application class directly, you instead:
javafx.run
.Run Maven Build
or Debug...
.Then the app will run without the module-info.java
file. I guess this is because the maven plugin is smart enough to dynamically include some kind of settings which allows the app to be reflected on by the JavaFX classes even without a module-info.java
file, though I don't know how this is accomplished.
To get that setting transferred to the Run button in the top toolbar, right-click on the javafx.run
Maven target and choose the option to Create Run/Debug Configuration
for the target. Then you can just choose Run from the top toolbar to execute the Maven target.
It looks to me as though the basic problem is that you have one wait()
call rather than a loop that waits until there are no more children. You also only wait if the last fork()
is successful rather than if at least one fork()
is successful.
You should only use _exit()
if you don't want normal cleanup operations - such as flushing open file streams including stdout
. There are occasions to use _exit()
; this is not one of them. (In this example, you could also, of course, simply have the children return instead of calling exit()
directly because returning from main()
is equivalent to exiting with the returned status. However, most often you would be doing the forking and so on in a function other than main()
, and then exit()
is often appropriate.)
Hacked, simplified version of your code that gives the diagnostics I'd want. Note that your for
loop skipped the first element of the array (mine doesn't).
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main(void)
{
pid_t child_pid, wpid;
int status = 0;
int i;
int a[3] = {1, 2, 1};
printf("parent_pid = %d\n", getpid());
for (i = 0; i < 3; i++)
{
printf("i = %d\n", i);
if ((child_pid = fork()) == 0)
{
printf("In child process (pid = %d)\n", getpid());
if (a[i] < 2)
{
printf("Should be accept\n");
exit(1);
}
else
{
printf("Should be reject\n");
exit(0);
}
/*NOTREACHED*/
}
}
while ((wpid = wait(&status)) > 0)
{
printf("Exit status of %d was %d (%s)\n", (int)wpid, status,
(status > 0) ? "accept" : "reject");
}
return 0;
}
Example output (MacOS X 10.6.3):
parent_pid = 15820
i = 0
i = 1
In child process (pid = 15821)
Should be accept
i = 2
In child process (pid = 15822)
Should be reject
In child process (pid = 15823)
Should be accept
Exit status of 15823 was 256 (accept)
Exit status of 15822 was 0 (reject)
Exit status of 15821 was 256 (accept)
This looks a little ugly. Is it possible to cast an entire stream to a different type? Like cast
Stream<Object>
to aStream<Client>
?
No that wouldn't be possible. This is not new in Java 8. This is specific to generics. A List<Object>
is not a super type of List<String>
, so you can't just cast a List<Object>
to a List<String>
.
Similar is the issue here. You can't cast Stream<Object>
to Stream<Client>
. Of course you can cast it indirectly like this:
Stream<Client> intStream = (Stream<Client>) (Stream<?>)stream;
but that is not safe, and might fail at runtime. The underlying reason for this is, generics in Java are implemented using erasure. So, there is no type information available about which type of Stream
it is at runtime. Everything is just Stream
.
BTW, what's wrong with your approach? Looks fine to me.
Try this:
public void LoadData()
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Stocks;Integrated Security=True;Pooling=False");
SqlDataAdapter sda = new SqlDataAdapter("Select * From [Stocks].[dbo].[product]", con);
DataTable dt = new DataTable();
sda.Fill(dt);
DataGridView1.Rows.Clear();
foreach (DataRow item in dt.Rows)
{
int n = DataGridView1.Rows.Add();
DataGridView1.Rows[n].Cells[0].Value = item["ProductCode"].ToString();
DataGridView1.Rows[n].Cells[1].Value = item["Productname"].ToString();
DataGridView1.Rows[n].Cells[2].Value = item["qty"].ToString();
if ((bool)item["productstatus"])
{
DataGridView1.Rows[n].Cells[3].Value = "Active";
}
else
{
DataGridView1.Rows[n].Cells[3].Value = "Deactive";
}
I have been working with IBM DB2 database for more then decade and now trying to learn PostgreSQL.
It works on PostgreSQL 9.3.4, but does not work on DB2 10.5:
UPDATE B SET
COLUMN1 = A.COLUMN1,
COLUMN2 = A.COLUMN2,
COLUMN3 = A.COLUMN3
FROM A
WHERE A.ID = B.ID
Note: Main problem is FROM cause that is not supported in DB2 and also not in ANSI SQL.
It works on DB2 10.5, but does NOT work on PostgreSQL 9.3.4:
UPDATE B SET
(COLUMN1, COLUMN2, COLUMN3) =
(SELECT COLUMN1, COLUMN2, COLUMN3 FROM A WHERE ID = B.ID)
FINALLY! It works on both PostgreSQL 9.3.4 and DB2 10.5:
UPDATE B SET
COLUMN1 = (SELECT COLUMN1 FROM A WHERE ID = B.ID),
COLUMN2 = (SELECT COLUMN2 FROM A WHERE ID = B.ID),
COLUMN3 = (SELECT COLUMN3 FROM A WHERE ID = B.ID)
For this problem you should:
Check whether the flashlight is available or not?
If so then Turn Off/On
If not then you can do whatever, according to your app needs.
For Checking availability of flash in the device:
You can use the following:
context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
which will return true if a flash is available, false if not.
See:
http://developer.android.com/reference/android/content/pm/PackageManager.html for more information.
For turning on/off flashlight:
I googled out and got this about android.permission.FLASHLIGHT. Android manifests' permission looks promising:
<!-- Allows access to the flashlight -->
<permission android:name="android.permission.FLASHLIGHT"
android:permissionGroup="android.permission-group.HARDWARE_CONTROLS"
android:protectionLevel="normal"
android:label="@string/permlab_flashlight"
android:description="@string/permdesc_flashlight" />
Then make use of Camera and set Camera.Parameters. The main parameter used here is FLASH_MODE_TORCH.
eg.
Code Snippet to turn on camera flashlight.
Camera cam = Camera.open();
Parameters p = cam.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
cam.setParameters(p);
cam.startPreview();
Code snippet to turn off camera led light.
cam.stopPreview();
cam.release();
I just found a project that uses this permission. Check quick-settings' src code. here http://code.google.com/p/quick-settings/ (Note: This link is now broken)
For Flashlight directly look http://code.google.com/p/quick-settings/source/browse/trunk/quick-settings/#quick-settings/src/com/bwx/bequick/flashlight (Note: This link is now broken)
Update6 You could also try to add a SurfaceView as described in this answer LED flashlight on Galaxy Nexus controllable by what API? This seems to be a solution that works on many phones.
Update 5 Major Update
I have found an alternative Link (for the broken links above): http://www.java2s.com/Open-Source/Android/Tools/quick-settings/com.bwx.bequick.flashlight.htm You can now use this link. [Update: 14/9/2012 This link is now broken]
Update 1
Another OpenSource Code : http://code.google.com/p/torch/source/browse/
Update 2
Example showing how to enable the LED on a Motorola Droid: http://code.google.com/p/droidled/
Another Open Source Code :
http://code.google.com/p/covedesigndev/
http://code.google.com/p/search-light/
Update 3 (Widget for turning on/off camera led)
If you want to develop a widget that turns on/off your camera led, then you must refer my answer Widget for turning on/off camera flashlight in android..
Update 4
If you want to set the intensity of light emerging from camera LED you can refer Can I change the LED intensity of an Android device? full post. Note that only rooted HTC devices support this feature.
** Issues:**
There are also some problems while turning On/Off flashlight. eg. for the devices not having FLASH_MODE_TORCH
or even if it has, then flashlight does not turn ON etc.
Typically Samsung creates a lot of problems.
You can refer to problems in the given below list:
Use camera flashlight in Android
Turn ON/OFF Camera LED/flash light in Samsung Galaxy Ace 2.2.1 & Galaxy Tab
Outline: Create two elements: a slider/switch and a trough as a parent of the slider. To toggle the state, switch the slider element between an "on" and an "off" class. In the style for one class, set "left" to 0 and leave "right" the default; for the other class, do the opposite:
<style type="text/css">
.toggleSwitch {
width: ...;
height: ...;
/* add other styling as appropriate to position element */
position: relative;
}
.slider {
background-image: url(...);
position: absolute;
width: ...;
height: ...;
}
.slider.on {
right: 0;
}
.slider.off {
left: 0;
}
</style>
<script type="text/javascript">
function replaceClass(elt, oldClass, newClass) {
var oldRE = RegExp('\\b'+oldClass+'\\b');
elt.className = elt.className.replace(oldRE, newClass);
}
function toggle(elt, on, off) {
var onRE = RegExp('\\b'+on+'\\b');
if (onRE.test(elt.className)) {
elt.className = elt.className.replace(onRE, off);
} else {
replaceClass(elt, off, on);
}
}
</script>
...
<div class="toggleSwitch" onclick="toggle(this.firstChild, 'on', 'off');"><div class="slider off" /></div>
Alternatively, just set the background image for the "on" and "off" states, which is a much easier approach than mucking about with positioning.
Yes, the 3rd template parameter on map
specifies the comparator, which is a binary predicate. Example:
struct ByLength : public std::binary_function<string, string, bool>
{
bool operator()(const string& lhs, const string& rhs) const
{
return lhs.length() < rhs.length();
}
};
int main()
{
typedef map<string, string, ByLength> lenmap;
lenmap mymap;
mymap["one"] = "one";
mymap["a"] = "a";
mymap["fewbahr"] = "foobar";
for( lenmap::const_iterator it = mymap.begin(), end = mymap.end(); it != end; ++it )
cout << it->first << "\n";
}
I go for hypothesys since I can't verify now.
With Apache, if you make a php script on your local machine calling your executable, and then call this script via POST or GET via html/javascript?
would it function?
let me know.
If you want to delete an item from the repository, but keep it locally as an unversioned file/folder, use Extended Context Menu ? Delete (keep local). You have to hold the Shift key while right clicking on the item in the explorer list pane (right pane) in order to see this in the extended context menu.
Delete completely:
right mouse click ? Menu ? Delete
Delete & Keep local:
Shift + right mouse click ? Menu ? Delete
Don't forget to add !important
. Then you can be sure that element really will be in the center:
.col-centered{
float: none !important;
margin: 0 auto !important;
}
1. String otherString = "helen" + character;
2. otherString += character;
This is how to retrieve a Column Name from a DataColumn:
MyDataTable.Columns(1).ColumnName
To get the name of all DataColumns within your DataTable:
Dim name(DT.Columns.Count) As String
Dim i As Integer = 0
For Each column As DataColumn In DT.Columns
name(i) = column.ColumnName
i += 1
Next
References
Not any C-header can be made compatible with C++ by merely wrapping in extern "C". When identifiers in a C-header conflict with C++ keywords the C++ compiler will complain about this.
For example, I have seen the following code fail in a g++ :
extern "C" {
struct method {
int virtual;
};
}
Kinda makes sense, but is something to keep in mind when porting C-code to C++.
The openssl
documentation says that file supplied as the -in
argument must be in PEM format.
Turns out that, contrary to the CA's manual, the certificate returned by the CA which I stored in myCert.cer
is not PEM format rather it is PKCS7.
In order to create my .p12
, I had to first convert the certificate to PEM:
openssl pkcs7 -in myCert.cer -print_certs -out certs.pem
and then execute
openssl pkcs12 -export -out keyStore.p12 -inkey myKey.pem -in certs.pem
Try this : Using this you can select date by last 30 days,
SELECT DATEADD(DAY,-30,GETDATE())
DECLARE @DDate date -- To store the current date
DECLARE @DTime time -- To store the current time
DECLARE @DateTime datetime -- To store the result of the concatenation
;
SET @DDate = GETDATE() -- Getting the current date
SET @DTime = GETDATE() -- Getting the current time
SET @DateTime = CONVERT(datetime, CONVERT(varchar(19), LTRIM(@DDate) + ' ' + LTRIM(@DTime) ));
;
/*
1. LTRIM the date and time do an automatic conversion of both types to string.
2. The inside CONVERT to varchar(19) is needed, because you cannot do a direct conversion to datetime
3. Once the inside conversion is done, the second do the final conversion to datetime.
*/
-- The following select shows the initial variables and the result of the concatenation
SELECT @DDate, @DTime, @DateTime
How to do it programatically :
To enable EditText use:
et.setEnabled(true);
To disable EditText use:
et.setEnabled(false);
The parentheses are poorly placed.
You need to use:
doThrow(new Exception()).when(mockedObject).methodReturningVoid(...);
^
and NOT use:
doThrow(new Exception()).when(mockedObject.methodReturningVoid(...));
^
This is explained in the documentation
https://www.codeproject.com/articles/317700/convert-a-pdf-into-a-series-of-images-using-csharp
I found this GhostScript wrapper to be working like a charm for converting the PDFs to PNGs, page by page.
Usage:
string pdf_filename = @"C:\TEMP\test.pdf";
var pdf2Image = new Cyotek.GhostScript.PdfConversion.Pdf2Image(pdf_filename);
for (var page = 1; page < pdf2Image.PageCount; page++)
{
string png_filename = @"C:\TEMP\test" + page + ".png";
pdf2Image.ConvertPdfPageToImage(png_filename, page);
}
Being built on GhostScript, obviously for commercial application the licensing question remains.
Here's a simple function. It generates a data frame and automatically uses the names of the vectors as values for the first column.
myfunc <- function(a, b, names = NULL) {
setNames(data.frame(c(rep(deparse(substitute(a)), length(a)),
rep(deparse(substitute(b)), length(b))), c(a, b)), names)
}
An example:
x <-c(1,2,3)
y <-c(100,200,300)
x_name <- "cond"
y_name <- "rating"
myfunc(x, y, c(x_name, y_name))
cond rating
1 x 1
2 x 2
3 x 3
4 y 100
5 y 200
6 y 300
sys.exit(myString)
doesn't mean "return this string". If you pass a string to sys.exit
, sys.exit
will consider that string to be an error message, and it will write that string to stderr
. The closest concept to a return value for an entire program is its exit status, which must be an integer.
If you want to capture output written to stderr, you can do something like
python yourscript 2> return_file
You could do something like that in your bash script
output=$((your command here) 2> &1)
This is not guaranteed to capture only the value passed to sys.exit
, though. Anything else written to stderr will also be captured, which might include logging output or stack traces.
example:
test.py
print "something"
exit('ohoh')
t.sh
va=$(python test.py 2>&1)
mkdir $va
bash t.sh
edit
Not sure why but in that case, I would write a main script and two other scripts... Mixing python and bash is pointless unless you really need to.
import script1
import script2
if __name__ == '__main__':
filename = script1.run(sys.args)
script2.run(filename)
I had an issue somebody made a revert to master to my branch, but I was needed to be able to merge it again but the problem is that the revert included all my commit. Lets look at that case we created our feature branch from M1 we merge our feature branch in M3 and revert on it in RM3
M1 -> M2 -> M3 -> M4- > RM3 -> M5
\. /
F1->F2 -
How to make the F2 able to merge to M5?
git checkout master
git checkout -b brach-before-revert
git reset --hard M4
git checkout master
git checkout -b new-feature-branch
git reset --hard M1
git merge --squash brach-before-revert
Please, modern is easier, and faster. On Linux, (pick one)
truncate -s 10G foo
fallocate -l 5G bar
It needs to be stated that truncate
on a file system supporting sparse files will create a sparse file and fallocate
will not. A sparse file is one where the allocation units that make up the file are not actually allocated until used. The meta-data for the file will however take up some considerable space but likely no where near the actual size of the file. You should consult resources about sparse files for more information as there are advantages and disadvantages to this type of file. A non-sparse file has its blocks (allocation units) allocated ahead of time which means the space is reserved as far as the file system sees it. Also fallocate
nor truncate
will not set the contents of the file to a specified value like dd
, instead the contents of a file allocated with fallocate
or truncate
may be any trash value that existed in the allocated units during creation and this behavior may or may not be desired. The dd
is the slowest because it actually writes the value or chunk of data to the entire file stream as specified with it's command line options.
This behavior could potentially be different - depending on file system used and conformance of that file system to any standard or specification. Therefore it is advised that proper research is done to ensure that the appropriate method is used.
The full code then would be this:
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(obj, start) {
for (var i = (start || 0), j = this.length; i < j; i++) {
if (this[i] === obj) { return i; }
}
return -1;
}
}
For a really thorough answer and code to this as well as other array functions check out Stack Overflow question Fixing JavaScript Array functions in Internet Explorer (indexOf, forEach, etc.).
public class secondLargestElement
{
public static void main(String[] args)
{
int []a1={1,0};
secondHigh(a1);
}
public static void secondHigh(int[] arr)
{
try
{
int highest,sec_high;
highest=arr[0];
sec_high=arr[1];
for(int i=1;i<arr.length;i++)
{
if(arr[i]>highest)
{
sec_high=highest;
highest=arr[i];
}
else
// The first condition before the || is to make sure that second highest is not actually same as the highest , think
// about {5,4,5}, you don't want the last 5 to be reported as the sec_high
// The other half after || says if the first two elements are same then also replace the sec_high with incoming integer
// Think about {5,5,4}
if(arr[i]>sec_high && arr[i]<highest || highest==sec_high)
sec_high=arr[i];
}
//System.out.println("high="+highest +"sec"+sec_high);
if(highest==sec_high)
System.out.println("All the elements in the input array are same");
else
System.out.println("The second highest element in the array is:"+ sec_high);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Not enough elements in the array");
//e.printStackTrace();
}
}
}
Create a bool isLoading
and set it to false
. With the help of ternary operator, When user clicks on login button set state of isLoading
to true
. You will get circular loading indicator in place of login button
isLoading ? new PrimaryButton(
key: new Key('login'),
text: 'Login',
height: 44.0,
onPressed: setState((){isLoading = true;}))
: Center(
child: CircularProgressIndicator(),
),
You can see Screenshots how it looks while before login is clicked
In mean time you can run login process and login user. If user credentials are wrong then again you will setState
of isLoading
to false
, such that loading indicator will become invisible and login button visible to user.
By the way, primaryButton used in code is my custom button. You can do same with OnPressed
in button
.
The PerlMonks and PerlDoc links from cartman and Olafur are a great reference - below is my crack at a summary:
my
variables are lexically scoped within a single block defined by {}
or within the same file if not in {}
s. They are not accessible from packages/subroutines defined outside of the same lexical scope / block.
our
variables are scoped within a package/file and accessible from any code that use
or require
that package/file - name conflicts are resolved between packages by prepending the appropriate namespace.
Just to round it out, local
variables are "dynamically" scoped, differing from my
variables in that they are also accessible from subroutines called within the same block.
this is the only way i can think of doing it.
//positive to minus
int a = 5; // starting with 5 to become -5
int b = int a * 2; // b = 10
int c = a - b; // c = - 5;
std::cout << c << endl;
//outputs - 5
//minus to positive
int a = -5; starting with -5 to become 5
int b = a * 2;
// b = -10
int c = a + b
// c = 5
std::cout << c << endl;
//outputs 5
Function examples
int b = 0;
int c = 0;
int positiveToNegative (int a) {
int b = a * 2;
int c = a - b;
return c;
}
int negativeToPositive (int a) {
int b = a * 2;
int c = a + b;
return c;
}
Personally, I'd code it as tinyint and:
Reasons:
It will take on average 8 bytes to store text, 1 byte for tinyint. Over millions of rows, this will make a difference.
What about collation? Is "Daily" the same as "DAILY"? It takes resources to do this kind of comparison.
Finally, what if you want to add "Biweekly" or "Hourly"? This requires a schema change when you could just add new rows to a lookup table.
This should work in all versions of Java
public static void centreWindow(Window frame) {
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);
int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);
frame.setLocation(x, y);
}
Update for swift 4 for Dashrath answer
import UIKit
import EventKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let eventStore = EKEventStore()
eventStore.requestAccess( to: EKEntityType.event, completion:{(granted, error) in
if (granted) && (error == nil) {
let event = EKEvent(eventStore: eventStore)
event.title = "My Event"
event.startDate = Date(timeIntervalSinceNow: TimeInterval())
event.endDate = Date(timeIntervalSinceNow: TimeInterval())
event.notes = "Yeah!!!"
event.calendar = eventStore.defaultCalendarForNewEvents
var event_id = ""
do{
try eventStore.save(event, span: .thisEvent)
event_id = event.eventIdentifier
}
catch let error as NSError {
print("json error: \(error.localizedDescription)")
}
if(event_id != ""){
print("event added !")
}
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
You can use indexOf(). Like:
var Color = ["blue", "black", "brown", "gold"];
var a = Color.indexOf("brown");
alert(a);
The indexOf() method searches the array for the specified item, and returns its position. And return -1 if the item is not found.
If you want to search from end to start, use the lastIndexOf() method:
var Color = ["blue", "black", "brown", "gold"];
var a = Color.lastIndexOf("brown");
alert(a);
The search will start at the specified position, or at the end if no start position is specified, and end the search at the beginning of the array.
Returns -1 if the item is not found.
CREATE TRIGGER clearcamcdr AFTER INSERT ON `asteriskcdrdb`.`cdr`
FOR EACH ROW
BEGIN
SET @INC = (SELECT sip_inc FROM trunks LIMIT 1);
IF NEW.billsec >1 AND NEW.channel LIKE @INC
AND NEW.dstchannel NOT LIKE ""
THEN
insert into `asteriskcdrdb`.`filtre` (id_appel,date_appel,source,destinataire,duree,sens,commentaire,suivi)
values (NEW.id,NEW.calldate,NEW.src,NEW.dstchannel,NEW.billsec,"entrant","","");
END IF;
END$$
Dont try this @ home
In case someone doesn't realize it, one way to do this would be to combine Christophe and RSabet's answers:
from datetime import datetime
import time
fmt = '%Y-%m-%d %H:%M:%S'
d1 = datetime.strptime('2010-01-01 17:31:22', fmt)
d2 = datetime.strptime('2010-01-03 20:15:14', fmt)
diff = d2 -d1
diff_minutes = (diff.days * 24 * 60) + (diff.seconds/60)
print(diff_minutes)
> 3043
For firefox
Either:
<asp:TextBox id="Textbox1" runat="server" autocomplete="off"></asp:TextBox>
Or from the CodeBehind:
Textbox1.Attributes.Add("autocomplete", "off");
The SuppressWarning annotation is used to suppress compiler warnings for the annotated element. Specifically, the unchecked
category allows suppression of compiler warnings generated as a result of unchecked type casts.
Looks like you created a separate question. I was answering your other question How to change flat file source using foreach loop container in an SSIS package? with the same answer. Anyway, here it is again.
Create two string data type variables namely DirPath
and FilePath
. Set the value C:\backup\ to the variable DirPath
. Do not set any value to the variable FilePath
.
Select the variable FilePath
and select F4 to view the properties. Set the EvaluateAsExpression
property to True and set the Expression property as @[User::DirPath] + "Source" + (DT_STR, 4, 1252) DATEPART("yy" , GETDATE()) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("mm" , GETDATE()), 2) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("dd" , GETDATE()), 2)
Please use below trick:
Another solution I have found to a similar error but the same error message is to increase the number of service handlers found. (My instance of this error was caused by too many connections in the Weblogic Portal Connection pools.)
SQL*Plus
and login as SYSTEM
. You should know what password you’ve used during the installation of Oracle DB XE.alter system set processes=150 scope=spfile;
in SQL*PlusFrom here:
To see command-line flags, use:
gcc -march=native -E -v - </dev/null 2>&1 | grep cc1
If you want to see the compiler/precompiler defines set by certain parameters, do this:
echo | gcc -dM -E - -march=native
All data is available under
window.location.search
you have to parse the string, eg.
function get(name){
if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search))
return decodeURIComponent(name[1]);
}
just call the function with GET variable name as parameter, eg.
get('foo');
this function will return the variables value or undefined if variable has no value or doesn't exist
If you don't use a passphrase, then the private key is not encrypted with any symmetric cipher - it is output completely unprotected.
You can generate a keypair, supplying the password on the command-line using an invocation like (in this case, the password is foobar
):
openssl genrsa -aes128 -passout pass:foobar 3072
However, note that this passphrase could be grabbed by any other process running on the machine at the time, since command-line arguments are generally visible to all processes.
A better alternative is to write the passphrase into a temporary file that is protected with file permissions, and specify that:
openssl genrsa -aes128 -passout file:passphrase.txt 3072
Or supply the passphrase on standard input:
openssl genrsa -aes128 -passout stdin 3072
You can also used a named pipe with the file:
option, or a file descriptor.
To then obtain the matching public key, you need to use openssl rsa
, supplying the same passphrase with the -passin
parameter as was used to encrypt the private key:
openssl rsa -passin file:passphrase.txt -pubout
(This expects the encrypted private key on standard input - you can instead read it from a file using -in <file>
).
Example of creating a 3072-bit private and public key pair in files, with the private key pair encrypted with password foobar
:
openssl genrsa -aes128 -passout pass:foobar -out privkey.pem 3072
openssl rsa -in privkey.pem -passin pass:foobar -pubout -out privkey.pub
May be these two links can help you Associate IP addresses with countries
You need only to write:
GRANT DBA TO NewDBA;
Because this already makes the user a DB Administrator
Changed the
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API">
function(){
myMap()
}
</script>
and made it
<script type="text/javascript">
function(){
myMap()
}
</script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API"></script>
It worked :)
readonly properties are used to create a fail-safe code. i really like the Encapsulation posts series of Mark Seemann about properties and backing fields:
http://blog.ploeh.dk/2011/05/24/PokayokeDesignFromSmellToFragrance.aspx
taken from Mark's example:
public class Fragrance : IFragrance
{
private readonly string name;
public Fragrance(string name)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
this.name = name;
}
public string Spread()
{
return this.name;
}
}
in this example you use the readonly name field to make sure the class invariant is always valid. in this case the class composer wanted to make sure the name field is set only once (immutable) and is always present.
This post is just an observation for Python behaviour I encountered. Maybe the advices you read above don't work for you if you made the same thing I did below.
Namely, I have a module which contains global/shared variables (as suggested above):
#sharedstuff.py
globaltimes_randomnode=[]
globalist_randomnode=[]
Then I had the main module which imports the shared stuff with:
import sharedstuff as shared
and some other modules that actually populated these arrays. These are called by the main module. When exiting these other modules I can clearly see that the arrays are populated. But when reading them back in the main module, they were empty. This was rather strange for me (well, I am new to Python). However, when I change the way I import the sharedstuff.py in the main module to:
from globals import *
it worked (the arrays were populated).
Just sayin'
There is, namely the _bittest intrinsic instruction.
In my case I had wrong package imported:
import org.testng.annotations.Test;
instead of
import org.junit.Test;
Beware of your ide autocomplete.
I always use the time-stamp - so its not possible, that the file exists already:
import os
import shutil
import datetime
now = str(datetime.datetime.now())[:19]
now = now.replace(":","_")
src_dir="C:\\Users\\Asus\\Desktop\\Versand Verwaltung\\Versand.xlsx"
dst_dir="C:\\Users\\Asus\\Desktop\\Versand Verwaltung\\Versand_"+str(now)+".xlsx"
shutil.copy(src_dir,dst_dir)
An AXD file is a file used by ASP.NET applications for handling embedded resource requests. It contains instructions for retrieving embedded resources, such as images, JavaScript (.JS) files, and.CSS files.
AXD files are used for injecting resources into the client-side webpage and access them on the server in a standard way.
You could create a custom tag as such:
<html>
<head>
<style>
vr {
display: inline-block;
// This is where you'd set the ruler color
background-color: black;
// This is where you'd set the ruler width
width: 2px;
//this is where you'd set the spacing between the ruler and surrounding text
margin: 0px 5px 0px 5px;
height: 100%;
vertical-align: top;
}
</style>
</head>
<body>
this is text <vr></vr> more text
</body>
</html>
(If anyone knows a way that I could turn this into an "open-ended" tag, like <hr>
let me know and I will edit it in)
Here is an example of how you can use for_each for a map.
std::map<int, int> map;
map.insert(std::pair<int, int>(1, 2));
map.insert(std::pair<int, int>(2, 4));
map.insert(std::pair<int, int>(3, 6));
auto f = [](std::pair<int,int> it) {std::cout << it.first + it.second << std::endl; };
std::for_each(map.begin(), map.end(), f);
I've found out the solution! Thanks to Firebug ;)
//"markers" is an array that I declared which contains all the marker of the map
//"i" is the index of the marker in the array that I want to trigger the OnClick event
//V2 version is:
GEvent.trigger(markers[i], 'click');
//V3 version is:
google.maps.event.trigger(markers[i], 'click');
Also can be done from the environment variable:
export CURL_CA_BUNDLE=""
Scott Murray wrote a great explanation of this[1]. For instance, for the code snippet:
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(0," + h + ")")
.call(xAxis);
He explains using the following:
Note that we use attr() to apply transform as an attribute of g. SVG transforms are quite powerful, and can accept several different kinds of transform definitions, including scales and rotations. But we are keeping it simple here with only a translation transform, which simply pushes the whole g group over and down by some amount.
Translation transforms are specified with the easy syntax of translate(x,y), where x and y are, obviously, the number of horizontal and vertical pixels by which to translate the element.
[1]: From Chapter 8, "Cleaning it up" of Interactive Data Visualization for the Web, which used to be freely available and is now behind a paywall.
Most of the time you don't need conversion:
>>>array([True,True,False,False]) + array([1,2,3,4])
array([2, 3, 3, 4])
The right way to do it is:
yourArray.astype(int)
or
yourArray.astype(float)
I'm using GDB7.1.1, as --help
shows:
gdb [options] --args executable-file [inferior-arguments ...]
IMHO, the order is a bit unintuitive at first.
You can try creating a css for your font with font-face (like explained here)
Step #1
Create a css file with font face and place it somewhere, like in assets/fonts
customfont.css
@font-face {
font-family: YourFontFamily;
src: url("/assets/font/yourFont.otf") format("truetype");
}
Step #2
Add the css to your .angular-cli.json in the styles
config
"styles":[
//...your other styles
"assets/fonts/customFonts.css"
]
Do not forget to restart ng serve
after doing this
Step #3
Use the font in your code
component.css
span {font-family: YourFontFamily; }
This is quick-and-dirty (and not formally valid HTML5), but it seems to work -- and it is inline as per the question:
<table border='1' style='border-collapse:collapse'>
No further styling of <tr>
/<td>
tags is required (for a basic table grid).
An observable allows you to subscribe only whereas a subject allows you to both publish and subscribe.
So a subject allows your services to be used as both a publisher and a subscriber.
As of now, I'm not so good at Observable
so I'll share only an example of Subject
.
Let's understand better with an Angular CLI example. Run the below commands:
npm install -g @angular/cli
ng new angular2-subject
cd angular2-subject
ng serve
Replace the content of app.component.html
with:
<div *ngIf="message">
{{message}}
</div>
<app-home>
</app-home>
Run the command ng g c components/home
to generate the home component. Replace the content of home.component.html
with:
<input type="text" placeholder="Enter message" #message>
<button type="button" (click)="setMessage(message)" >Send message</button>
#message
is the local variable here. Add a property message: string;
to the app.component.ts
's class.
Run this command ng g s service/message
. This will generate a service at src\app\service\message.service.ts
. Provide this service to the app.
Import Subject
into MessageService
. Add a subject too. The final code shall look like this:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class MessageService {
public message = new Subject<string>();
setMessage(value: string) {
this.message.next(value); //it is publishing this value to all the subscribers that have already subscribed to this message
}
}
Now, inject this service in home.component.ts
and pass an instance of it to the constructor. Do this for app.component.ts
too. Use this service instance for passing the value of #message
to the service function setMessage
:
import { Component } from '@angular/core';
import { MessageService } from '../../service/message.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent {
constructor(public messageService:MessageService) { }
setMessage(event) {
console.log(event.value);
this.messageService.setMessage(event.value);
}
}
Inside app.component.ts
, subscribe and unsubscribe (to prevent memory leaks) to the Subject
:
import { Component, OnDestroy } from '@angular/core';
import { MessageService } from './service/message.service';
import { Subscription } from 'rxjs/Subscription';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
message: string;
subscription: Subscription;
constructor(public messageService: MessageService) { }
ngOnInit() {
this.subscription = this.messageService.message.subscribe(
(message) => {
this.message = message;
}
);
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
That's it.
Now, any value entered inside #message
of home.component.html
shall be printed to {{message}}
inside app.component.html
Careful with the eval, the JSON specs http://json.org/js.html recommend something like
var myObject = eval('(' + myJSONtext + ')');
And there may be some more gotchas. There is a plugin for jQuery that will take care of it, i guess:
The differences in practice :
string testString = "";
Console.WriteLine(string.Format("IsNullOrEmpty : {0}", string.IsNullOrEmpty(testString)));
Console.WriteLine(string.Format("IsNullOrWhiteSpace : {0}", string.IsNullOrWhiteSpace(testString)));
Console.ReadKey();
Result :
IsNullOrEmpty : True
IsNullOrWhiteSpace : True
**************************************************************
string testString = " MDS ";
IsNullOrEmpty : False
IsNullOrWhiteSpace : False
**************************************************************
string testString = " ";
IsNullOrEmpty : False
IsNullOrWhiteSpace : True
**************************************************************
string testString = string.Empty;
IsNullOrEmpty : True
IsNullOrWhiteSpace : True
**************************************************************
string testString = null;
IsNullOrEmpty : True
IsNullOrWhiteSpace : True
Instead of using pixels should use em or percentage as it is more adaptive and fluid, better not target devices target your content:
format
supports a percentage floating point precision type:
>>> print "{0:.0%}".format(1./3)
33%
If you don't want integer division, you can import Python3's division from __future__
:
>>> from __future__ import division
>>> 1 / 3
0.3333333333333333
# The above 33% example would could now be written without the explicit
# float conversion:
>>> print "{0:.0f}%".format(1/3 * 100)
33%
# Or even shorter using the format mini language:
>>> print "{:.0%}".format(1/3)
33%
Following up on the answer and link from AlexMart, something like this works:
.controller('MyCtrl', function($scope) {
$scope.$on('$ionicView.enter', function() {
// Code you want executed every time view is opened
console.log('Opened!')
})
})
To answer the question in the title, you create a keystore with the Java Keytool utility that comes with any standard JDK distribution and can be located at %JAVA_HOME%\bin
. On Windows this would usually be C:\Program Files\Java\jre7\bin
.
So on Windows, open a command window and switch to that directory and enter a command like this
keytool -genkey -v -keystore my-release-key.keystore -alias alias_name -keyalg RSA -keysize 2048 -validity 10000
Keytool prompts you to provide passwords for the keystore, provide the Distinguished Name fields and then the password for your key. It then generates the keystore as a file called my-release-key.keystore
in the directory you're in. The keystore and key are protected by the passwords you entered. The keystore contains a single key, valid for 10000 days. The alias_name
is a name that you — will use later, to refer to this keystore when signing your application.
For more information about Keytool, see the documentation at: http://docs.oracle.com/javase/6/docs/technotes/tools/windows/keytool.html
and for more information on signing Android apps go here: http://developer.android.com/tools/publishing/app-signing.html
UTF-8 is not a character set, it's an encoding. The character set for UTF-8 is Unicode. If you want to store Unicode text you use the nvarchar
data type.
If the database would use UTF-8 to store text, you would still not get the text out as encoded UTF-8 data, you would get it out as decoded text.
You can easily store UTF-8 encoded text in the database, but then you don't store it as text, you store it as binary data (varbinary
).
Older version of Express use app.use(express.json())
or bodyParser.json()
read more about bodyParser middleware
On latest version of express we could simply use res.json()
const express = require('express'),
port = process.env.port || 3000,
app = express()
app.get('/', (req, res) => res.json({key: "value"}))
app.listen(port, () => console.log(`Server start at ${port}`))
HTTP Servers tend to reject old browsers and systems.
The page Tech Blog (wh): Most Common User Agents reflects the user-agent property of your current browser in section "Your user agent is:", which can be applied to set the request property "User-Agent" of a java.net.URLConnection
or the system property "http.agent".
import shutil
command = 'ls'
shutil.which(command) is not None
As a one-liner of Jan-Philip Gehrcke Answer:
cmd_exists = lambda x: shutil.which(x) is not None
As a def:
def cmd_exists(cmd):
return shutil.which(cmd) is not None
my_command = 'ls'
any(
(
os.access(os.path.join(path, my_command), os.X_OK)
and os.path.isfile(os.path.join(path, my_command)
)
for path in os.environ["PATH"].split(os.pathsep)
)
This is a one-liner of Jay's Answer, Also here as a lambda func:
cmd_exists = lambda x: any((os.access(os.path.join(path, x), os.X_OK) and os.path.isfile(os.path.join(path, x))) for path in os.environ["PATH"].split(os.pathsep))
cmd_exists('ls')
Or lastly, indented as a function:
def cmd_exists(cmd, path=None):
""" test if path contains an executable file with name
"""
if path is None:
path = os.environ["PATH"].split(os.pathsep)
for prefix in path:
filename = os.path.join(prefix, cmd)
executable = os.access(filename, os.X_OK)
is_not_directory = os.path.isfile(filename)
if executable and is_not_directory:
return True
return False
for iterating through JSON you can use this:
json_object = json.loads(json_file)
for element in json_object:
for value in json_object['Name_OF_YOUR_KEY/ELEMENT']:
print(json_object['Name_OF_YOUR_KEY/ELEMENT']['INDEX_OF_VALUE']['VALUE'])
Step 1:
select object_name, s.sid, s.serial#, p.spid
from v$locked_object l, dba_objects o, v$session s, v$process p
where l.object_id = o.object_id and l.session_id = s.sid and s.paddr = p.addr;
Step 2:
alter system kill session 'sid,serial#'; --`sid` and `serial#` get from step 1
More info: http://www.oracle-base.com/articles/misc/killing-oracle-sessions.php
I assume you wanted columns 1
and 9
?
To select multiple columns at once, use
X = data[:, [1, 9]]
To select one at a time, use
x, y = data[:, 1], data[:, 9]
With names:
data[:, ['Column Name1','Column Name2']]
You can get the names from data.dtype.names
…
I know the topic is a bit old and seems stale, but anyway I was able to use these options:
deploy:
resources:
limits:
cpus: '0.001'
memory: 50M
when using 3.7 version of docker-compose
What helped in my case, was using this command:
docker-compose --compatibility up
--compatibility
flag stands for (taken from the documentation):
If set, Compose will attempt to convert deploy keys in v3 files to their non-Swarm equivalent
Think it's great, that I don't have to revert my docker-compose file back to v2.
I was using ADO.NET and was using SQL Command as:
string query =
"SELECT * " +
"FROM table_name" +
"Where id=@id";
the thing was i missed a whitespace at the end of "FROM table_name"+
So basically it said
string query = "SELECT * FROM table_nameWHERE id=@id";
and this was causing the error.
Hope it helps
Since no one has mentioned this, to add to the no-gutter answer above which works, if you want custom spaced gutters, all you have to do is specify the value in px for the margin left and right properties, and padding left and right properties like so;
.row.no-gutter {
margin-left: 4px;
margin-right: 4px;
}
.row.no-gutter [class*='col-']:not(:first-child),
.row.no-gutter [class*='col-']:not(:last-child) {
padding-right: 4px;
padding-left: 4px;
}
One can look at PlatformUI
in Eclipse for a class with static methods and private constructor with itself being final.
public final class <class name>
{
//static constants
//static memebers
}
Use the AsyncTask class (instead of Runnable). It has a method called onProgressUpdate which can affect the UI (it's invoked in the UI thread).
That worked for me:
input:
[complex(a,b) for a,b in zip([1,2,3],[1,2,3])]
output:
[(1+4j), (2+5j), (3+6j)]
cat * | grep -c string
Try it like this instead, move your myclass items inside a main method:
class UserInput {
public void name() {
System.out.println("This is a test.");
}
}
public class MyClass {
public static void main( String args[] )
{
UserInput input = new UserInput();
input.name();
}
}
First, create staticfiles folder. Inside that folder create css, js, and img folder.
settings.py
import os
PROJECT_DIR = os.path.dirname(__file__)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(PROJECT_DIR, 'myweblabdev.sqlite'),
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media')
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(PROJECT_DIR, 'staticfiles'),
)
main urls.py
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from myweblab import settings
admin.autodiscover()
urlpatterns = patterns('',
.......
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
template
{% load static %}
<link rel="stylesheet" href="{% static 'css/style.css' %}">
Below is the structure of SQL that you may write. You can do multiple joins by using "AND" or "OR".
Select TableA.Col1, TableA.Col2, TableB.Val
FROM TableA,
INNER JOIN TableB
ON TableA.Col1 = TableB.Col1 OR TableA.Col2 = TableB.Col2
From the Solution Explorer window select your form, right-click, click on View Designer. Voila! The form should display.
I tried posting a couple screenshots, but this is my first post; therefore, I could not post any images.
In real life you wish to simulate a signal with white noise. You should add to your signal random points that have Normal Gaussian distribution. If we speak about a device that have sensitivity given in unit/SQRT(Hz) then you need to devise standard deviation of your points from it. Here I give function "white_noise" that does this for you, an the rest of a code is demonstration and check if it does what it should.
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal
"""
parameters:
rhp - spectral noise density unit/SQRT(Hz)
sr - sample rate
n - no of points
mu - mean value, optional
returns:
n points of noise signal with spectral noise density of rho
"""
def white_noise(rho, sr, n, mu=0):
sigma = rho * np.sqrt(sr/2)
noise = np.random.normal(mu, sigma, n)
return noise
rho = 1
sr = 1000
n = 1000
period = n/sr
time = np.linspace(0, period, n)
signal_pure = 100*np.sin(2*np.pi*13*time)
noise = white_noise(rho, sr, n)
signal_with_noise = signal_pure + noise
f, psd = signal.periodogram(signal_with_noise, sr)
print("Mean spectral noise density = ",np.sqrt(np.mean(psd[50:])), "arb.u/SQRT(Hz)")
plt.plot(time, signal_with_noise)
plt.plot(time, signal_pure)
plt.xlabel("time (s)")
plt.ylabel("signal (arb.u.)")
plt.show()
plt.semilogy(f[1:], np.sqrt(psd[1:]))
plt.xlabel("frequency (Hz)")
plt.ylabel("psd (arb.u./SQRT(Hz))")
#plt.axvline(13, ls="dashed", color="g")
plt.axhline(rho, ls="dashed", color="r")
plt.show()
Here is what I follow on My system.
All Projects: There is a projects directory in my home folder i.e. ~/projects
. All the projects rest inside it.
Individual Project: I follow a standardized structure template used by many developers called django-skel for individual projects. It basically takes care of all your static file and media files and all.
Virtual environment: I have a virtualenvs folder inside my home to store all virtual environments in the system i.e. ~/virtualenvs
. This gives me flexibility that I know what all virtual environments I have and can look use easily
The above 3 are the main partitions of My working environment.
All the other parts you mentioned are mostly dependent on project to project basis (i.e. you might use different databases for different projects). So they should reside in their individual projects.
void main(){
var x = "4";
int number = int.parse(x);//STRING to INT
var y = "4.6";
double doubleNum = double.parse(y);//STRING to DOUBLE
var z = 55;
String myStr = z.toString();//INT to STRING
}
int.parse() and double.parse() can throw an error when it couldn't parse the String
try current($xml->code[0]->lat)
it returns element under current pointer of array, which is 0, so you will get value
If you are wondering where you can download the shared library (although this will not work on your client's devices unless you include the dll) here is the link: https://de.osdn.net/projects/mingw/downloads/72215/libgcc-9.2.0-1-mingw32-dll-1.tar.xz/
Look at the traceback:
Traceback (most recent call last):
File "C:\Python33\lib\site-packages\bottle.py", line 821, in _cast
out = iter(out)
TypeError: 'bool' object is not iterable
Your code isn't iterating the value, but the code receiving it is.
The solution is: return an iterable. I suggest that you either convert the bool to a string (str(False)
) or enclose it in a tuple ((False,)
).
Always read the traceback: it's correct, and it's helpful.
I had a simpler solution. Using @apple way but rename main.py to pip.py then put it in your python version scripts folder and add scripts folder to your path access it globally. if you don't want to add it to path you have to cd to scripts and then run pip command.
I use this function to get payload , header , exp(Expiration Time), iat (Issued At) based on this answer
function parseJwt(token) {
try {
// Get Token Header
const base64HeaderUrl = token.split('.')[0];
const base64Header = base64HeaderUrl.replace('-', '+').replace('_', '/');
const headerData = JSON.parse(window.atob(base64Header));
// Get Token payload and date's
const base64Url = token.split('.')[1];
const base64 = base64Url.replace('-', '+').replace('_', '/');
const dataJWT = JSON.parse(window.atob(base64));
dataJWT.header = headerData;
// TODO: add expiration at check ...
return dataJWT;
} catch (err) {
return false;
}
}
const jwtDecoded = parseJwt('YOUR_TOKEN') ;
if(jwtDecoded)
{
console.log(jwtDecoded)
}
One way is that In case of Session Expire, in every action you have to check its session and if it is null then redirect to Login page.
But this is very hectic method
To over come this you need to create your own ActionFilterAttribute
which will do this, you just need to add this attribute in every action method.
Here is the Class which overrides ActionFilterAttribute.
public class SessionExpireFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpContext ctx = HttpContext.Current;
// check if session is supported
CurrentCustomer objCurrentCustomer = new CurrentCustomer();
objCurrentCustomer = ((CurrentCustomer)SessionStore.GetSessionValue(SessionStore.Customer));
if (objCurrentCustomer == null)
{
// check if a new session id was generated
filterContext.Result = new RedirectResult("~/Users/Login");
return;
}
base.OnActionExecuting(filterContext);
}
}
Then in action just add this attribute like so:
[SessionExpire]
public ActionResult Index()
{
return Index();
}
This will do you work.
$(selector).change()
Longer slower alternative, better for abstraction.
$(selector).trigger("change")
class MyParent:
def sayHi():
print('Mamma says hi')
from path.to.MyParent import MyParent
class ChildClass(MyParent):
pass
An instance of ChildClass
will then inherit the sayHi()
method.
Firstly you make sure you have add permission in manifest file.
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
Check if the application has draw over other apps permission or not? This permission is by default available for API<23. But for API > 23 you have to ask for the permission in runtime.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, 1);
}
Use This code:
public class ChatHeadService extends Service {
private WindowManager mWindowManager;
private View mChatHeadView;
WindowManager.LayoutParams params;
public ChatHeadService() {
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Language language = new Language();
//Inflate the chat head layout we created
mChatHeadView = LayoutInflater.from(this).inflate(R.layout.dialog_incoming_call, null);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
| WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.CENTER_HORIZONTAL | Gravity.TOP;
params.x = 0;
params.y = 100;
mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
mWindowManager.addView(mChatHeadView, params);
} else {
params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
| WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.CENTER_HORIZONTAL | Gravity.TOP;
params.x = 0;
params.y = 100;
mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
mWindowManager.addView(mChatHeadView, params);
}
TextView tvTitle=mChatHeadView.findViewById(R.id.tvTitle);
tvTitle.setText("Incoming Call");
//Set the close button.
Button btnReject = (Button) mChatHeadView.findViewById(R.id.btnReject);
btnReject.setText(language.getText(R.string.reject));
btnReject.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//close the service and remove the chat head from the window
stopSelf();
}
});
//Drag and move chat head using user's touch action.
final Button btnAccept = (Button) mChatHeadView.findViewById(R.id.btnAccept);
btnAccept.setText(language.getText(R.string.accept));
LinearLayout linearLayoutMain=mChatHeadView.findViewById(R.id.linearLayoutMain);
linearLayoutMain.setOnTouchListener(new View.OnTouchListener() {
private int lastAction;
private int initialX;
private int initialY;
private float initialTouchX;
private float initialTouchY;
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
//remember the initial position.
initialX = params.x;
initialY = params.y;
//get the touch location
initialTouchX = event.getRawX();
initialTouchY = event.getRawY();
lastAction = event.getAction();
return true;
case MotionEvent.ACTION_UP:
//As we implemented on touch listener with ACTION_MOVE,
//we have to check if the previous action was ACTION_DOWN
//to identify if the user clicked the view or not.
if (lastAction == MotionEvent.ACTION_DOWN) {
//Open the chat conversation click.
Intent intent = new Intent(ChatHeadService.this, HomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
//close the service and remove the chat heads
stopSelf();
}
lastAction = event.getAction();
return true;
case MotionEvent.ACTION_MOVE:
//Calculate the X and Y coordinates of the view.
params.x = initialX + (int) (event.getRawX() - initialTouchX);
params.y = initialY + (int) (event.getRawY() - initialTouchY);
//Update the layout with new X & Y coordinate
mWindowManager.updateViewLayout(mChatHeadView, params);
lastAction = event.getAction();
return true;
}
return false;
}
});
}
@Override
public void onDestroy() {
super.onDestroy();
if (mChatHeadView != null) mWindowManager.removeView(mChatHeadView);
}
}
I was totally lost on why my Gridview.Databind()
would not refresh.
My issue, I discovered, was my gridview was inside a UpdatePanel. To get my GridView to FINALLY refresh was this:
gvServerConfiguration.Databind()
uppServerConfiguration.Update()
uppServerConfiguration is the id associated with my UpdatePanel in my asp.net code.
Hope this helps someone.
You can convert the QString type to python string by just using the str
function. Assuming you are not using any Unicode characters you can get a python
string as below:
text = str(combobox1.currentText())
If you are using any unicode characters, you can do:
text = unicode(combobox1.currentText())
You can check if string contains numbers only:
Regex.IsMatch(myStringVariable, @"^-?\d+$")
But number can be bigger than Int32.MaxValue
or less than Int32.MinValue
- you should keep that in mind.
Another option - create extension method and move ugly code there:
public static bool IsInteger(this string s)
{
if (String.IsNullOrEmpty(s))
return false;
int i;
return Int32.TryParse(s, out i);
}
That will make your code more clean:
if (myStringVariable.IsInteger())
// ...
SOLUTION
Just hold on a while after uploading your app on play store because google takes some time to update app versions.It will work !
I think the main benefit would be when you define your own Display Templates, or use Data annotations.
So for example if your title was a date, you could define
[DisplayFormat(DataFormatString = "{0:d}")]
and then on every page it would display the value in a consistent manner. Otherwise you may have to customise the display on multiple pages. So it does not help much for plain strings, but it does help for currencies, dates, emails, urls, etc.
For example instead of an email address being a plain string it could show up as a link:
<a href="mailto:@ViewData.Model">@ViewData.TemplateInfo.FormattedModelValue</a>
If you do not want to create a new row but simply put it in the empty cell then use:
df.columns.name = 'foo'
Otherwise use:
df.index.name = 'foo'
There are at least three ways to get the "sum total of all the data in files and subdirectories" in bytes that work in both Linux/Unix and Git Bash for Windows, listed below in order from fastest to slowest on average. For your reference, they were executed at the root of a fairly deep file system (docroot
in a Magento 2 Enterprise installation comprising 71,158 files in 30,027 directories).
1.
$ time find -type f -printf '%s\n' | awk '{ total += $1 }; END { print total" bytes" }'
748660546 bytes
real 0m0.221s
user 0m0.068s
sys 0m0.160s
2.
$ time echo `find -type f -print0 | xargs -0 stat --format=%s | awk '{total+=$1} END {print total}'` bytes
748660546 bytes
real 0m0.256s
user 0m0.164s
sys 0m0.196s
3.
$ time echo `find -type f -exec du -bc {} + | grep -P "\ttotal$" | cut -f1 | awk '{ total += $1 }; END { print total }'` bytes
748660546 bytes
real 0m0.553s
user 0m0.308s
sys 0m0.416s
These two also work, but they rely on commands that don't exist on Git Bash for Windows:
1.
$ time echo `find -type f -printf "%s + " | dc -e0 -f- -ep` bytes
748660546 bytes
real 0m0.233s
user 0m0.116s
sys 0m0.176s
2.
$ time echo `find -type f -printf '%s\n' | paste -sd+ | bc` bytes
748660546 bytes
real 0m0.242s
user 0m0.104s
sys 0m0.152s
If you only want the total for the current directory, then add -maxdepth 1
to find
.
Note that some of the suggested solutions don't return accurate results, so I would stick with the solutions above instead.
$ du -sbh
832M .
$ ls -lR | grep -v '^d' | awk '{total += $5} END {print "Total:", total}'
Total: 583772525
$ find . -type f | xargs stat --format=%s | awk '{s+=$1} END {print s}'
xargs: unmatched single quote; by default quotes are special to xargs unless you use the -0 option
4390471
$ ls -l| grep -v '^d'| awk '{total = total + $5} END {print "Total" , total}'
Total 968133
Your logic condition is wrong. IIUC, what you want is:
import pyspark.sql.functions as f
df.filter((f.col('d')<5))\
.filter(
((f.col('col1') != f.col('col3')) |
(f.col('col2') != f.col('col4')) & (f.col('col1') == f.col('col3')))
)\
.show()
I broke the filter()
step into 2 calls for readability, but you could equivalently do it in one line.
Output:
+----+----+----+----+---+
|col1|col2|col3|col4| d|
+----+----+----+----+---+
| A| xx| D| vv| 4|
| A| x| A| xx| 3|
| E| xxx| B| vv| 3|
| F|xxxx| F| vvv| 4|
| G| xxx| G| xx| 4|
+----+----+----+----+---+
They are not case sensitive. In fact NodeJS web server explicitly converts them to lower-case, before making them available in the request object.
It's important to note here that all headers are represented in lower-case only, regardless of how the client actually sent them. This simplifies the task of parsing headers for whatever purpose.
Remember that your suggestions makes it difficult for clients to communicate with the server. They need to understand your innovative solution and encrypt the data accordingly, this model is not so good for public API (unless you are amazon\yahoo\google..).
Anyways, if you must encrypt the body content I would suggest you to check out existing standards and solutions like:
XML encryption (W3C standard)
remove float: left
from image css and add text-align: center
property in parent element body
<!DOCTYPE html>_x000D_
<html>_x000D_
<body style="text-align: center;">_x000D_
_x000D_
<img_x000D_
src="http://icons.iconarchive.com/icons/rokey/popo-emotions/128/big-smile-icon.png"_x000D_
width="42" height="42"_x000D_
align="middle"_x000D_
style="_x000D_
_x000D_
display: block;_x000D_
margin-left: auto;_x000D_
margin-right: auto;_x000D_
z-index: 1;"_x000D_
>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
This is for the searchers,
The best I did is,
$('#myDiv *').attr("disabled", true);
$('#myDiv *').fadeTo('slow', .6);
Check if SElinux is enabled. If it is in enforcing mode just try with permissive mode. In case that helps you should create SElinux policies for mongodb.
You can try with audit2allow - check https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/6/html/security-enhanced_linux/sect-security-enhanced_linux-fixing_problems-allowing_access_audit2allow
1. To properly purge the queue of waiting tasks you have to stop all the workers (http://celery.readthedocs.io/en/latest/faq.html#i-ve-purged-messages-but-there-are-still-messages-left-in-the-queue):
$ sudo rabbitmqctl stop
or (in case RabbitMQ/message broker is managed by Supervisor):
$ sudo supervisorctl stop all
2. ...and then purge the tasks from a specific queue:
$ cd <source_dir>
$ celery amqp queue.purge <queue name>
3. Start RabbitMQ:
$ sudo rabbitmqctl start
or (in case RabbitMQ is managed by Supervisor):
$ sudo supervisorctl start all
Diffrence between Foreach & map :
Map() : If you use map then map can return new array by iterating main array.
Foreach() : If you use Foreach then it can not return anything for each can iterating main array.
useFul link : use this link for understanding diffrence
Hi For jQuery You can only use like this
Use async and type="text/javascript" only
Instead of storing images in database store them in a folder in your disk and store their location in your data base.
I would set up a shortcut, either to CMD or to the thing you want to run, then set the properties of the shortcut to require admin, and then run the shortcut from your batch file. I haven't tested to confirm it will respect the properties, but I think it's more elegant and doesn't require activating the Administrator account.
Also if you do it as a scheduled task (which can be set up from code) there is an option to run it elevated there.
When the problem is in the recalculation of an IF condition, I add AND(ISDATE(NOW());condition)
so that the cell is forced to recalculate according to
what is set in the Calculation tab in Spreadsheet Settings as explained before.
This works because NOW
is one of the functions that is affected by the Calculation setting and ISDATE(NOW())
always returns TRUE
.
For example, in one of my sheets I had the following condition which I use to check whether a sheet with name stored in C1
is already created:
=IF(ISREF(INDIRECT(C$1&"!A1")); TRUE; FALSE)
In this case C1="February"
, so I expected the condition to become TRUE
when a sheet with this name was created, which didn't happen. To force it to update, I changed the Calculation setting and used:
=IF(AND( ISDATE(NOW()) ; ISREF(INDIRECT(C$1&"!A1")) ); TRUE; FALSE)
Setting margin in layout params will not work in Alertdialog. you have to set padding in parent layout and then add edittext in that layout.
This is my working kotlin code...
val alert = AlertDialog.Builder(context!!)
val edittext = EditText(context!!)
edittext.hint = "Enter Name"
edittext.maxLines = 1
val layout = FrameLayout(context!!)
//set padding in parent layout
layout.setPaddingRelative(45,15,45,0)
alert.setTitle(title)
layout.addView(edittext)
alert.setView(layout)
alert.setPositiveButton(getString(R.string.label_save), DialogInterface.OnClickListener {
dialog, which ->
run {
val qName = edittext.text.toString()
Utility.hideKeyboard(context!!, dialogView!!)
}
})
alert.setNegativeButton(getString(R.string.label_cancel), DialogInterface.OnClickListener {
dialog, which ->
run {
dismiss()
}
})
alert.show()
It is a syntax. In the function arguments int (&myArray)[100]
parenthesis that enclose the &myArray
are necessary. if you don't use them, you will be passing an array of references
and that is because the subscript operator []
has higher precedence over the & operator
.
E.g. int &myArray[100] // array of references
So, by using type construction ()
you tell the compiler that you want a reference to an array of 100 integers.
E.g int (&myArray)[100] // reference of an array of 100 ints