It it possible to do in the admin, but there is not a very straightforward way to it. Also, I would like to advice to keep most business logic in your models, so you won't be dependent on the Django Admin.
Maybe it would be easier (and maybe even better) if you have the two seperate fields on your model. Then add a method on your model that combines them.
For example:
class MyModel(models.model):
field1 = models.CharField(max_length=10)
field2 = models.CharField(max_length=10)
def combined_fields(self):
return '{} {}'.format(self.field1, self.field2)
Then in the admin you can add the combined_fields()
as a readonly field:
class MyModelAdmin(models.ModelAdmin):
list_display = ('field1', 'field2', 'combined_fields')
readonly_fields = ('combined_fields',)
def combined_fields(self, obj):
return obj.combined_fields()
If you want to store the combined_fields
in the database you could also save it when you save the model:
def save(self, *args, **kwargs):
self.field3 = self.combined_fields()
super(MyModel, self).save(*args, **kwargs)
Since the value of $var
is the empty string, this:
if [ $var == $var1 ]; then
expands to this:
if [ == abcd ]; then
which is a syntax error.
You need to quote the arguments:
if [ "$var" == "$var1" ]; then
You can also use =
rather than ==
; that's the original syntax, and it's a bit more portable.
If you're using bash, you can use the [[
syntax, which doesn't require the quotes:
if [[ $var = $var1 ]]; then
Even then, it doesn't hurt to quote the variable reference, and adding quotes:
if [[ "$var" = "$var1" ]]; then
might save a future reader a moment trying to remember whether [[
... ]]
requires them.
After you correct the possible dmp file problem, this is a way to ensure that the schema is remapped and imported appropriately. This will also ensure that the tablespace will change also, if needed:
impdp system/<password> SCHEMAS=user1 remap_schema=user1:user2 \
remap_tablespace=user1:user2 directory=EXPORTDIR \
dumpfile=user1.dmp logfile=E:\Data\user1.log
EXPORTDIR must be defined in oracle as a directory as the system user
create or replace directory EXPORTDIR as 'E:\Data';
grant read, write on directory EXPORTDIR to user2;
I hope it will be helpful for others.
// put below code (method) in Adapter class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
myList.clear();
if (charText.length() == 0) {
myList.addAll(arraylist);
}
else
{
for (MyBean wp : arraylist) {
if (wp.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
myList.add(wp);
}
}
}
notifyDataSetChanged();
}
declare below code in adapter class
private ArrayList<MyBean> myList; // for loading main list
private ArrayList<MyBean> arraylist=null; // for loading filter data
below code in adapter Constructor
this.arraylist = new ArrayList<MyBean>();
this.arraylist.addAll(myList);
and below code in your activity class
final EditText searchET = (EditText)findViewById(R.id.search_et);
// Capture Text in EditText
searchET.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = searchET.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
I found a better way of doing it so you can get a input from a txtbox or have something be generated in that text box and be able to click a button to do it.!
import java.awt.datatransfer.*;
import java.awt.Toolkit;
private void /* Action performed when the copy to clipboard button is clicked */ {
String ctc = txtCommand.getText().toString();
StringSelection stringSelection = new StringSelection(ctc);
Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard();
clpbrd.setContents(stringSelection, null);
}
// txtCommand is the variable of a text box
I think the problem is with the datatype of the data you are passing Caused by: java.sql.SQLException: Invalid column type: 1111
check the datatypes you pass with the actual column datatypes may be there can be some mismatch or some constraint violation with null
my 2c
the purpose of encapsulation is to hide implementation details from the user of your class e.g. if you internally keep a std::list of items in your class and then decide that a std::vector would be more effective you can change this without the user caring. That said, the way you interact with the either stl container is thanks to abstraction, both the list and the vector can for instance be traversed in the same way using similar methods (iterators).
Here's a start. Basically, we copy the header on load, and then check (using .scrollTop()
or window.scrollY
) to see when the user scrolls beyond a point (e.g. 200pixels). Then we simply toggle a class (in this case .down
) which moves the original into view.
Lastly all we need to do is apply a transition: top 0.2s ease-in
to our clone, so that when it's in the .down
state it slides into view. Dunked does it better, but with a little playing around it's easy to configure
CSS
header {
position: relative;
width: 100%;
height: 60px;
}
header.clone {
position: fixed;
top: -65px;
left: 0;
right: 0;
z-index: 999;
transition: 0.2s top cubic-bezier(.3,.73,.3,.74);
}
body.down header.clone {
top: 0;
}
either Vanilla JS (polyfill as required)
var sticky = {
sticky_after: 200,
init: function() {
this.header = document.getElementsByTagName("header")[0];
this.clone = this.header.cloneNode(true);
this.clone.classList.add("clone");
this.header.insertBefore(this.clone);
this.scroll();
this.events();
},
scroll: function() {
if(window.scrollY > this.sticky_after) {
document.body.classList.add("down");
}
else {
document.body.classList.remove("down");
}
},
events: function() {
window.addEventListener("scroll", this.scroll.bind(this));
}
};
document.addEventListener("DOMContentLoaded", sticky.init.bind(sticky));
or jQuery
$(document).ready(function() {
var $header = $("header"),
$clone = $header.before($header.clone().addClass("clone"));
$(window).on("scroll", function() {
var fromTop = $("body").scrollTop();
$('body').toggleClass("down", (fromTop > 200));
});
});
Whilst the above answers the OP's original question of "How does Dunked achieve this effect?", I wouldn't recommend this approach. For starters, copying the entire top navigation could be pretty costly, and there's no real reason why we can't use the original (with a little bit of work).
Furthermore, Paul Irish and others, have written about how animating with translate()
is better than animating with top
. Not only is it more performant, but it also means that you don't need to know the exact height of your element. The above solution would be modified with the following (See JSFiddle):
header.clone {
position: fixed;
top: 0;
left: 0;
right: 0;
transform: translateY(-100%);
transition: 0.2s transform cubic-bezier(.3,.73,.3,.74);
}
body.down header.clone {
transform: translateY(0);
}
The only drawback with using transforms is, that whilst browser support is pretty good, you'll probably want to add vendor prefixed versions to maximize compatibility.
If the newline is expected to be at the end of the string, then:
if (!s.empty() && s[s.length()-1] == '\n') {
s.erase(s.length()-1);
}
If the string can contain many newlines anywhere in the string:
std::string::size_type i = 0;
while (i < s.length()) {
i = s.find('\n', i);
if (i == std::string:npos) {
break;
}
s.erase(i);
}
Ran to the same issue, Assuming your using anaconda3 and your using a venv
with >= python=3.6
:
python -m pip install keras
sudo python -m pip install --user tensorflow
int** create2DArray(unsigned height, unsigned width)
{
int** array2D = 0;
array2D = new int*[height];
for (int h = 0; h < height; h++)
{
array2D[h] = new int[width];
for (int w = 0; w < width; w++)
{
// fill in some initial values
// (filling in zeros would be more logic, but this is just for the example)
array2D[h][w] = w + width * h;
}
}
return array2D;
}
int main ()
{
printf("Creating a 2D array2D\n");
printf("\n");
int height = 15;
int width = 10;
int** my2DArray = create2DArray(height, width);
printf("Array sized [%i,%i] created.\n\n", height, width);
// print contents of the array2D
printf("Array contents: \n");
for (int h = 0; h < height; h++)
{
for (int w = 0; w < width; w++)
{
printf("%i,", my2DArray[h][w]);
}
printf("\n");
}
return 0;
}
For all the given solution, when you try this in a modern browser (like FF), and you have set the correct model
// Model
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime Start { get; set; }
// View
<div class="form-group">
@Html.LabelFor(model => model.Start, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Start, "{0:dd-MM-yyyy}", new { htmlAttributes = new { @class = "form-control"} })
</div>
</div>
mvc(5) wil render (the type of the input is set to date based on your date settings in your model!)
<div class="col-md-10">
<input class="form-control text-box single-line" data-val="true" data-val-date="The field Start must be a date." data-val-required="The Start field is required." id="Start" name="Start" value="01-05-2018" type="date">
<span class="field-validation-valid text-danger" data-valmsg-for="Start" data-valmsg-replace="true"></span>
</div>
And the browser will show
To fix this you need to change the type to text instead of date (also if you want to use your custom calender)
@Html.EditorFor(model => model.Start, "{0:dd-MM-yyyy}", new { htmlAttributes = new { @class = "form-control", @type = "text" } })
This is an old question, but there is another subtle way this message can happen. It's explained pretty well here, in the docs.
Imagine this scenerio:
try {
// code that triggers a pdo exception
} catch (Exception $e) {
throw new MyCustomExceptionHandler($e);
}
And MyCustomExceptionHandler
is defined roughly like:
class MyCustomExceptionHandler extends Exception {
public function __construct($e) {
parent::__construct($e->getMessage(), $e->getCode());
}
}
This will actually trigger a new exception in the custom exception handler because the Exception
class is expecting a number for the second parameter in its constructor, but PDOException
might have dynamically changed the return type of $e->getCode()
to a string.
A workaround for this would be to define you custom exception handler like:
class MyCustomExceptionHandler extends Exception {
public function __construct($e) {
parent::__construct($e->getMessage());
$this->code = $e->getCode();
}
}
I do not know much about Java but URL query arguments should be separated by "&", not "?"
http://tools.ietf.org/html/rfc3986 is good place for reference using "sub-delim" as keyword. http://en.wikipedia.org/wiki/Query_string is another good source.
Just go to Tools > Options > Environment > Keyboard > Find the action you want to set key board short-cut and change according to keyboard habbit.
My workaround for this issue was to set display: inline
to the image element.
With this, your image and text will be aligned to the right if you set text-align: right
from a parent container.
The following will work out of the box on any site:
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>_x000D_
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.min.js"></script>_x000D_
_x000D_
<div class="dialogBox" style="border:1px solid gray;">_x000D_
<a href="/" class="exampleLink">Test</a>_x000D_
<!-- TODO: Change above href -->_x000D_
<!-- NOTE: Must be a local url, not cross domain -->_x000D_
</div>_x000D_
_x000D_
<script type="text/javascript">_x000D_
_x000D_
_x000D_
var $modalDialog = $('<div/>', { _x000D_
'class': 'exampleModal', _x000D_
'id': 'exampleModal1' _x000D_
})_x000D_
.appendTo('body')_x000D_
.dialog({_x000D_
resizable: false,_x000D_
autoOpen: false,_x000D_
height: 300,_x000D_
width: 350,_x000D_
show: 'fold',_x000D_
buttons: {_x000D_
"Close": function () {_x000D_
$modalDialog.dialog("close");_x000D_
}_x000D_
},_x000D_
modal: true_x000D_
});_x000D_
_x000D_
$(function () {_x000D_
$('a.exampleLink').on('click', function (e) {_x000D_
e.preventDefault();_x000D_
// TODO: Undo comments, below_x000D_
//var url = $('a.exampleLink:first').attr('href');_x000D_
//$modalDialog.load(url);_x000D_
$modalDialog.dialog("open");_x000D_
});_x000D_
});_x000D_
_x000D_
</script>
_x000D_
In case it helps someone, I had a similar issue and the error was because of two reasons:
Not using the app's namespace before the url name
{% url 'app_name:url_name' %}
Missing single quotes around the url name (as pointed out here by Charlie)
#include <algorithm> // std::search
#include <string>
using std::search; using std::count; using std::string;
int main() {
string mystring = "The needle in the haystack";
string str = "needle";
string::const_iterator it;
it = search(mystring.begin(), mystring.end(),
str.begin(), str.end()) != mystring.end();
// if string is found... returns iterator to str's first element in mystring
// if string is not found... returns iterator to mystring.end()
if (it != mystring.end())
// string is found
else
// not found
return 0;
}
I found this method as useful in new versions of Windows 10:
Turn on this feature: "Beta: Use Unicode UTF-8 for worldwide language support"
Control panel -> Regional settings -> Administrative tab-> Change system locale...
This happens when a python extension (written in C) tries to access a memory beyond reach.
You can trace it in following ways.
sys.settrace
at the very first line of the code.Use gdb
as described by Mark in this answer.. At the command prompt
gdb python
(gdb) run /path/to/script.py
## wait for segfault ##
(gdb) backtrace
## stack trace of the c code
Apache Commons has a great StringUtils class (org.apache.commons.lang.StringUtils). In StringUtils
there is a strip(String, String)
method that will do what you want.
I highly recommend using Apache Commons anyway, especially the Collections and Lang libraries.
You can try:
\bcat\b.*\bmat\b
\b
is an anchor and matches a word boundary. It will look for words cat and mat anywhere in the string with mat following cat. It will not match:
Therez caterpillar on the mat
.
but will match
The cat slept on the mat in front of the fire
If you want to match strings which have letters cat followed by mat, you can try:
cat.*mat
This will match both the above example strings.
if you have a hive setup you can put the local dataset directly using Hive load command in hdfs/s3.
You will need to use "Local" keyword when writing your load command.
Syntax for hiveload command
LOAD DATA [LOCAL] INPATH 'filepath' [OVERWRITE] INTO TABLE tablename [PARTITION (partcol1=val1, partcol2=val2 ...)]
Refer below link for more detailed information. https://cwiki.apache.org/confluence/display/Hive/LanguageManual%20DML#LanguageManualDML-Loadingfilesintotables
This is what I did and it works try and play around with it. It calculates total,avarage,minimum and maximum.
public static void main(String[] args) {
int[] score= {56,90,89,99,59,67};
double avg;
int sum=0;
int maxValue=0;
int minValue=100;
for(int i=0;i<6;i++){
sum=sum+score[i];
if(score[i]<minValue){
minValue=score[i];
}
if(score[i]>maxValue){
maxValue=score[i];
}
}
avg=sum/6.0;
System.out.print("Max: "+maxValue+"," +" Min: "+minValue+","+" Avarage: "+avg+","+" Sum: "+sum);}
}
Ruby has sigils and twigils, Python doesn't.
Edit: And one very important thing that I forgot (after all, the previous was just to flame a little bit :-p):
Python has a JIT compiler (Psyco), a sightly lower level language for writing faster code (Pyrex) and the ability to add inline C++ code (Weave).
Supplementing the answer by p.s.w.g
, here are three other ways of achieving this using lodash
4.17.5
, without using _.includes()
:
Say you want to add object entry
to an array of objects numbers
, only if entry
does not exist already.
let numbers = [
{ to: 1, from: 2 },
{ to: 3, from: 4 },
{ to: 5, from: 6 },
{ to: 7, from: 8 },
{ to: 1, from: 2 } // intentionally added duplicate
];
let entry = { to: 1, from: 2 };
/*
* 1. This will return the *index of the first* element that matches:
*/
_.findIndex(numbers, (o) => { return _.isMatch(o, entry) });
// output: 0
/*
* 2. This will return the entry that matches. Even if the entry exists
* multiple time, it is only returned once.
*/
_.find(numbers, (o) => { return _.isMatch(o, entry) });
// output: {to: 1, from: 2}
/*
* 3. This will return an array of objects containing all the matches.
* If an entry exists multiple times, if is returned multiple times.
*/
_.filter(numbers, _.matches(entry));
// output: [{to: 1, from: 2}, {to: 1, from: 2}]
If you want to return a Boolean
, in the first case, you can check the index that is being returned:
_.findIndex(numbers, (o) => { return _.isMatch(o, entry) }) > -1;
// output: true
I encountered the same problem. Strange, but the reason was that the object Scanner interprets fractions depending on localization of system. If the current localization uses a comma to separate parts of the fractions, the fraction with the dot will turn into type String. Hence the error ...
$>git add .
$>git rm file_Name
It works. You add new file using right click -> create new file, and immediately delete it after that. The file would go to the untracked file list.
Because setting the div
's display
style property to ""
doesn't change anything in the CSS rule itself. That basically just creates an "empty," inline CSS rule, which has no effect beyond clearing the same property on that element.
You need to set it to something that has a value:
document.getElementById('mybox').style.display = "block";
What you're doing would work if you were replacing an inline style on the div, like this:
<div id="myBox" style="display: none;"></div>
document.getElementById('mybox').style.display = "";
I faced this error when I created an empty project with the MVC folders and then deployed the application to the server. My issue was that I didn't define the authentication in Web.config
, so all I had to do was add this line to a system.web
tag.
<system.web>
<authentication mode="None"/>
</system.web>
This code- (sets currency to GB(Britain/UK/England/£) then prints a line. Then sets currency to US/$ and prints a line)
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB",false);
Console.WriteLine("bbbbbbb {0:c}",4321.2);
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US",false);
Console.WriteLine("bbbbbbb {0:c}",4321.2);
Will display-
bbbbbbb £4,321.20
bbbbbbb $4,321.20
For a list of culture names e.g. en-GB en-US e.t.c.
http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo(v=vs.80).aspx
you can using this
sudo chown -R $USER:$USER "$(git rev-parse --show-toplevel)/.git"
The posted setdiff
answer is nice. I just thought I'd post this related function I wrote a while back. Its usefulness is up to the reader :-).
lstype<-function(type='closure'){
inlist<-ls(.GlobalEnv)
if (type=='function') type <-'closure'
typelist<-sapply(sapply(inlist,get),typeof)
return(names(typelist[typelist==type]))
}
I'd suggest doing something similar to:
function show_sub(cat) {
if (!cat) {
return false;
}
else if (document.getElementById(cat)) {
var parent = document.getElementById(cat),
sub = parent.getElementsByClassName('sub');
if (sub[0].style.display == 'inline'){
sub[0].style.display = 'none';
}
else {
sub[0].style.display = 'inline';
}
}
}
document.getElementById('cat').onclick = function(){
show_sub(this.id);
};????
Though the above relies on the use of a class
rather than a name
attribute equal to sub
.
As to why your original version "didn't work" (not, I must add, a particularly useful description of the problem), all I can suggest is that, in Chromium, the JavaScript console reported that:
Uncaught TypeError: Object # has no method 'getElementsByName'.
One approach to working around the older-IE family's limitations is to use a custom function to emulate getElementsByClassName()
, albeit crudely:
function eBCN(elem,classN){
if (!elem || !classN){
return false;
}
else {
var children = elem.childNodes;
for (var i=0,len=children.length;i<len;i++){
if (children[i].nodeType == 1
&&
children[i].className == classN){
var sub = children[i];
}
}
return sub;
}
}
function show_sub(cat) {
if (!cat) {
return false;
}
else if (document.getElementById(cat)) {
var parent = document.getElementById(cat),
sub = eBCN(parent,'sub');
if (sub.style.display == 'inline'){
sub.style.display = 'none';
}
else {
sub.style.display = 'inline';
}
}
}
var D = document,
listElems = D.getElementsByTagName('li');
for (var i=0,len=listElems.length;i<len;i++){
listElems[i].onclick = function(){
show_sub(this.id);
};
}?
$("#idform").validate({
rules: {
'roles': {
required: true,
},
},
messages: {
'roles': {
required: "One Option please",
},
}
});
Yet another idea to throw in to the mix... In my case, the component throwing the error was a template-less component with a custom render()
function. I couldn't see why it wasn't working, until I realised that I hadn't put <script>
...</script>
tags around the code in the component (seemed unnecessary, since I had no template or style tags either). Not sure why this got past the compiler...?
Either way... make sure you use your <script>
tags ;-)
>>> names = ['King', 'Queen', 'Joker']
>>> any(n in 'King and john' for n in names)
True
>>> all(n in 'King and Queen' for n in names)
False
It just reduce several line of code into one. You don't have to write lengthy code like:
for n in names:
if n in 'King and john':
print True
else:
print False
Assuming that you want to reduce dependencies to other assemblies and to keep things simple, you can do:
var sb = new System.Text.StringBuilder();
sb.Append("a=" + HttpUtility.UrlEncode("TheValueOfA") + "&");
sb.Append("b=" + HttpUtility.UrlEncode("TheValueOfB") + "&");
sb.Append("c=" + HttpUtility.UrlEncode("TheValueOfC") + "&");
sb.Append("d=" + HttpUtility.UrlEncode("TheValueOfD") + "&");
sb.Remove(sb.Length-1, 1); // Remove the final '&'
string result = sb.ToString();
This works well with loops too. The final ampersand removal needs to go outside of the loop.
Note that the concatenation operator is used to improve readability. The cost of using it compared to the cost of using a StringBuilder is minimal (I think Jeff Atwood posted something on this topic).
Try this...
SELECT TO_CHAR(column_name,'99G999D99MI')
as format_column
FROM DUAL;
loc: only work on index
iloc: work on position
at: get scalar values. It's a very fast loc
iat: Get scalar values. It's a very fast iloc
Also,
at
andiat
are meant to access a scalar, that is, a single element in the dataframe, whileloc
andiloc
are ments to access several elements at the same time, potentially to perform vectorized operations.
http://pyciencia.blogspot.com/2015/05/obtener-y-filtrar-datos-de-un-dataframe.html
For ASP.NET on Linux, check out Mono.
That said, thousands of sites run on Windows Server without any issues. A poorly-configured server with any OS will be vulnerable; Linux won't save you from a poor admin.
So I guess my "best practice" for deplying an ASP.NET app would be to use Windows Server 2008 (likely Web edition). And hire a good administrator.
i didn't know that the ".stop()" is necessary.
$(window).scroll(function () {
var scroll = $(window).scrollTop();
console.log(scroll);
if (scroll >= 50){
$('.sidebar-padder').stop().animate({ 'height': '380px'}, 1000);
}else{
$('.sidebar-padder').stop().animate({ 'height': '600px'}, 1000);
};
It supports after KITKAT. Just add following code inside onCreate method of your Activity. No need any modifications to Manifest file.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Window w = getWindow(); // in Activity's onCreate() for instance
w.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
}
CustomTableCell.h is a UITableViewCell:
@property (weak, nonatomic) IBOutlet UIButton *action1Button;
@property (weak, nonatomic) IBOutlet UIButton *action2Button;
MyVC.m after imports:
@interface MYTapGestureRecognizer : UITapGestureRecognizer
@property (nonatomic) NSInteger dataint;
@end
Inside "cellForRowAtIndexPath" in MyVC.m:
//CustomTableCell
CustomTableCell *cell = (CustomTableCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
//Set title buttons
[cell.action1Button setTitle:[NSString stringWithString:NSLocalizedString(@"action1", nil)] forState:UIControlStateNormal];
[cell.action2Button setTitle:[NSString stringWithString:NSLocalizedString(@"action2", nil)] forState:UIControlStateNormal];
//Set visibility buttons
[cell.action1Button setHidden:FALSE];
[cell.action2Button setHidden:FALSE];
//Do 1 action
[cell.action1Button addTarget:self action:@selector(do1Action :) forControlEvents:UIControlEventTouchUpInside];
//Do 2 action
MYTapGestureRecognizer *action2Tap = [[MYTapGestureRecognizer alloc] initWithTarget:self action:@selector(do2Action :)];
cancelTap.numberOfTapsRequired = 1;
cancelTap.dataint = indexPath.row;
[cell.action2Button setUserInteractionEnabled:YES];
[cell.action2Button addGestureRecognizer:action2Tap];
MyVC.m:
-(void)do1Action :(id)sender{
//do some action that is not necessary fr data
}
-(void)do2Action :(UITapGestureRecognizer *)tapRecognizer{
MYTapGestureRecognizer *tap = (MYTapGestureRecognizer *)tapRecognizer;
numberTag = tap.dataint;
FriendRequest *fr = [_list objectAtIndex:numberTag];
//connect with a WS o do some action with fr data
//actualize list in tableView
[self.myTableView reloadData];
}
Yes, just like you did:
select something + somethingElse as onlyOneColumn from someTable
If you queried the database, you would have gotten the right answer.
What happens is you ask for an expression. A very simple expression is just a column name, a more complicated expression can have formulas etc in it.
The app is stored in %LocalAppData%
in your %UserProfile%
. So the full path could be:
C:\Users\username\AppData\Local\GitHub
From RFC 1945 (HTTP/1.0) and RFC 2617 (HTTP Authentication referenced by HTTP/1.1)
The realm attribute (case-insensitive) is required for all authentication schemes which issue a challenge. The realm value (case-sensitive), in combination with the canonical root URL of the server being accessed, defines the protection space. These realms allow the protected resources on a server to be partitioned into a set of protection spaces, each with its own authentication scheme and/or authorization database. The realm value is a string, generally assigned by the origin server, which may have additional semantics specific to the authentication scheme.
In short, pages in the same realm should share credentials. If your credentials work for a page with the realm "My Realm", it should be assumed that the same username and password combination should work for another page with the same realm.
There is no need to add paths to environment if you use the Anaconda Prompt.
Start the Anaconda prompt change to your directory and run your script or start your editor from there. This will ensure you are in the full Anaconda environment and the SSL error will stop.
Whats the difference between command prompt and Anaconda Prompt? See this SO answer to what is the difference between command prompt and anaconda prompt.
Use .container-fluid
when you want your page to shapeshift with every little difference in its viewport size.
Use .container
when you want your page to shapeshift to only 4 kinds of sizes, which are also known as "breakpoints".
The breakpoints corresponding to their sizes are:
seems you need to link with the obj file that implements tolayer5()
Update: your function declaration doesn't match the implementation:
void tolayer5(int AorB, struct msg msgReceived)
void tolayer5(int, char data[])
So compiler would treat them as two different functions (you are using c++). and it cannot find the implementation for the one you called in main().
You can try this set unique attribute for each element
TextView mtextView = findViewById(R.id.myTextView);
mtextView.setShowSoftInputOnFocus(false);
Keyboard will not show while element is focus
You can get it one line like this:
String monthName = new DataFormatSymbols.getMonths()[cal.get(Calendar.MONTH)]
I found this solution similar to the original problem
<?php
$test_array = array (
'bla' => 'blub',
'foo' => 'bar',
'another_array' => array (
'stack' => 'overflow',
),
);
class NoSimpleXMLElement extends SimpleXMLElement {
public function addChild($name,$value) {
parent::addChild($value,$name);
}
}
$xml = new NoSimpleXMLElement('<root/>');
array_walk_recursive($test_array, array ($xml, 'addChild'));
print $xml->asXML();
I have this issue, and all I did was make sure that I was referencing the right .Net framework in all the projects then just change the web.config from
From
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
To
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework" requirePermission="false"/>
All works..
You probably want egrep. Try:
egrep '^[d-]rwx.*[0-9]$' usrLog.txt
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="Tom"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="24sp"
android:layout_weight="3"/>
<TextView
android:text="Tim"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="24sp"
android:layout_weight="3"/>
<TextView
android:text="Todd"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="24sp"
android:layout_weight="3"/>
</LinearLayout>
In circle, Tom, Tim, and Todd get assumed to be 3 centimeters. If you want it to be touch down screen, put it as Tom and Tim getting assumed to be 1 centimeter, which means they combine virtual but its 2D plane is at the bottom. This is displayed on screen.
Here is a real world example which shows front/mid/back end.
It is possible to have overlapping between frontend and backend. This usually leaads to long-term issues with application maintenance and scalability. Fairly common in legacy applications.
Most modern technology stacks encourage developers to have strict separation. For example in the picture you can see that backend of the first system has rest web service which is a clear separation line.
Most bottlenecks in large are caused by database/network. Databases are located in backend. As for network issues every connection goes through netowrk, so every connection has potential for being slow. With good application design these issues are avoidable to large extend.
Instead of using -f or --force developers should use
--force-with-lease
Why? Because it checks the remote branch for changes which is absolutely a good idea. Let's imagine that James and Lisa are working on the same feature branch and Lisa has pushed a commit. James now rebases his local branch and is rejected when trying to push. Of course James thinks this is due to rebase and uses --force and would rewrite all Lisa's changes. If James had used --force-with-lease he would have received a warning that there are commits done by someone else. I don't see why anyone would use --force instead of --force-with-lease when pushing after a rebase.
Try this:
$(":focus").each(function() {
alert("Focused Elem_id = "+ this.id );
});
You have endless loop in place:
function save() {
var filename = id('filename').value;
var name = id('name').value;
var text = id('text').value;
save(filename, name, text);
}
No idea what you're trying to accomplish with that endless loop but first of all get rid of it and see if things are working.
Using the new FormData object (and other ES6 stuff), you can do this to turn your entire form into JSON:
let data = {};
let formdata = new FormData(theform);
for (let tuple of formdata.entries()) data[tuple[0]] = tuple[1];
and then just xhr.send(JSON.stringify(data));
like in Jan's original answer.
They are usually stored in the following folders:
/bin/
/usr/bin/
/sbin/
/usr/sbin/
If you're not sure, use the which
command:
~$ which firefox
/usr/bin/firefox
ddd-cqrs-sample is also a good resource. Written with Java, Spring and JPA.
Updated link: https://github.com/BottegaIT/ddd-leaven-v2
String
values are not implementation dependent, according the ECMA-262 3rd Edition Specification, each character represents a single 16-bit unit of UTF-16 text:
4.3.16 String Value
A string value is a member of the type String and is a finite ordered sequence of zero or more 16-bit unsigned integer values.
NOTE Although each value usually represents a single 16-bit unit of UTF-16 text, the language does not place any restrictions or requirements on the values except that they be 16-bit unsigned integers.
If you're seeing errors from library headers and you're using GCC, then you can disable warnings by including the headers using -isystem
instead of -I
.
Similar features exist in clang.
If you're using CMake, you can specify SYSTEM
for include_directories
.
You are assigning an onclick
event inside an function.
That means once the function has executed once, the second onclick
event is assigned to the element as well.
Either assign the function
onclick
or use jqueryclick()
.
There's no need to have both
For Bootstrap 3:
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
_x000D_
<div class="row">_x000D_
<div class="col-md-4">_x000D_
<div class="well">1_x000D_
<br/>_x000D_
<br/>_x000D_
<br/>_x000D_
<br/>_x000D_
<br/>_x000D_
</div>_x000D_
</div>_x000D_
<div class="col-md-8">_x000D_
<div class="row">_x000D_
<div class="col-md-6">_x000D_
<div class="well">2</div>_x000D_
</div>_x000D_
<div class="col-md-6">_x000D_
<div class="well">3</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="row">_x000D_
<div class="col-md-6">_x000D_
<div class="well">4</div>_x000D_
</div>_x000D_
<div class="col-md-6">_x000D_
<div class="well">5</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="row">_x000D_
<div class="col-md-4">_x000D_
<div class="well">6</div>_x000D_
</div>_x000D_
<div class="col-md-4">_x000D_
<div class="well">7</div>_x000D_
</div>_x000D_
<div class="col-md-4">_x000D_
<div class="well">8</div>_x000D_
</div>_x000D_
</div>
_x000D_
For Bootstrap 2:
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="row-fluid">_x000D_
<div class="span4"><div class="well">1<br/><br/><br/><br/><br/></div></div>_x000D_
<div class="span8">_x000D_
<div class="row-fluid">_x000D_
<div class="span6"><div class="well">2</div></div>_x000D_
<div class="span6"><div class="well">3</div></div>_x000D_
</div>_x000D_
<div class="row-fluid">_x000D_
<div class="span6"><div class="well">4</div></div>_x000D_
<div class="span6"><div class="well">5</div></div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="row-fluid">_x000D_
<div class="span4">_x000D_
<div class="well">6</div>_x000D_
</div>_x000D_
<div class="span4">_x000D_
<div class="well">7</div>_x000D_
</div>_x000D_
<div class="span4">_x000D_
<div class="well">8</div>_x000D_
</div>_x000D_
</div>
_x000D_
See the demo on JSFiddle (Bootstrap 2): http://jsfiddle.net/SxcqH/52/
One easy way is to add a pass of tr
to squeeze any repeated field separators out:
$ ps | egrep 11383 | tr -s ' ' | cut -d ' ' -f 4
I ran some other question regarding ARIA. But it's content looks more promising for this question. would like to share them
What is ARIA?
If you put effort into making your website accessible to users with a variety of different browsing habits and physical disabilities, you'll likely recognize the role and aria-* attributes. WAI-ARIA (Accessible Rich Internet Applications) is a method of providing ways to define your dynamic web content and applications so that people with disabilities can identify and successfully interact with it. This is done through roles that define the structure of the document or application, or through aria-* attributes defining a widget-role, relationship, state, or property.
ARIA use is recommended in the specifications to make HTML5 applications more accessible. When using semantic HTML5 elements, you should set their corresponding role.
And see this you tube video for ARIA live.
You don't need awk for this...
echo aaa0.bbb.ccc | cut -d. -f1
cut -d. -f1 <<< aaa0.bbb.ccc
echo aaa0.bbb.ccc | { IFS=. read a _ ; echo $a ; }
{ IFS=. read a _ ; echo $a ; } <<< aaa0.bbb.ccc
x=aaa0.bbb.ccc; echo ${x/.*/}
Heavier options:
sed:
echo aaa0.bbb.ccc | sed 's/\..*//'
sed 's/\..*//' <<< aaa0.bbb.ccc
awk:
echo aaa0.bbb.ccc | awk -F. '{print $1}'
awk -F. '{print $1}' <<< aaa0.bbb.ccc
You are looking for -H
option in gnu grep.
find . -name '*bills*' -exec grep -H "put" {} \;
-H, --with-filename
Print the filename for each match.
Thanks for above answer , here is my jQuery code that is working now:
$(".header-login-li").click(function(){
activaTab('pane_login');
});
$(".header-register-li").click(function(){
activaTab('pane_reg');
$("#reg_log_modal_header_text").css()
});
function activaTab(tab){
$('.nav-tabs a[href="#' + tab + '"]').tab('show');
};
According to the stack trace, your issue is that your app cannot find org.apache.commons.dbcp.BasicDataSource
, as per this line:
java.lang.ClassNotFoundException: org.apache.commons.dbcp.BasicDataSource
I see that you have commons-dbcp in your list of jars, but for whatever reason, your app is not finding the BasicDataSource
class in it.
The code below would be a bit more efficient than the answers presented above when dealing with larger datasets.
SELECT * FROM Call WHERE
NOT EXISTS (SELECT 'x' FROM Phone_book where
Phone_book.phone_number = Call.phone_number)
Try this:
SELECT min(sal) FROM (
SELECT sal FROM emp ORDER BY sal desc) WHERE ROWNUM <= 3; -- Replace 3 with any value of N
var zoomRect: MKMapRect = MKMapRect.null
for annotation in mapView.annotations {
let annotationPoint = MKMapPoint(annotation.coordinate)
let pointRect = MKMapRect(x: annotationPoint.x, y: annotationPoint.y, width: 0.1, height: 0.1)
zoomRect = zoomRect.union(pointRect)
}
mapView.setVisibleMapRect(zoomRect, animated: true)
// Edited for swift 5
Personally, I would fix this in the .htaccess file. You should have access to that.
Define your CSS URL as such:
url(/image_dir/image.png);
In your .htacess file, put:
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^image_dir/(.*) subdir/images/$1
or
RewriteRule ^image_dir/(.*) images/$1
depending on the site.
Install express using npm: https://expressjs.com/en/starter/installing.html
Create a file named server.js at the same level of your index.html with this content:
var express = require('express');
var server = express();
server.use('/', express.static(__dirname + '/'));
server.listen(8080);
If you wish to put it in a different location, set the path on the third line:
server.use('/', express.static(__dirname + '/public'));
CD to the folder containing your file and run node from the console with this command:
node server.js
Browse to localhost:8080
To handle the possibility of int
, float
, and empty string values, I'd use a combination of a list comprehension, dictionary comprehension, along with conditional expressions, as shown:
dicts = [{'a': '1' , 'b': '' , 'c': '3.14159'},
{'d': '4' , 'e': '5' , 'f': '6'}]
print [{k: int(v) if v and '.' not in v else float(v) if v else None
for k, v in d.iteritems()}
for d in dicts]
# [{'a': 1, 'c': 3.14159, 'b': None}, {'e': 5, 'd': 4, 'f': 6}]
However dictionary comprehensions weren't added to Python 2 until version 2.7. It can still be done in earlier versions as a single expression, but has to be written using the dict
constructor like the following:
# for pre-Python 2.7
print [dict([k, int(v) if v and '.' not in v else float(v) if v else None]
for k, v in d.iteritems())
for d in dicts]
# [{'a': 1, 'c': 3.14159, 'b': None}, {'e': 5, 'd': 4, 'f': 6}]
Note that either way this creates a new dictionary of lists, instead of modifying the original one in-place (which would need to be done differently).
Well, you can actually send data via JavaScript - but you should know that this is the #1 exploit source in web pages as it's XSS :)
I personally would suggest to use an HTML formular instead and modify the javascript data on the server side.
But if you want to share between two pages (I assume they are not both on localhost, because that won't make sense to share between two both-backend-driven pages) you will need to specify the CORS headers to allow the browser to send data to the whitelisted domains.
These two links might help you, it shows the example via Node backend, but you get the point how it works:
And, of course, the CORS spec:
~Cheers
For Visual Studio Express 2013 to get rid of these problem you have to do the following.
Right click on your project click Properties. In properties window from left menus select Configuration Properties->C/C++->General
In right side select
Treat Warning As Errors NO
and
SDL Checks NO
To automatically remove all spaces from input field you need to create custom validator.
removeSpaces(c: FormControl) {
if (c && c.value) {
let removedSpaces = c.value.split(' ').join('');
c.value !== removedSpaces && c.setValue(removedSpaces);
}
return null;
}
It works with entered and pasted text.
The problem was the box "open new connection" that was checked. So I couldn't use my temporary table.
I prefer to do it in code:
// Run a specific test only
//testing::GTEST_FLAG(filter) = "MyLibrary.TestReading"; // I'm testing a new feature, run something quickly
// Exclude a specific test
testing::GTEST_FLAG(filter) = "-MyLibrary.TestWriting"; // The writing test is broken, so skip it
I can either comment out both lines to run all tests, uncomment out the first line to test a single feature that I'm investigating/working on, or uncomment the second line if a test is broken but I want to test everything else.
You can also test/exclude a suite of features by using wildcards and writing a list, "MyLibrary.TestNetwork*" or "-MyLibrary.TestFileSystem*".
There is a "3 of 9"
control on CodeProject: Barcode .NET Control
Really have to do this with JS. Here's a solution. I didn't use your class names, but I called the div within the td class name of "full-height" :-) Used jQuery, obviously. Note this was called from jQuery(document).ready(function(){ setFullHeights();}); Also note if you have images, you are going to have to iterate through them first with something like:
function loadedFullHeights(){
var imgCount = jQuery(".full-height").find("img").length;
if(imgCount===0){
return setFullHeights();
}
var loaded = 0;
jQuery(".full-height").find("img").load(function(){
loaded++;
if(loaded ===imgCount){
setFullHeights()
}
});
}
And you would want to call the loadedFullHeights() from docReady instead. This is actually what I ended up using just in case. Got to think ahead you know!
function setFullHeights(){
var par;
var height;
var $ = jQuery;
var heights=[];
var i = 0;
$(".full-height").each(function(){
par =$(this).parent();
height = $(par).height();
var tPad = Number($(par).css('padding-top').replace('px',''));
var bPad = Number($(par).css('padding-bottom').replace('px',''));
height -= tPad+bPad;
heights[i]=height;
i++;
});
for(ii in heights){
$(".full-height").eq(ii).css('height', heights[ii]+'px');
}
}
If you want to load an assembly without locking it during the duration of the PowerShell session, use this:
$bytes = [System.IO.File]::ReadAllBytes($storageAssemblyPath)
[System.Reflection.Assembly]::Load($bytes)
Where $storageAssemblyPath
is the filepath of your assembly.
This is especially usefull if you need to cleanup the ressources within your session. For example in a deployment script.
if you want some glow effect use this
@keyframes blink {
50% {
opacity: 0.0;
}
}
@-webkit-keyframes blink {
50% {
opacity: 0.0;
}
}
atom-text-editor::shadow .bracket-matcher .region {
border:none;
background-color: rgba(195,195,255,0.1);
border-bottom: 1px solid rgb(155,155,255);
box-shadow: 0px 0px 9px 4px rgba(155,155,255,0.1);
border-radius: 3px;
animation: blink 2s steps(115, start) infinite;
-webkit-animation: blink 2s steps(115, start) infinite;
}
var formData = new FormData; var arr = ['item1', 'item2', 'item3'];
arr.forEach(item => {
formData.append(
"myFile",item
); });
Update: Turns out that this method, while following STL idioms well, is actually surprisingly inefficient! Don't do this with large files. (See: http://insanecoding.blogspot.com/2011/11/how-to-read-in-file-in-c.html)
You can make a streambuf iterator out of the file and initialize the string with it:
#include <string>
#include <fstream>
#include <streambuf>
std::ifstream t("file.txt");
std::string str((std::istreambuf_iterator<char>(t)),
std::istreambuf_iterator<char>());
Not sure where you're getting the t.open("file.txt", "r")
syntax from. As far as I know that's not a method that std::ifstream
has. It looks like you've confused it with C's fopen
.
Edit: Also note the extra parentheses around the first argument to the string constructor. These are essential. They prevent the problem known as the "most vexing parse", which in this case won't actually give you a compile error like it usually does, but will give you interesting (read: wrong) results.
Following KeithB's point in the comments, here's a way to do it that allocates all the memory up front (rather than relying on the string class's automatic reallocation):
#include <string>
#include <fstream>
#include <streambuf>
std::ifstream t("file.txt");
std::string str;
t.seekg(0, std::ios::end);
str.reserve(t.tellg());
t.seekg(0, std::ios::beg);
str.assign((std::istreambuf_iterator<char>(t)),
std::istreambuf_iterator<char>());
In response to Jonathan's answer above, this only seems to work for certain delimiters. For example:
>>> a='Beautiful, is; better*than\nugly'
>>> import re
>>> re.split('; |, |\*|\n',a)
['Beautiful', 'is', 'better', 'than', 'ugly']
>>> b='1999-05-03 10:37:00'
>>> re.split('- :', b)
['1999-05-03 10:37:00']
By putting the delimiters in square brackets it seems to work more effectively.
>>> re.split('[- :]', b)
['1999', '05', '03', '10', '37', '00']
In MySQL if You don't want to change the collation and want to perform case sensitive search then just use binary keyword like this:
SELECT * FROM table_name WHERE binary username=@search_parameter and binary password=@search_parameter
For plaintext email using JavaScript, you may also use \r
with encodeURIComponent()
.
For example, this message:
hello\rthis answer is now well formated\rand it contains good knowleadge\rthat is why I am up voting
URI Encoded, results in:
hello%0Dthis%20answer%20is%20now%20well%20formated%0Dand%20it%20contains%20good%20knowleadge%0Dthat%20is%20why%20I%20am%20up%20voting
And, using the href:
mailto:[email protected]?body=hello%0Dthis%20answer%20is%20now%20well%20formated%0Dand%20it%20contains%20good%20knowleadge%0Dthat%20is%20why%20I%20am%20up%20voting
Will result in the following email body text:
hello
this answer is now well formated
and it contains good knowleadge
that is why I am up voting
This is a mix of HTML and code but it's pretty basic, easy to understand and should be fairly simple to decouple to suit your needs I think.
try {
// Find out how many items are in the table
$total = $dbh->query('
SELECT
COUNT(*)
FROM
table
')->fetchColumn();
// How many items to list per page
$limit = 20;
// How many pages will there be
$pages = ceil($total / $limit);
// What page are we currently on?
$page = min($pages, filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, array(
'options' => array(
'default' => 1,
'min_range' => 1,
),
)));
// Calculate the offset for the query
$offset = ($page - 1) * $limit;
// Some information to display to the user
$start = $offset + 1;
$end = min(($offset + $limit), $total);
// The "back" link
$prevlink = ($page > 1) ? '<a href="?page=1" title="First page">«</a> <a href="?page=' . ($page - 1) . '" title="Previous page">‹</a>' : '<span class="disabled">«</span> <span class="disabled">‹</span>';
// The "forward" link
$nextlink = ($page < $pages) ? '<a href="?page=' . ($page + 1) . '" title="Next page">›</a> <a href="?page=' . $pages . '" title="Last page">»</a>' : '<span class="disabled">›</span> <span class="disabled">»</span>';
// Display the paging information
echo '<div id="paging"><p>', $prevlink, ' Page ', $page, ' of ', $pages, ' pages, displaying ', $start, '-', $end, ' of ', $total, ' results ', $nextlink, ' </p></div>';
// Prepare the paged query
$stmt = $dbh->prepare('
SELECT
*
FROM
table
ORDER BY
name
LIMIT
:limit
OFFSET
:offset
');
// Bind the query params
$stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
$stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
// Do we have any results?
if ($stmt->rowCount() > 0) {
// Define how we want to fetch the results
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$iterator = new IteratorIterator($stmt);
// Display the results
foreach ($iterator as $row) {
echo '<p>', $row['name'], '</p>';
}
} else {
echo '<p>No results could be displayed.</p>';
}
} catch (Exception $e) {
echo '<p>', $e->getMessage(), '</p>';
}
webView.clearCache(true)
appFormWebView.clearFormData()
appFormWebView.clearHistory()
appFormWebView.clearSslPreferences()
CookieManager.getInstance().removeAllCookies(null)
CookieManager.getInstance().flush()
WebStorage.getInstance().deleteAllData()
I would suggest Travis for Open source project. It's just simple to configure and use.
Simple steps to setup:
.travis.yml
file in root of your project. Add Travis as service in your repository settings page.Now every time you commit into your repository Travis will build your project. You can follow simple steps to get started with Travis CI.
And yet another possibility:
In [2]: a = array([1, 2, 3, -4, 5])
In [3]: where(a<0, 0, a)
Out[3]: array([1, 2, 3, 0, 5])
Change . to / as the path separator and use getResourceAsStream
:
reader = new BufferedReader(new InputStreamReader(
getClass().getClassLoader().getResourceAsStream(
"com/company/app/dao/sql/SqlQueryFile.sql")));
or
reader = new BufferedReader(new InputStreamReader(
getClass().getResourceAsStream(
"/com/company/app/dao/sql/SqlQueryFile.sql")));
Note the leading slash when using Class.getResourceAsStream()
vs ClassLoader.getResourceAsStream
.
getSystemResourceAsStream
uses the system classloader which isn't what you want.
I suspect that using slashes instead of dots would work for ClassPathResource
too.
$('tr').click(function()
{
$(this).remove();
});
i think you will try the above code, as it work, but i don't know why it work for sometime and then the whole table is removed. i am also trying to remove the row by click the row. but could not find exact answer.
python -m pip install requests
or
python3 -m pip install requests
I think this is an appropriate solution:
<select id="test" name="form_select" onchange="showDiv(this)">
<option value="0">No</option>
<option value="1">Yes</option>
</select>
<div id="hidden_div" style="display:none;">Hello hidden content</div>
<script type="text/javascript">
function showDiv(select){
if(select.value==1){
document.getElementById('hidden_div').style.display = "block";
} else{
document.getElementById('hidden_div').style.display = "none";
}
}
</script>
_x000D_
Simplify or break apart the function so that it doesn't require nine arguments (or ignore pylint, but dodges like the ones you're proposing defeat the purpose of a lint tool).
EDIT: if it's a temporary measure, disable the warning for the particular function in question using a comment as described here: http://lists.logilab.org/pipermail/python-projects/2006-April/000664.html
Later, you can grep for all of the disabled warnings.
To improve the above answer: The ToTable function on dataview has a "distinct" flag.
//This will filter all records to be distinct
dt = dt.DefaultView.ToTable(true);
Check the Variables section in the Go template docs. A range may declare two variables, separated by a comma. The following should work:
{{ range $key, $value := . }}
<li><strong>{{ $key }}</strong>: {{ $value }}</li>
{{ end }}
By using the List
property.
ListBox1.AddItem "foo"
ListBox1.List(ListBox1.ListCount - 1, 1) = "bar"
DateTime dateValue;
CultureInfo culture = CultureInfo.CurrentCulture;
DateTimeStyles styles = DateTimeStyles.None;
DateTime.TryParse(datetimestring,culture, styles, out dateValue);
Why not measure it:
class Program
{
class NameComparer : IComparer<string>
{
public int Compare(string x, string y)
{
return string.Compare(x, y, true);
}
}
class Person
{
public Person(string id, string name)
{
Id = id;
Name = name;
}
public string Id { get; set; }
public string Name { get; set; }
}
static void Main()
{
List<Person> persons = new List<Person>();
persons.Add(new Person("P005", "Janson"));
persons.Add(new Person("P002", "Aravind"));
persons.Add(new Person("P007", "Kazhal"));
Sort(persons);
OrderBy(persons);
const int COUNT = 1000000;
Stopwatch watch = Stopwatch.StartNew();
for (int i = 0; i < COUNT; i++)
{
Sort(persons);
}
watch.Stop();
Console.WriteLine("Sort: {0}ms", watch.ElapsedMilliseconds);
watch = Stopwatch.StartNew();
for (int i = 0; i < COUNT; i++)
{
OrderBy(persons);
}
watch.Stop();
Console.WriteLine("OrderBy: {0}ms", watch.ElapsedMilliseconds);
}
static void Sort(List<Person> list)
{
list.Sort((p1, p2) => string.Compare(p1.Name, p2.Name, true));
}
static void OrderBy(List<Person> list)
{
var result = list.OrderBy(n => n.Name, new NameComparer()).ToArray();
}
}
On my computer when compiled in Release mode this program prints:
Sort: 1162ms
OrderBy: 1269ms
UPDATE:
As suggested by @Stefan here are the results of sorting a big list fewer times:
List<Person> persons = new List<Person>();
for (int i = 0; i < 100000; i++)
{
persons.Add(new Person("P" + i.ToString(), "Janson" + i.ToString()));
}
Sort(persons);
OrderBy(persons);
const int COUNT = 30;
Stopwatch watch = Stopwatch.StartNew();
for (int i = 0; i < COUNT; i++)
{
Sort(persons);
}
watch.Stop();
Console.WriteLine("Sort: {0}ms", watch.ElapsedMilliseconds);
watch = Stopwatch.StartNew();
for (int i = 0; i < COUNT; i++)
{
OrderBy(persons);
}
watch.Stop();
Console.WriteLine("OrderBy: {0}ms", watch.ElapsedMilliseconds);
Prints:
Sort: 8965ms
OrderBy: 8460ms
In this scenario it looks like OrderBy performs better.
UPDATE2:
And using random names:
List<Person> persons = new List<Person>();
for (int i = 0; i < 100000; i++)
{
persons.Add(new Person("P" + i.ToString(), RandomString(5, true)));
}
Where:
private static Random randomSeed = new Random();
public static string RandomString(int size, bool lowerCase)
{
var sb = new StringBuilder(size);
int start = (lowerCase) ? 97 : 65;
for (int i = 0; i < size; i++)
{
sb.Append((char)(26 * randomSeed.NextDouble() + start));
}
return sb.ToString();
}
Yields:
Sort: 8968ms
OrderBy: 8728ms
Still OrderBy is faster
clearfix
is the same as overflow:hidden
. Both clear floated children of the parent, but clearfix
will not cut off the element which overflow to it's parent
.
It also works in IE8 & above.
There is no need to define "."
in content & .clearfix. Just write like this:
.clr:after {
clear: both;
content: "";
display: block;
}
HTML
<div class="parent clr"></div>
Read these links for more
There's no benefit to using properties with primitive types. @property
is used with heap allocated NSObjects
like NSString*
, NSNumber*
, UIButton*
, and etc, because memory managed accessors are created for free. When you create a BOOL
, the value is always allocated on the stack and does not require any special accessors to prevent memory leakage. isWorking
is simply the popular way of expressing the state of a boolean value.
In another OO language you would make a variable private bool working;
and two accessors: SetWorking
for the setter and IsWorking
for the accessor.
you have to create a instance of the class for calling the method..
Just adding the #include <math.h>
in c source file and -lm in Makefile at the end will work for me.
gcc -pthread -o p3 p3.c -lm
$matches = array();
preg_match('/id=([0-9]+)\?/', $url, $matches);
This is safe for if the format changes. slandau's answer won't work if you ever have any other numbers in the URL.
str.strip
is the best approach for this situation, but more_itertools.strip
is also a general solution that strips both leading and trailing elements from an iterable:
Code
import more_itertools as mit
iterables = ["231512-n\n"," 12091231000-n00000","alphanum0000", "00alphanum"]
pred = lambda x: x in {"0", "\n", " "}
list("".join(mit.strip(i, pred)) for i in iterables)
# ['231512-n', '12091231000-n', 'alphanum', 'alphanum']
Details
Notice, here we strip both leading and trailing "0"
s among other elements that satisfy a predicate. This tool is not limited to strings.
See also docs for more examples of
more_itertools.strip
: strip both endsmore_itertools.lstrip
: strip the left endmore_itertools.rstrip
: strip the right endmore_itertools
is a third-party library installable via > pip install more_itertools
.
Create an AJAX postback method which writes a CSV file to your webserver and returns the url.. Set a hidden IFrame in the browser to the location of the CSV file on the server.
Your user will then be presented with the CSV download link.
This is what I typically do:
File outputDir = context.getCacheDir(); // context being the Activity pointer
File outputFile = File.createTempFile("prefix", "extension", outputDir);
As for their deletion, I am not complete sure either. Since I use this in my implementation of a cache, I manually delete the oldest files till the cache directory size comes down to my preset value.
I am answering this because it's the top result in Google for "String isBlank() Method".
If you are using Java 11 or above, you can use the String class isBlank() method. This method does the same thing as Apache Commons StringUtils class.
I have written a small post on this method examples, read it here.
It’s very easy to get in Android:
int width = Resources.getSystem().getDisplayMetrics().widthPixels;
int height = Resources.getSystem().getDisplayMetrics().heightPixels;
All that the call to urlopen()
does (according to the docs) is return a file-like object. Once you have that, you need to call its read()
method to actually pull the JSON data across the network.
Something like:
jsonurl = urlopen(url)
text = json.loads(jsonurl.read())
print text
Phantom.js is an headless webkit server and it will load any web page and render it in memory, although you might not be able to see it, there is a Screen Capture feature, in which you can export the current view as PNG, PDF, JPEG and GIF. Have a look at this example from phantom.js documentation
You can style it by the following way:
echo "<p style='color:red;'>" . $ip['cityName'] . "</p>";
echo "<p style='color:red;'>" . $ip['countryName'] . "</p>";
You can use the dangerouslySetInnerHTML
property to inject arbitrary HTML:
// Assume from another require()'ed module:_x000D_
var html = '<h1>Hello, world!</h1>'_x000D_
_x000D_
var MyComponent = React.createClass({_x000D_
render: function() {_x000D_
return React.createElement("h1", {dangerouslySetInnerHTML: {__html: html}})_x000D_
}_x000D_
})_x000D_
_x000D_
ReactDOM.render(React.createElement(MyComponent), document.getElementById('app'))
_x000D_
<script src="https://fb.me/react-0.14.3.min.js"></script>_x000D_
<script src="https://fb.me/react-dom-0.14.3.min.js"></script>_x000D_
<div id="app"></div>
_x000D_
You could even componentize this template behavior (untested):
class TemplateComponent extends React.Component {
constructor(props) {
super(props)
this.html = require(props.template)
}
render() {
return <div dangerouslySetInnerHTML={{__html: this.html}}/>
}
}
TemplateComponent.propTypes = {
template: React.PropTypes.string.isRequired
}
// use like
<TemplateComponent template='./template.html'/>
And with this, template.html
(in the same directory) looks something like (again, untested):
// ./template.html
module.exports = '<h1>Hello, world!</h1>'
For those who might have the same problem as me, I got this error when the DB I was using was actually master, and not the DB I should have been using.
Just put use [DBName]
on the top of your script, or manually change the DB in use in the SQL Server Management Studio GUI.
You can also use @mock.patch.object
:
Let's say a module my_module.py
uses pandas
to read from a database and we would like to test this module by mocking pd.read_sql_table
method (which takes table_name
as argument).
What you can do is to create (inside your test) a db_mock
method that returns different objects depending on the argument provided:
def db_mock(**kwargs):
if kwargs['table_name'] == 'table_1':
# return some DataFrame
elif kwargs['table_name'] == 'table_2':
# return some other DataFrame
In your test function you then do:
import my_module as my_module_imported
@mock.patch.object(my_module_imported.pd, "read_sql_table", new_callable=lambda: db_mock)
def test_my_module(mock_read_sql_table):
# You can now test any methods from `my_module`, e.g. `foo` and any call this
# method does to `read_sql_table` will be mocked by `db_mock`, e.g.
ret = my_module_imported.foo(table_name='table_1')
# `ret` is some DataFrame returned by `db_mock`
Removing the @Slf4J annotation from the class and then re-adding it worked for me.
You can use the following example to store a query result in a variable using PL/pgSQL:
select * into demo from maintenanceactivitytrack ;
raise notice'p_maintenanceid:%',demo;
var groups = list.GroupBy(x => x.ID);
Can anybody suggest how to get the values (List) from an IGrouping<int, smth> in such a context?
"IGrouping<int, smth> group" is actually an IEnumerable with a key, so you either:
foreach (IGrouping<int, smth> group in groups)
{
var thisIsYourGroupKey = group.Key;
List<smth> list = group.ToList(); // or use directly group.foreach
}
You could do something like this:
i={'foo':'bar', 'baz':'huh?'}
keys=i.keys() #in python 3, you'll need `list(i.keys())`
values=i.values()
print keys[values.index("bar")] #'foo'
However, any time you change your dictionary, you'll need to update your keys,values because dictionaries are not ordered in versions of Python prior to 3.7. In these versions, any time you insert a new key/value pair, the order you thought you had goes away and is replaced by a new (more or less random) order. Therefore, asking for the index in a dictionary doesn't make sense.
As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted. As of Python 3.7+ dictionaries are ordered by order of insertion.
Also note that what you're asking is probably not what you actually want. There is no guarantee that the inverse mapping in a dictionary is unique. In other words, you could have the following dictionary:
d={'i':1, 'j':1}
In that case, it is impossible to know whether you want i
or j
and in fact no answer here will be able to tell you which ('i'
or 'j'
) will be picked (again, because dictionaries are unordered). What do you want to happen in that situation? You could get a list of acceptable keys ... but I'm guessing your fundamental understanding of dictionaries isn't quite right.
List<String> list = Arrays.asList(array);
The list returned will be backed by the array, it acts like a bridge, so it will be fixed-size.
Have you tried using the ConflictResolution:=xlLocalSessionChanges parameter in the SaveAs method?
As so:
Public Sub example()
Application.DisplayAlerts = False
Application.EnableEvents = False
For Each element In sArray
XLSMToXLSX(element)
Next element
Application.DisplayAlerts = False
Application.EnableEvents = False
End Sub
Sub XLSMToXLSX(ByVal file As String)
Do While WorkFile <> ""
If Right(WorkFile, 4) <> "xlsx" Then
Workbooks.Open Filename:=myPath & WorkFile
Application.DisplayAlerts = False
Application.EnableEvents = False
ActiveWorkbook.SaveAs Filename:= _
modifiedFileName, FileFormat:= _
xlOpenXMLWorkbook, CreateBackup:=False, _
ConflictResolution:=xlLocalSessionChanges
Application.DisplayAlerts = True
Application.EnableEvents = True
ActiveWorkbook.Close
End If
WorkFile = Dir()
Loop
End Sub
The best way is to use q
parameter so that it displays the map with the point marked. eg.:
https://maps.google.com/?q=<lat>,<lng>
Not exactly for this OP, but for those who encountered 404 and cannot set response content-type
to "application/json"
(any content-type
). One possibility is a server actually responds 406 but explorer (e.g., chrome) prints it as 404.
If you do not customize message converter, spring would use AbstractMessageConverterMethodProcessor.java
. It would run:
List<MediaType> requestedMediaTypes = getAcceptableMediaTypes(request);
List<MediaType> producibleMediaTypes = getProducibleMediaTypes(request, valueType, declaredType);
and if they do not have any overlapping (the same item), it would throw HttpMediaTypeNotAcceptableException
and this finally causes 406. No matter if it is an ajax, or GET/POST, or form action, if the request uri ends with a .html
or any suffix, the requestedMediaTypes
would be "text/[that suffix]", and this conflicts with producibleMediaTypes
, which is usually:
"application/json"
"application/xml"
"text/xml"
"application/*+xml"
"application/json"
"application/*+json"
"application/json"
"application/*+json"
"application/xml"
"text/xml"
"application/*+xml"
"application/xml"
"text/xml"
"application/*+xml"
You can do something like this
var now = moment();
var time = now.hour() + ':' + now.minutes() + ':' + now.seconds();
time = time + ((now.hour()) >= 12 ? ' PM' : ' AM');
\.[]{}()<>*+-=!?^$|
]
and }
) are only need to be escaped after opening the same type of bracket.[]
-brackets some characters (like +
and -
) do sometimes work without escape.The following code works very well with Google SMTP server. You need to supply your Google username and password.
import com.sun.mail.smtp.SMTPTransport;
import java.security.Security;
import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
*
* @author doraemon
*/
public class GoogleMail {
private GoogleMail() {
}
/**
* Send email using GMail SMTP server.
*
* @param username GMail username
* @param password GMail password
* @param recipientEmail TO recipient
* @param title title of the message
* @param message message to be sent
* @throws AddressException if the email address parse failed
* @throws MessagingException if the connection is dead or not in the connected state or if the message is not a MimeMessage
*/
public static void Send(final String username, final String password, String recipientEmail, String title, String message) throws AddressException, MessagingException {
GoogleMail.Send(username, password, recipientEmail, "", title, message);
}
/**
* Send email using GMail SMTP server.
*
* @param username GMail username
* @param password GMail password
* @param recipientEmail TO recipient
* @param ccEmail CC recipient. Can be empty if there is no CC recipient
* @param title title of the message
* @param message message to be sent
* @throws AddressException if the email address parse failed
* @throws MessagingException if the connection is dead or not in the connected state or if the message is not a MimeMessage
*/
public static void Send(final String username, final String password, String recipientEmail, String ccEmail, String title, String message) throws AddressException, MessagingException {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
// Get a Properties object
Properties props = System.getProperties();
props.setProperty("mail.smtps.host", "smtp.gmail.com");
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
props.setProperty("mail.smtps.auth", "true");
/*
If set to false, the QUIT command is sent and the connection is immediately closed. If set
to true (the default), causes the transport to wait for the response to the QUIT command.
ref : http://java.sun.com/products/javamail/javadocs/com/sun/mail/smtp/package-summary.html
http://forum.java.sun.com/thread.jspa?threadID=5205249
smtpsend.java - demo program from javamail
*/
props.put("mail.smtps.quitwait", "false");
Session session = Session.getInstance(props, null);
// -- Create a new message --
final MimeMessage msg = new MimeMessage(session);
// -- Set the FROM and TO fields --
msg.setFrom(new InternetAddress(username + "@gmail.com"));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail, false));
if (ccEmail.length() > 0) {
msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccEmail, false));
}
msg.setSubject(title);
msg.setText(message, "utf-8");
msg.setSentDate(new Date());
SMTPTransport t = (SMTPTransport)session.getTransport("smtps");
t.connect("smtp.gmail.com", username, password);
t.sendMessage(msg, msg.getAllRecipients());
t.close();
}
}
Username + password is no longer a recommended solution. This is due to
I tried this and Gmail sent the email used as username in this code an email saying that We recently blocked a sign-in attempt to your Google Account, and directed me to this support page: support.google.com/accounts/answer/6010255 so it looks for it to work, the email account being used to send needs to reduce their own security
Google had released Gmail API - https://developers.google.com/gmail/api/?hl=en. We should use oAuth2 method, instead of username + password.
Here's the code snippet to work with Gmail API.
import com.google.api.client.util.Base64;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.model.Message;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Properties;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
*
* @author doraemon
*/
public class GoogleMail {
private GoogleMail() {
}
private static MimeMessage createEmail(String to, String cc, String from, String subject, String bodyText) throws MessagingException {
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
MimeMessage email = new MimeMessage(session);
InternetAddress tAddress = new InternetAddress(to);
InternetAddress cAddress = cc.isEmpty() ? null : new InternetAddress(cc);
InternetAddress fAddress = new InternetAddress(from);
email.setFrom(fAddress);
if (cAddress != null) {
email.addRecipient(javax.mail.Message.RecipientType.CC, cAddress);
}
email.addRecipient(javax.mail.Message.RecipientType.TO, tAddress);
email.setSubject(subject);
email.setText(bodyText);
return email;
}
private static Message createMessageWithEmail(MimeMessage email) throws MessagingException, IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
email.writeTo(baos);
String encodedEmail = Base64.encodeBase64URLSafeString(baos.toByteArray());
Message message = new Message();
message.setRaw(encodedEmail);
return message;
}
public static void Send(Gmail service, String recipientEmail, String ccEmail, String fromEmail, String title, String message) throws IOException, MessagingException {
Message m = createMessageWithEmail(createEmail(recipientEmail, ccEmail, fromEmail, title, message));
service.users().messages().send("me", m).execute();
}
}
To construct an authorized Gmail service through oAuth2, here's the code snippet.
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.GmailScopes;
import com.google.api.services.oauth2.Oauth2;
import com.google.api.services.oauth2.model.Userinfoplus;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.yccheok.jstock.engine.Pair;
/**
*
* @author yccheok
*/
public class Utils {
/** Global instance of the JSON factory. */
private static final GsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
/** Global instance of the HTTP transport. */
private static HttpTransport httpTransport;
private static final Log log = LogFactory.getLog(Utils.class);
static {
try {
// initialize the transport
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
} catch (IOException ex) {
log.error(null, ex);
} catch (GeneralSecurityException ex) {
log.error(null, ex);
}
}
private static File getGmailDataDirectory() {
return new File(org.yccheok.jstock.gui.Utils.getUserDataDirectory() + "authentication" + File.separator + "gmail");
}
/**
* Send a request to the UserInfo API to retrieve the user's information.
*
* @param credentials OAuth 2.0 credentials to authorize the request.
* @return User's information.
* @throws java.io.IOException
*/
public static Userinfoplus getUserInfo(Credential credentials) throws IOException
{
Oauth2 userInfoService =
new Oauth2.Builder(httpTransport, JSON_FACTORY, credentials).setApplicationName("JStock").build();
Userinfoplus userInfo = userInfoService.userinfo().get().execute();
return userInfo;
}
public static String loadEmail(File dataStoreDirectory) {
File file = new File(dataStoreDirectory, "email");
try {
return new String(Files.readAllBytes(Paths.get(file.toURI())), "UTF-8");
} catch (IOException ex) {
log.error(null, ex);
return null;
}
}
public static boolean saveEmail(File dataStoreDirectory, String email) {
File file = new File(dataStoreDirectory, "email");
try {
//If the constructor throws an exception, the finally block will NOT execute
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
try {
writer.write(email);
} finally {
writer.close();
}
return true;
} catch (IOException ex){
log.error(null, ex);
return false;
}
}
public static void logoutGmail() {
File credential = new File(getGmailDataDirectory(), "StoredCredential");
File email = new File(getGmailDataDirectory(), "email");
credential.delete();
email.delete();
}
public static Pair<Pair<Credential, String>, Boolean> authorizeGmail() throws Exception {
// Ask for only the permissions you need. Asking for more permissions will
// reduce the number of users who finish the process for giving you access
// to their accounts. It will also increase the amount of effort you will
// have to spend explaining to users what you are doing with their data.
// Here we are listing all of the available scopes. You should remove scopes
// that you are not actually using.
Set<String> scopes = new HashSet<>();
// We would like to display what email this credential associated to.
scopes.add("email");
scopes.add(GmailScopes.GMAIL_SEND);
// load client secrets
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(Utils.JSON_FACTORY,
new InputStreamReader(Utils.class.getResourceAsStream("/assets/authentication/gmail/client_secrets.json")));
return authorize(clientSecrets, scopes, getGmailDataDirectory());
}
/** Authorizes the installed application to access user's protected data.
* @return
* @throws java.lang.Exception */
private static Pair<Pair<Credential, String>, Boolean> authorize(GoogleClientSecrets clientSecrets, Set<String> scopes, File dataStoreDirectory) throws Exception {
// Set up authorization code flow.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
httpTransport, JSON_FACTORY, clientSecrets, scopes)
.setDataStoreFactory(new FileDataStoreFactory(dataStoreDirectory))
.build();
// authorize
return new MyAuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}
public static Gmail getGmail(Credential credential) {
Gmail service = new Gmail.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName("JStock").build();
return service;
}
}
To provide a user friendly way of oAuth2 authentication, I made use of JavaFX, to display the following input dialog
The key to display user friendly oAuth2 dialog can be found in MyAuthorizationCodeInstalledApp.java and SimpleSwingBrowser.java
I had this problem and this is the best solution without any external or additional script libraries: In Javascript tags or file create this function: We assume here that canvas is your canvas:
function download(){
var download = document.getElementById("download");
var image = document.getElementById("canvas").toDataURL("image/png")
.replace("image/png", "image/octet-stream");
download.setAttribute("href", image);
}
In the body part of your HTML specify the button:
<a id="download" download="image.png"><button type="button" onClick="download()">Download</button></a>
This is working and download link looks like a button. Tested in Firefox and Chrome.
In foreach
loop instead of carBootSaleList
use carBootSaleList.data
.
You probably do not need answer anymore, but it could help someone.
Here is your json:
{
"syncresponse": {
"synckey": "2011-09-30 14:52:00",
"createdtrs": [
],
"modtrs": [
],
"deletedtrs": [
{
"companyid": "UTB17",
"username": "DA",
"date": "2011-09-26",
"reportid": "31341"
}
]
}
}
and it's parsing:
JSONObject object = new JSONObject(result);
String syncresponse = object.getString("syncresponse");
JSONObject object2 = new JSONObject(syncresponse);
String synckey = object2.getString("synckey");
JSONArray jArray1 = object2.getJSONArray("createdtrs");
JSONArray jArray2 = object2.getJSONArray("modtrs");
JSONArray jArray3 = object2.getJSONArray("deletedtrs");
for(int i = 0; i < jArray3 .length(); i++)
{
JSONObject object3 = jArray3.getJSONObject(i);
String comp_id = object3.getString("companyid");
String username = object3.getString("username");
String date = object3.getString("date");
String report_id = object3.getString("reportid");
}
In all the places I've worked, database has been mandatory because of application support. As Adam said, the user might not be at his desk or the machine might be off, or you might want to quickly change someone's configuration or assign a new-joiner a default (or team member's) config.
If the settings are likely to grow as new versions of the application are released, you might want to store the data as blobs which can then be deserialized by the application. This is especially useful if you use something like Prism which discovers modules, as you can't know what settings a module will return. The blobs could be keyed by username/machine composite key. That way you can have different settings for every machine.
I've not used the in-built Settings class much so I'll abstain from commenting. :)
edittext_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/edittext_pressed" android:state_pressed="true" /> <!-- pressed -->
<item android:drawable="@drawable/edittext_disable" android:state_enabled="false" /> <!-- focused -->
<item android:drawable="@drawable/edittext_default" /> <!-- default -->
</selector>
edittext_default.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape android:shape="rectangle" >
<solid android:color="#BBDEFB" />
<padding android:bottom="2dp" />
</shape>
</item>
<item android:bottom="5dp">
<shape android:shape="rectangle" >
<solid android:color="#fff" />
<padding
android:left="0dp"
android:right="0dp" />
</shape>
</item>
<item>
<shape android:shape="rectangle" >
<solid android:color="#fff" />
</shape>
</item>
</layer-list>
edittext_pressed.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape android:shape="rectangle" >
<solid android:color="#00f" />
<padding android:bottom="2dp" />
</shape>
</item>
<item android:bottom="5dp">
<shape android:shape="rectangle" >
<solid android:color="#fff" />
<padding
android:left="0dp"
android:right="0dp" />
</shape>
</item>
<item>
<shape android:shape="rectangle" >
<solid android:color="#fff" />
</shape>
</item>
</layer-list>
edittext_disable.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape android:shape="rectangle" >
<solid android:color="#aaaaaa" />
<padding android:bottom="2dp" />
</shape>
</item>
<item android:bottom="5dp">
<shape android:shape="rectangle" >
<solid android:color="#fff" />
<padding
android:left="0dp"
android:right="0dp" />
</shape>
</item>
<item>
<shape android:shape="rectangle" >
<solid android:color="#fff" />
</shape>
</item>
</layer-list>
Actually you can fix it with following steps -
cls.__dict__
{'isFilled':True}
or {'isFilled':False}
depending upon what you have set.del cls.__dict__['isFilled']
In this case, we delete the entry which overrides the method as mentioned by BrenBarn.
In my case onChange event was typed as React.ChangeEvent:
onChange={ (e: React.ChangeEvent<HTMLSelectElement>) => {
console.warn('onChange TextInput value: ' + e.target.value);
}
}
Gives the Max Count of record in table
select max(len(Description))from Table_Name
Gives Record Having Greater Count
select Description from Table_Name group by Description having max(len(Description)) >27
Hope helps someone.
The other plus of using RecycleView
is animation, it can be done in two lines of code
RecyclerView.ItemAnimator itemAnimator = new DefaultItemAnimator();
recyclerView.setItemAnimator(itemAnimator);
But the widget is still raw, e.g you can't create header and footer.
Update: This answer has led to the development of ng2-completer
an Angular2 autocomplete component.
This is the list of existing autocomplete components for Angular2:
Credit goes to @dan-cancro for coming up with the idea
Keeping the original answer for those who wish to create their own directive:
To display autocomplete list we first need an attribute directive that will return the list of suggestions based on the input text and then display them in a dropdown. The directive has 2 options to display the list:
It looks to me that 2nd way is a better choice as it uses angular 2 core mechanisms instead of bypassing them by working directly with the DOM and therefore I'll use this method.
This is the directive code:
"use strict";
import {Directive, DynamicComponentLoader, Input, ComponentRef, Output, EventEmitter, OnInit, ViewContainerRef} from "@angular/core";
import {Promise} from "es6-promise";
import {AutocompleteList} from "./autocomplete-list";
@Directive({
selector: "[ng2-autocomplete]", // The attribute for the template that uses this directive
host: {
"(keyup)": "onKey($event)" // Liten to keyup events on the host component
}
})
export class AutocompleteDirective implements OnInit {
// The search function should be passed as an input
@Input("ng2-autocomplete") public search: (term: string) => Promise<Array<{ text: string, data: any }>>;
// The directive emits ng2AutocompleteOnSelect event when an item from the list is selected
@Output("ng2AutocompleteOnSelect") public selected = new EventEmitter();
private term = "";
private listCmp: ComponentRef<AutocompleteList> = undefined;
private refreshTimer: any = undefined;
private searchInProgress = false;
private searchRequired = false;
constructor( private viewRef: ViewContainerRef, private dcl: DynamicComponentLoader) { }
/**
* On key event is triggered when a key is released on the host component
* the event starts a timer to prevent concurrent requests
*/
public onKey(event: any) {
if (!this.refreshTimer) {
this.refreshTimer = setTimeout(
() => {
if (!this.searchInProgress) {
this.doSearch();
} else {
// If a request is in progress mark that a new search is required
this.searchRequired = true;
}
},
200);
}
this.term = event.target.value;
if (this.term === "" && this.listCmp) {
// clean the list if the search term is empty
this.removeList();
}
}
public ngOnInit() {
// When an item is selected remove the list
this.selected.subscribe(() => {
this.removeList();
});
}
/**
* Call the search function and handle the results
*/
private doSearch() {
this.refreshTimer = undefined;
// if we have a search function and a valid search term call the search
if (this.search && this.term !== "") {
this.searchInProgress = true;
this.search(this.term)
.then((res) => {
this.searchInProgress = false;
// if the term has changed during our search do another search
if (this.searchRequired) {
this.searchRequired = false;
this.doSearch();
} else {
// display the list of results
this.displayList(res);
}
})
.catch(err => {
console.log("search error:", err);
this.removeList();
});
}
}
/**
* Display the list of results
* Dynamically load the list component if it doesn't exist yet and update the suggestions list
*/
private displayList(list: Array<{ text: string, data: any }>) {
if (!this.listCmp) {
this.dcl.loadNextToLocation(AutocompleteList, this.viewRef)
.then(cmp => {
// The component is loaded
this.listCmp = cmp;
this.updateList(list);
// Emit the selectd event when the component fires its selected event
(<AutocompleteList>(this.listCmp.instance)).selected
.subscribe(selectedItem => {
this.selected.emit(selectedItem);
});
});
} else {
this.updateList(list);
}
}
/**
* Update the suggestions list in the list component
*/
private updateList(list: Array<{ text: string, data: any }>) {
if (this.listCmp) {
(<AutocompleteList>(this.listCmp.instance)).list = list;
}
}
/**
* remove the list component
*/
private removeList() {
this.searchInProgress = false;
this.searchRequired = false;
if (this.listCmp) {
this.listCmp.destroy();
this.listCmp = undefined;
}
}
}
The directive dynamically loads a dropdown component, this is a sample of such a component using bootstrap 4:
"use strict";
import {Component, Output, EventEmitter} from "@angular/core";
@Component({
selector: "autocomplete-list",
template: `<div class="dropdown-menu search-results">
<a *ngFor="let item of list" class="dropdown-item" (click)="onClick(item)">{{item.text}}</a>
</div>`, // Use a bootstrap 4 dropdown-menu to display the list
styles: [".search-results { position: relative; right: 0; display: block; padding: 0; overflow: hidden; font-size: .9rem;}"]
})
export class AutocompleteList {
// Emit a selected event when an item in the list is selected
@Output() public selected = new EventEmitter();
public list;
/**
* Listen for a click event on the list
*/
public onClick(item: {text: string, data: any}) {
this.selected.emit(item);
}
}
To use the directive in another component you need to import the directive, include it in the components directives and provide it with a search function and event handler for the selection:
"use strict";
import {Component} from "@angular/core";
import {AutocompleteDirective} from "../component/ng2-autocomplete/autocomplete";
@Component({
selector: "my-cmp",
directives: [AutocompleteDirective],
template: `<input class="form-control" type="text" [ng2-autocomplete]="search()" (ng2AutocompleteOnSelect)="onItemSelected($event)" autocomplete="off">`
})
export class MyComponent {
/**
* generate a search function that returns a Promise that resolves to array of text and optionally additional data
*/
public search() {
return (filter: string): Promise<Array<{ text: string, data: any }>> => {
// do the search
resolve({text: "one item", data: null});
};
}
/**
* handle item selection
*/
public onItemSelected(selected: { text: string, data: any }) {
console.log("selected: ", selected.text);
}
}
Update: code compatible with angular2 rc.1
The web application name (actually the context path) is available by calling HttpServletrequest#getContextPath()
(and thus NOT getServletPath()
as one suggested before). You can retrieve this in JSP by ${pageContext.request.contextPath}
.
<p>The context path is: ${pageContext.request.contextPath}.</p>
If you intend to use this for all relative paths in your JSP page (which would make this question more sense), then you can make use of the HTML <base>
tag:
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<c:set var="req" value="${pageContext.request}" />
<c:set var="url">${req.requestURL}</c:set>
<c:set var="uri" value="${req.requestURI}" />
<!doctype html>
<html lang="en">
<head>
<title>SO question 2204870</title>
<base href="${fn:substring(url, 0, fn:length(url) - fn:length(uri))}${req.contextPath}/">
<script src="js/global.js"></script>
<link rel="stylesheet" href="css/global.css">
</head>
<body>
<ul>
<li><a href="home.jsp">Home</a></li>
<li><a href="faq.jsp">FAQ</a></li>
<li><a href="contact.jsp">Contact</a></li>
</ul>
</body>
</html>
All links in the page will then automagically be relative to the <base>
so that you don't need to copypaste the context path everywhere. Note that when relative links start with a /
, then they will not be relative to the <base>
anymore, but to the domain root instead.
If anyone else is having a nullptr on the searchview variable, I found out that the item setup is a tiny bit different:
old:
android:showAsAction="ifRoom"
android:actionViewClass="android.widget.SearchView"
new:
app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="androidx.appcompat.widget.SearchView"
pre-android x:
app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="android.support.v7.widget.SearchView"
For more information, it's updated documentation is located here.
A SQL View is a virtual table, which is based on SQL SELECT query. A view references one or more existing database tables or other views. It is the snap shot of the database whereas a stored procedure is a group of Transact-SQL statements compiled into a single execution plan.
View is simple showcasing data stored in the database tables whereas a stored procedure is a group of statements that can be executed.
A view is faster as it displays data from the tables referenced whereas a store procedure executes sql statements.
Check this article : View vs Stored Procedures . Exactly what you are looking for
Usually, you don't want to expose any of your internal paths for how your server is structured to the outside world. What you can is make a /scripts
static route in your server that fetches its files from whatever directory they happen to reside in. So, if your files are in "./node_modules/bootstrap/dist/"
. Then, the script tag in your pages just looks like this:
<script src="/scripts/bootstrap.min.js"></script>
If you were using express with nodejs, a static route is as simple as this:
app.use('/scripts', express.static(__dirname + '/node_modules/bootstrap/dist/'));
Then, any browser requests from /scripts/xxx.js
will automatically be fetched from your dist
directory at __dirname + /node_modules/bootstrap/dist/xxx.js
.
Note: Newer versions of NPM put more things at the top level, not nested so deep so if you are using a newer version of NPM, then the path names will be different than indicated in the OP's question and in the current answer. But, the concept is still the same. You find out where the files are physically located on your server drive and you make an app.use()
with express.static()
to make a pseudo-path to those files so you aren't exposing the actual server file system organization to the client.
If you don't want to make a static route like this, then you're probably better off just copying the public scripts to a path that your web server does treat as /scripts
or whatever top level designation you want to use. Usually, you can make this copying part of your build/deployment process.
If you want to make just one particular file public in a directory and not everything found in that directory with it, then you can manually create individual routes for each file rather than use express.static()
such as:
<script src="/bootstrap.min.js"></script>
And the code to create a route for that
app.get('/bootstrap.min.js', function(req, res) {
res.sendFile(__dirname + '/node_modules/bootstrap/dist/bootstrap.min.js');
});
Or, if you want to still delineate routes for scripts with /scripts
, you could do this:
<script src="/scripts/bootstrap.min.js"></script>
And the code to create a route for that
app.get('/scripts/bootstrap.min.js', function(req, res) {
res.sendFile(__dirname + '/node_modules/bootstrap/dist/bootstrap.min.js');
});
T-SQL is not asynchronous, so you really have no choice but to wait until SP2 ends. Luckily, that's what you want.
CREATE PROCEDURE SP1 AS
EXEC SP2
PRINT 'Done'
List<Object> list = new ArrayList<>();
list.add(1);
list.add("1");
As the return type of ArrayList is object, you can add any type of data to ArrayList but it is not a good practice to use ArrayList because there is unnecessary boxing and unboxing.
While creating virtualenv if you use sudo the directory is created with root privileges.So when you try to install a package with non-sudo user you won't have permission to install into it. So always create virtualenv without sudo and install without sudo.
You can also copy packages installed on global python to virtualenv.
cp -r /lib/python/site-packages/* virtualenv/lib/python/site-packages/
You may find my MSDN article on the subject helpful; I took a lot of space in that article describing when you should use async
on ASP.NET, not just how to use async
on ASP.NET.
I have some concerns using async actions in ASP.NET MVC. When it improves performance of my apps, and when - not.
First, understand that async
/await
is all about freeing up threads. On GUI applications, it's mainly about freeing up the GUI thread so the user experience is better. On server applications (including ASP.NET MVC), it's mainly about freeing up the request thread so the server can scale.
In particular, it won't:
await
. await
only "yields" to the ASP.NET thread pool, not to the browser.First question is - is it good to use async action everywhere in ASP.NET MVC?
I'd say it's good to use it everywhere you're doing I/O. It may not necessarily be beneficial, though (see below).
However, it's bad to use it for CPU-bound methods. Sometimes devs think they can get the benefits of async
by just calling Task.Run
in their controllers, and this is a horrible idea. Because that code ends up freeing up the request thread by taking up another thread, so there's no benefit at all (and in fact, they're taking the penalty of extra thread switches)!
Shall I use async/await keywords when I want to query database (via EF/NHibernate/other ORM)?
You could use whatever awaitable methods you have available. Right now most of the major players support async
, but there are a few that don't. If your ORM doesn't support async
, then don't try to wrap it in Task.Run
or anything like that (see above).
Note that I said "you could use". If you're talking about ASP.NET MVC with a single database backend, then you're (almost certainly) not going to get any scalability benefit from async
. This is because IIS can handle far more concurrent requests than a single instance of SQL server (or other classic RDBMS). However, if your backend is more modern - a SQL server cluster, Azure SQL, NoSQL, etc - and your backend can scale, and your scalability bottleneck is IIS, then you can get a scalability benefit from async
.
Third question - How many times I can use await keywords to query database asynchronously in ONE single action method?
As many as you like. However, note that many ORMs have a one-operation-per-connection rule. In particular, EF only allows a single operation per DbContext; this is true whether the operation is synchronous or asynchronous.
Also, keep in mind the scalability of your backend again. If you're hitting a single instance of SQL Server, and your IIS is already capable of keeping SQLServer at full capacity, then doubling or tripling the pressure on SQLServer is not going to help you at all.
You can use jQuery.children property.
var numItems = $('.wrapper').children('div').length;
for more information refer http://api.jquery.com/
java.text.NumberFormat is probably what you want.
For me worked like a charm
element(by.cssContainingText('option', 'BeaverBox Testing')).click();
I am not sure if this is the case but this problem seems to occur a number of times when migrating wordpress sites or migrating dynamic sites in general. If this is the case make sure the hosting you are migrating to uses the same PHP version your old site uses.
If you are not migrating your site and this is just a problem that has come up try updating to PHP 5. This takes care of some of these problems. Might seem like a silly solution but did the trick for me.
I do not think a Git commit can record an intention like “stop tracking this file, but do not delete it”.
Enacting such an intention will require intervention outside Git in any repositories that merge (or rebase onto) a commit that deletes the file.
Probably the easiest thing to do is to tell your downstream users to save a copy of the file, pull your deletion, then restore the file.
If they are pulling via rebase and are ‘carrying’ modifications to the file, they will get conflicts. To resolve such conflicts, use git rm foo.conf && git rebase --continue
(if the conflicting commit has changes besides those to the removed file) or git rebase --skip
(if the conflicting commit has only changed to the removed file).
If they have already pulled your deletion commit, they can still recover the previous version of the file with git show:
git show @{1}:foo.conf >foo.conf
Or with git checkout (per comment by William Pursell; but remember to re-remove it from the index!):
git checkout @{1} -- foo.conf && git rm --cached foo.conf
If they have taken other actions since pulling your deletion (or they are pulling with rebase into a detached HEAD), they may need something other than @{1}
. They could use git log -g
to find the commit just before they pulled your deletion.
In a comment, you mention that the file you want to “untrack, but keep” is some kind of configuration file that is required for running the software (directly out of a repository).
If it is not completely unacceptable to continue to maintain the configuration file's content in the repository, you might be able to rename the tracked file from (e.g.) foo.conf
to foo.conf.default
and then instruct your users to cp foo.conf.default foo.conf
after applying the rename commit.
Or, if the users already use some existing part of the repository (e.g. a script or some other program configured by content in the repository (e.g. Makefile
or similar)) to launch/deploy your software, you could incorporate a defaulting mechanism into the launch/deploy process:
test -f foo.conf || test -f foo.conf.default &&
cp foo.conf.default foo.conf
With such a defaulting mechanism in place, users should be able to pull a commit that renames foo.conf
to foo.conf.default
without having to do any extra work.
Also, you avoid having to manually copy a configuration file if you make additional installations/repositories in the future.
If it is unacceptable to maintain the content in the repository then you will likely want to completely eradicate it from history with something like git filter-branch --index-filter …
.
This amounts to rewriting history, which will require manual intervention for each branch/repository (see “Recovering From Upstream Rebase” section in the git rebase manpage).
The special treatment required for your configuration file would be just another step that one must perform while recovering from the rewrite:
Whatever method you use, you will probably want to include the configuration filename in a .gitignore
file in the repository so that no one can inadvertently git add foo.conf
again (it is possible, but requires -f
/--force
).
If you have more than one configuration file, you might consider ‘moving’ them all into a single directory and ignoring the whole thing (by ‘moving’ I mean changing where the program expects to find its configuration files, and getting the users (or the launch/deploy mechanism) to copy/move the files to to their new location; you obviously would not want to git mv a file into a directory that you will be ignoring).
For people (like me) who really want PathLocationStrategy
(i.e. html5Mode) instead of HashLocationStrategy
, see How to: Configure your server to work with html5Mode from a third-party wiki:
When you have html5Mode enabled, the
#
character will no longer be used in your URLs. The#
symbol is useful because it requires no server side configuration. Without#
, the URL looks much nicer, but it also requires server side rewrites.
Here I only copy three examples from the wiki, in case the Wiki get lost. Other examples can be found by searching keyword "URL rewrite" (e.g. this answer for Firebase).
<VirtualHost *:80>
ServerName my-app
DocumentRoot /path/to/app
<Directory /path/to/app>
RewriteEngine on
# Don't rewrite files or directories
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
# Rewrite everything else to index.html to allow HTML5 state links
RewriteRule ^ index.html [L]
</Directory>
</VirtualHost>
Documentation for rewrite module
server {
server_name my-app;
root /path/to/app;
location / {
try_files $uri $uri/ /index.html;
}
}
<system.webServer>
<rewrite>
<rules>
<rule name="Main Rule" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
</rules>
</rewrite>
</system.webServer>
Your destructor might be executing inside a chain of other destructors. Throwing an exception that is not caught by your immediate caller can leave multiple objects in an inconsistent state, thus causing even more problems then ignoring the error in the cleanup operation.
Just connect to Internet and start Android Studio and open your project. While Gradle Sync it will download the dependencies from Internet(All JAR Files). This solved it for me. No Editing in Gradle file ,all was done by Android Studio Automatically. Using Android Studio 2.2 :)
Also don't forget to install Java JDK 1.x(7 or 8 all works fine).
Old question but I stumbled here so why not take a shot at it since the question is seeking various perspective and not a definitive answer.
w3c may have its recommendations - which I care a lot - but want to rethink since the question is here.
Why does w3c consider domain names be case insensitive and leaves anything afterwards case insensitive ?
I am thinking that the rationale is that the domain part of the URL is hand typed by a user. Everything after being hyper text will be resolved by the machine (browser and server in the back).
Machines can handle case insensitivity better than humans (not the technical kind:)).
But the question is just because the machines CAN handle that should it be done that way ?
I mean what are the benefits of naming and accessing a resource sitting at hereIsTheResource
vs hereistheresource
?
The lateral is very unreadable than the camel case one which is more readable. Readable to Humans (including the technical kind.)
So here are my points:-
Resource Path falls in the somewhere in the middle of programming structure and being close to an end user behind the browser sometimes.
Your URL (excluding the domain name) should be case insensitive if your users are expected to touch it or type it etc. You should develop your application to AVOID having users type the path as much as possible.
Your URL (excluding the domain name) should be case sensitive if your users would never type it by hand.
Conclusion
Path should be case sensitive. My points are weighing towards the case sensitive paths.
SHOW CREATE TABLE yourTable;
or
SHOW COLUMNS FROM yourTable;
In my case the "SQL Server" Server service stopped. When I restarted the service that enabled me to run the query and eliminate the error.
Its also a good idea to examine your query to find out why the query made this service stop
All you need to do is a post request like below :-
POST https://www.googleapis.com/oauth2/v4/token
Content-Type: application/json
{
"client_id": <client_id>,
"client_secret": <client_secret>,
"refresh_token": <refresh_token>,
"grant_type": "refresh_token"
}
There's a setSeconds
method as well:
var t = new Date();
t.setSeconds(t.getSeconds() + 10);
For a list of the other Date
functions, you should check out MDN
setSeconds
will correctly handle wrap-around cases:
var d;_x000D_
d = new Date('2014-01-01 10:11:55');_x000D_
alert(d.getMinutes() + ':' + d.getSeconds()); //11:55_x000D_
d.setSeconds(d.getSeconds() + 10);_x000D_
alert(d.getMinutes() + ':0' + d.getSeconds()); //12:05
_x000D_
std::string a = "Hello ";
std::string b = "World ";
std::string c = a;
c.append(b);
The solutions posted so far either only replace Environment.NewLine
or they fail if the replacement string contains line breaks because they call string.Replace
multiple times.
Here's a solution that uses a regular expression to make all three replacements in just one pass over the string. This means that the replacement string can safely contain line breaks.
string result = Regex.Replace(input, @"\r\n?|\n", replacementString);
An alternative is not to replace the .class file in the jar file. Instead put it into a new jar file and ensure that it appears earlier on your classpath than the original jar file.
Not sure I would recommend this for production software but for development it is quick and easy.
You can use ghget with any URL copied from the address bar:
ghget https://github.com/fivethirtyeight/data/tree/master/airline-safety
It's a self-contained portable shell script that doesn't use SVN (which didn't work for me on a big repo). It also doesn't use the API so it doesn't require a token and isn't rate-limited.
Disclaimer: I made it.
you may check this http://coenraets.org/blog/2011/10/sample-application-with-jquery-mobile-and-phonegap/ and you can also check http://mobile.tutsplus.com/category/tutorials/phonegap/ which provide you with a good sample
It's an attribute designed to help assistive technology (e.g. screen readers) attach a label to an otherwise anonymous HTML element.
So there's the <label>
element:
<label for="fmUserName">Your name</label>
<input id="fmUserName">
The <label>
explicitly tells the user to type their name into the input
box where id="fmUserName"
.
aria-label
does much the same thing, but it's for those cases where it isn't practical or desirable to have a label
on screen. Take the MDN example:
<button aria-label="Close" onclick="myDialog.close()">X</button>`
Most people would be able to infer visually that this button will close the dialog. A blind person using assistive technology might just hear "X" read aloud, which doesn't mean much without the visual clues. aria-label
explicitly tells them what the button will do.
sp_executesql
is more likely to promote query plan reuse. When using sp_executesql
, parameters are explicitly identified in the calling signature. This excellent article descibes this process.
The oft cited reference for many aspects of dynamic sql is Erland Sommarskog's must read: "The Curse and Blessings of Dynamic SQL".
var startTime = new TimeSpan(6, 0, 0); // 6:00 AM
var endTime = new TimeSpan(5, 30, 0); // 5:30 AM
var hours24 = new TimeSpan(24, 0, 0);
var difference = endTime.Subtract(startTime); // (-00:30:00)
difference = (difference.Duration() != difference) ? hours24.Subtract(difference.Duration()) : difference; // (23:30:00)
can also add difference between the dates if we compare two different dates
new TimeSpan(24 * days, 0, 0)
As a beginner who stumbled across this thread, I'd like to add a python-for-dummies adaptation of abevieiramota's very neat answer (because I'm at the level that I had to look up 'ravel' to work out what their code was doing):
import numpy as np
import matplotlib.pyplot as plt
fig, ((ax1,ax2,ax3),(ax4,ax5,ax6)) = plt.subplots(2,3)
axlist = [ax1,ax2,ax3,ax4,ax5,ax6]
first = ax1.imshow(np.random.random((10,10)), vmin=0, vmax=1)
third = ax3.imshow(np.random.random((12,12)), vmin=0, vmax=1)
fig.colorbar(first, ax=axlist)
plt.show()
Much less pythonic, much easier for noobs like me to see what's actually happening here.
As of Pandas 0.17 there is now a styling system which essentially provides formatted views of a DataFrame using Python format strings:
import pandas as pd
import numpy as np
constants = pd.DataFrame([('pi',np.pi),('e',np.e)],
columns=['name','value'])
C = constants.style.format({'name': '~~ {} ~~', 'value':'--> {:15.10f} <--'})
C
which displays
This is a view object; the DataFrame itself does not change formatting, but updates in the DataFrame are reflected in the view:
constants.name = ['pie','eek']
C
However it appears to have some limitations:
Adding new rows and/or columns in-place seems to cause inconsistency in the styled view (doesn't add row/column labels):
constants.loc[2] = dict(name='bogus', value=123.456)
constants['comment'] = ['fee','fie','fo']
constants
which looks ok but:
C
Formatting works only for values, not index entries:
constants = pd.DataFrame([('pi',np.pi),('e',np.e)],
columns=['name','value'])
constants.set_index('name',inplace=True)
C = constants.style.format({'name': '~~ {} ~~', 'value':'--> {:15.10f} <--'})
C
split(delimiter)
by default removes trailing empty strings from result array. To turn this mechanism off we need to use overloaded version of split(delimiter, limit)
with limit
set to negative value like
String[] split = data.split("\\|", -1);
Little more details:
split(regex)
internally returns result of split(regex, 0)
and in documentation of this method you can find (emphasis mine)
The
limit
parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array.If the limit
n
is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter.If
n
is non-positive then the pattern will be applied as many times as possible and the array can have any length.If
n
is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.
Exception:
It is worth mentioning that removing trailing empty string makes sense only if such empty strings ware created by split mechanism. So for "".split(anything)
since we can't split ""
farther we will get as result [""]
array.
It happens because split didn't happen here, so ""
despite being empty and trailing represents original string, not empty string which was created by splitting process.
add this to you CSS:
html, body
{
height: 100%;
}
when you say to wrap
to be 100%
, 100% of what? of its parent (body), so his parent has to have some height.
and the same goes for body
, his parent his html
. html
parent his the viewport..
so, by setting them both to 100%, wrap
can also have a percentage height.
also: the elements have some default padding/margin, that causes them to span a little more then the height you applied to them. (causing a scroll bar) you can use
*
{
padding: 0;
margin: 0;
}
to disable that.
Look at That Fiddle
You can also use FormData (But not available in IE):
var formData = new FormData(document.getElementsByName('yourForm')[0]);// yourForm: form selector
$.ajax({
type: "POST",
url: "yourURL",// where you wanna post
data: formData,
processData: false,
contentType: false,
error: function(jqXHR, textStatus, errorMessage) {
console.log(errorMessage); // Optional
},
success: function(data) {console.log(data)}
});
This is how you use FormData.
I run into the same problem and wrote a little shared-memory utility class to work around it.
I'm using multiprocessing.RawArray
(lockfree), and also the access to the arrays is not synchronized at all (lockfree), be careful not to shoot your own feet.
With the solution I get speedups by a factor of approx 3 on a quad-core i7.
Here's the code: Feel free to use and improve it, and please report back any bugs.
'''
Created on 14.05.2013
@author: martin
'''
import multiprocessing
import ctypes
import numpy as np
class SharedNumpyMemManagerError(Exception):
pass
'''
Singleton Pattern
'''
class SharedNumpyMemManager:
_initSize = 1024
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(SharedNumpyMemManager, cls).__new__(
cls, *args, **kwargs)
return cls._instance
def __init__(self):
self.lock = multiprocessing.Lock()
self.cur = 0
self.cnt = 0
self.shared_arrays = [None] * SharedNumpyMemManager._initSize
def __createArray(self, dimensions, ctype=ctypes.c_double):
self.lock.acquire()
# double size if necessary
if (self.cnt >= len(self.shared_arrays)):
self.shared_arrays = self.shared_arrays + [None] * len(self.shared_arrays)
# next handle
self.__getNextFreeHdl()
# create array in shared memory segment
shared_array_base = multiprocessing.RawArray(ctype, np.prod(dimensions))
# convert to numpy array vie ctypeslib
self.shared_arrays[self.cur] = np.ctypeslib.as_array(shared_array_base)
# do a reshape for correct dimensions
# Returns a masked array containing the same data, but with a new shape.
# The result is a view on the original array
self.shared_arrays[self.cur] = self.shared_arrays[self.cnt].reshape(dimensions)
# update cnt
self.cnt += 1
self.lock.release()
# return handle to the shared memory numpy array
return self.cur
def __getNextFreeHdl(self):
orgCur = self.cur
while self.shared_arrays[self.cur] is not None:
self.cur = (self.cur + 1) % len(self.shared_arrays)
if orgCur == self.cur:
raise SharedNumpyMemManagerError('Max Number of Shared Numpy Arrays Exceeded!')
def __freeArray(self, hdl):
self.lock.acquire()
# set reference to None
if self.shared_arrays[hdl] is not None: # consider multiple calls to free
self.shared_arrays[hdl] = None
self.cnt -= 1
self.lock.release()
def __getArray(self, i):
return self.shared_arrays[i]
@staticmethod
def getInstance():
if not SharedNumpyMemManager._instance:
SharedNumpyMemManager._instance = SharedNumpyMemManager()
return SharedNumpyMemManager._instance
@staticmethod
def createArray(*args, **kwargs):
return SharedNumpyMemManager.getInstance().__createArray(*args, **kwargs)
@staticmethod
def getArray(*args, **kwargs):
return SharedNumpyMemManager.getInstance().__getArray(*args, **kwargs)
@staticmethod
def freeArray(*args, **kwargs):
return SharedNumpyMemManager.getInstance().__freeArray(*args, **kwargs)
# Init Singleton on module load
SharedNumpyMemManager.getInstance()
if __name__ == '__main__':
import timeit
N_PROC = 8
INNER_LOOP = 10000
N = 1000
def propagate(t):
i, shm_hdl, evidence = t
a = SharedNumpyMemManager.getArray(shm_hdl)
for j in range(INNER_LOOP):
a[i] = i
class Parallel_Dummy_PF:
def __init__(self, N):
self.N = N
self.arrayHdl = SharedNumpyMemManager.createArray(self.N, ctype=ctypes.c_double)
self.pool = multiprocessing.Pool(processes=N_PROC)
def update_par(self, evidence):
self.pool.map(propagate, zip(range(self.N), [self.arrayHdl] * self.N, [evidence] * self.N))
def update_seq(self, evidence):
for i in range(self.N):
propagate((i, self.arrayHdl, evidence))
def getArray(self):
return SharedNumpyMemManager.getArray(self.arrayHdl)
def parallelExec():
pf = Parallel_Dummy_PF(N)
print(pf.getArray())
pf.update_par(5)
print(pf.getArray())
def sequentialExec():
pf = Parallel_Dummy_PF(N)
print(pf.getArray())
pf.update_seq(5)
print(pf.getArray())
t1 = timeit.Timer("sequentialExec()", "from __main__ import sequentialExec")
t2 = timeit.Timer("parallelExec()", "from __main__ import parallelExec")
print("Sequential: ", t1.timeit(number=1))
print("Parallel: ", t2.timeit(number=1))
Why not just try loading all the files in the folder? If OpenCV can't open it, oh well. Move on to the next. cv2.imread()
returns None
if the image can't be opened. Kind of weird that it doesn't raise an exception.
import cv2
import os
def load_images_from_folder(folder):
images = []
for filename in os.listdir(folder):
img = cv2.imread(os.path.join(folder,filename))
if img is not None:
images.append(img)
return images
You need to examine (put a breakpoint on / Quick Watch) the Request object in the Page_Load
method of your Test.aspx.cs
file.
I understand you want to open a xml file using php. That's called to parse a xml file. The best reference is here.
To install font-awesome you first should install it with npm. So in your project root directory type:
npm install font-awesome --save
(Of course I assume you have node.js and npm already installed. And you've done npm install
in your projects root directory)
Then edit the resources/assets/sass/app.scss
file and add at the top this line:
@import "node_modules/font-awesome/scss/font-awesome.scss";
Now you can do for example:
npm run dev
This builds unminified versions of the resources in the correct folders. If you wanted to minify them, you would instead run:
npm run production
And then you can use the font.
I had same problem and i find out solution by following this guide . I run with goal in maven.
clean package
Its worked for me Thanq
From Eclipse
You cannot launch a web page from an elevated application. This will raise a 0x800004005 exception, probably because explorer.exe and the browser are running non-elevated.
To launch a web page from an elevated application in a non-elevated web browser, use the code made by Mike Feng. I tried to pass the URL to lpApplicationName but that didn't work. Also not when I use CreateProcessWithTokenW with lpApplicationName = "explorer.exe" (or iexplore.exe) and lpCommandLine = url.
The following workaround does work: Create a small EXE-project that has one task: Process.Start(url), use CreateProcessWithTokenW to run this .EXE. On my Windows 8 RC this works fine and opens the web page in Google Chrome.
Try this.
CameraManager camManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
String cameraId = null; // Usually front camera is at 0 position.
try {
cameraId = camManager.getCameraIdList()[0];
camManager.setTorchMode(cameraId, true);
} catch (CameraAccessException e) {
e.printStackTrace();
}
I solve such queries using this pattern:
SELECT *
FROM t
WHERE t.field=(
SELECT MAX(t.field)
FROM t AS t0
WHERE t.group_column1=t0.group_column1
AND t.group_column2=t0.group_column2 ...)
That is it will select records where the value of a field is at its max value. To apply it to your query I used the common table expression so that I don't have to repeat the JOIN twice:
WITH site_history AS (
SELECT sites.siteName, sites.siteIP, history.date
FROM sites
JOIN history USING (siteName)
)
SELECT *
FROM site_history h
WHERE date=(
SELECT MAX(date)
FROM site_history h0
WHERE h.siteName=h0.siteName)
ORDER BY siteName
It's important to note that it works only if the field we're calculating the maximum for is unique. In your example the date
field should be unique for each siteName
, that is if the IP can't be changed multiple times per millisecond. In my experience this is commonly the case otherwise you don't know which record is the newest anyway. If the history
table has an unique index for (site, date)
, this query is also very fast, index range scan on the history
table scanning just the first item can be used.
I solved this type of error by making a directory in the onCreate event, then accessing the directory by creating a new file object in a method that needs to do something such as save or retrieve a file in that directory, hope this helps!
public class MyClass {
private String state;
public File myFilename;
@Override
protected void onCreate(Bundle savedInstanceState) {//create your directory the user will be able to find
super.onCreate(savedInstanceState);
if (Environment.MEDIA_MOUNTED.equals(state)) {
myFilename = new File(Environment.getExternalStorageDirectory().toString() + "/My Directory");
if (!myFilename.exists()) {
myFilename.mkdirs();
}
}
}
public void myMethod {
File fileTo = new File(myFilename.toString() + "/myPic.png");
// use fileTo object to save your file in your new directory that was created in the onCreate method
}
}
Besides de color, my problem was that I was setting the text using textlabel
bt.titleLabel?.text = title
and I solved changing to:
bt.setTitle(title, for: .normal)
https://docs.djangoproject.com/en/stable/topics/db/queries/#creating-objects
To create and save an object in a single step, use the
create()
method.
For future reference, one can use this code
ES6:
_clone: function(obj){
let newObj = {};
for(let i in obj){
if(typeof(obj[i]) === 'object' && Object.keys(obj[i]).length){
newObj[i] = clone(obj[i]);
} else{
newObj[i] = obj[i];
}
}
return Object.assign({},newObj);
}
ES5:
function clone(obj){
let newObj = {};
for(let i in obj){
if(typeof(obj[i]) === 'object' && Object.keys(obj[i]).length){
newObj[i] = clone(obj[i]);
} else{
newObj[i] = obj[i];
}
}
return Object.assign({},newObj);
}
E.g
var obj ={a:{b:1,c:3},d:4,e:{f:6}}
var xc = clone(obj);
console.log(obj); //{a:{b:1,c:3},d:4,e:{f:6}}
console.log(xc); //{a:{b:1,c:3},d:4,e:{f:6}}
xc.a.b = 90;
console.log(obj); //{a:{b:1,c:3},d:4,e:{f:6}}
console.log(xc); //{a:{b:90,c:3},d:4,e:{f:6}}
I found that if the exception is thrown in the same method that it is caught, the stack trace is not preserved, for what it's worth.
void testExceptionHandling()
{
try
{
throw new ArithmeticException("illegal expression");
}
catch (Exception ex)
{
throw;
}
finally
{
System.Diagnostics.Debug.WriteLine("finally called.");
}
}
Try this:
$('#mySelectElement option')[0].selected = true;
Regards!