If you want to open it for a range and for a protocol
ufw allow 11200:11299/tcp
ufw allow 11200:11299/udp
I just experienced the same behavior of tools:replace=...
as described by the OP.
It turned out that the root cause for tools:replace
being ignored by the manifest merger is a bug described here. It basically means that if you have a library in your project that contains a manifest with an <application ...>
node containing a tools:ignore=...
attribute, it can happen that the tools:replace=...
attribute in the manifest of your main module will be ignored.
The tricky point here is that it can happen, but does not have to. In my case I had two libraries, library A with the tools:ignore=...
attribute, library B with the attributes to be replaced in the respective manifests and the tools:replace=...
attribute in the manifest of the main module. If the manifest of B was merged into the main manifest before the manifest of A everything worked as expected. In opposite merge order the error appeared.
The order in which these merges happen seems to be somewhat random. In my case changing the order in the dependencies section of build.gradle
had no effect but changing the name of the flavor did it.
So, the only reliable workaround seems to be to unpack the problem causing library, remove the tools:ignore=...
tag (which should be no problem as it is a hint for lint only) and pack the library again.
And vote for the bug to be fixed, of cause.
This works too:
var exeBlk = {
() -> Void in
}
exeBlk = {
//do something
}
//instead of nil:
exeBlk = {}
As other noted you have several options. If you want only mathematical functions. You can import only Darwin.
import Darwin
If you want mathematical functions and other standard classes and functions. You can import Foundation.
import Foundation
If you want everything and also classes for user interface, it depends if your playground is for OS X or iOS.
For OS X, you need import Cocoa.
import Cocoa
For iOS, you need import UIKit.
import UIKit
You can easily discover your playground platform by opening File Inspector (??1).
To start redis with a config file all you need to do is specifiy the config file as an argument:
redis-server /root/config/redis.rb
Instead of using and killing PID's I would suggest creating an init script for your service
I would suggest taking a look at the Installing Redis more properly section of http://redis.io/topics/quickstart. It will walk you through setting up an init script with redis so you can just do something like service redis_server start
and service redis_server stop
to control your server.
I am not sure exactly what distro you are using, that article describes instructions for a Debian based distro. If you are are using a RHEL/Fedora distro let me know, I can provide you with instructions for the last couple of steps, the config file and most of the other steps will be the same.
Use FileSaver.js
. It supports Chrome, Edge, Firefox, and IE 10+ (and probably IE < 10 with a few "polyfills" - see Note 4). FileSaver.js
implements the saveAs() FileSaver interface in browsers that do not natively support it:
https://github.com/eligrey/FileSaver.js
Minified version is really small at < 2.5KB, gzipped < 1.2KB.
Usage:
/* TODO: replace the blob content with your byte[] */
var blob = new Blob([yourBinaryDataAsAnArrayOrAsAString], {type: "application/octet-stream"});
var fileName = "myFileName.myExtension";
saveAs(blob, fileName);
You might need Blob.js in some browsers (see Note 3). Blob.js implements the W3C Blob interface in browsers that do not natively support it. It is a cross-browser implementation:
https://github.com/eligrey/Blob.js
Consider StreamSaver.js if you have files larger than blob's size limitations.
Complete example:
/* Two options_x000D_
* 1. Get FileSaver.js from here_x000D_
* https://github.com/eligrey/FileSaver.js/blob/master/FileSaver.min.js -->_x000D_
* <script src="FileSaver.min.js" />_x000D_
*_x000D_
* Or_x000D_
*_x000D_
* 2. If you want to support only modern browsers like Chrome, Edge, Firefox, etc., _x000D_
* then a simple implementation of saveAs function can be:_x000D_
*/_x000D_
function saveAs(blob, fileName) {_x000D_
var url = window.URL.createObjectURL(blob);_x000D_
_x000D_
var anchorElem = document.createElement("a");_x000D_
anchorElem.style = "display: none";_x000D_
anchorElem.href = url;_x000D_
anchorElem.download = fileName;_x000D_
_x000D_
document.body.appendChild(anchorElem);_x000D_
anchorElem.click();_x000D_
_x000D_
document.body.removeChild(anchorElem);_x000D_
_x000D_
// On Edge, revokeObjectURL should be called only after_x000D_
// a.click() has completed, atleast on EdgeHTML 15.15048_x000D_
setTimeout(function() {_x000D_
window.URL.revokeObjectURL(url);_x000D_
}, 1000);_x000D_
}_x000D_
_x000D_
(function() {_x000D_
// convert base64 string to byte array_x000D_
var byteCharacters = atob("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");_x000D_
var byteNumbers = new Array(byteCharacters.length);_x000D_
for (var i = 0; i < byteCharacters.length; i++) {_x000D_
byteNumbers[i] = byteCharacters.charCodeAt(i);_x000D_
}_x000D_
var byteArray = new Uint8Array(byteNumbers);_x000D_
_x000D_
// now that we have the byte array, construct the blob from it_x000D_
var blob1 = new Blob([byteArray], {type: "application/octet-stream"});_x000D_
_x000D_
var fileName1 = "cool.gif";_x000D_
saveAs(blob1, fileName1);_x000D_
_x000D_
// saving text file_x000D_
var blob2 = new Blob(["cool"], {type: "text/plain"});_x000D_
var fileName2 = "cool.txt";_x000D_
saveAs(blob2, fileName2);_x000D_
})();
_x000D_
Tested on Chrome, Edge, Firefox, and IE 11 (use FileSaver.js
for supporting IE 11).
You can also save from a canvas
element. See https://github.com/eligrey/FileSaver.js#saving-a-canvas.
Demos: https://eligrey.com/demos/FileSaver.js/
Blog post by author of FileSaver.js
: http://eligrey.com/blog/post/saving-generated-files-on-the-client-side
Note 1: Browser support: https://github.com/eligrey/FileSaver.js#supported-browsers
Note 2: Failed to execute 'atob' on 'Window'
Note 3: Polyfill for browsers not supporting Blob: https://github.com/eligrey/Blob.js
See http://caniuse.com/#search=blob
Note 4: IE < 10 support (I've not tested this part):
https://github.com/eligrey/FileSaver.js#ie--10
https://github.com/eligrey/FileSaver.js/issues/56#issuecomment-30917476
Downloadify is a Flash-based polyfill for supporting IE6-9: https://github.com/dcneiner/downloadify (I don't recommend Flash-based solutions in general, though.)
Demo using Downloadify and FileSaver.js for supporting IE6-9 also: http://sheetjs.com/demos/table.html
Note 5: Creating a BLOB from a Base64 string in JavaScript
Note 6: FileSaver.js
examples: https://github.com/eligrey/FileSaver.js#examples
I also had this problem and was able to solve it by enabling CORS support on the server. In my case it was an Azure server and it was easy: Enable CORS on Azure
So check for your server how it works and enable CORS. I didn't even need a browser plugin or proxy :)
The introduction of some new testing facilities in Spring 4.2.RC1 lets one write Spring integration tests that don't rely on the SpringJUnit4ClassRunner
. Check out this part of the documentation.
In your case you could write your Spring integration test and still use mocks like this:
@RunWith(MockitoJUnitRunner.class)
@ContextConfiguration("test-app-ctx.xml")
public class FooTest {
@ClassRule
public static final SpringClassRule SPRING_CLASS_RULE = new SpringClassRule();
@Rule
public final SpringMethodRule springMethodRule = new SpringMethodRule();
@Autowired
@InjectMocks
TestTarget sut;
@Mock
Foo mockFoo;
@Test
public void someTest() {
// ....
}
}
If you have used extern for functions before, exactly same philosophy is followed for templates. if not, going though extern for simple functions may help. Also, you may want to put the extern(s) in header file and include the header when you need it.
This is a very low-level exception, which is ORA-17410.
It may happen for several reasons:
A temporary problem with networking.
Wrong JDBC driver version.
Some issues with a special data structure (on database side).
Database bug.
In my case, it was a bug we hit on the database, which needs to be patched.
List<T>.Add
adds a single element. Instead, use List<T>.AddRange
to add multiple values.
Additionally, List<T>.AddRange
takes an IEnumerable<T>
, so you don't need to convert tripDetails
into a List<TripDetails>
, you can pass it directly, e.g.:
tripDetailsCollection.AddRange(tripDetails);
adb install -r exampleApp.apk
(The -r
makes it replace the existing copy, add an -s
if installing on an emulator)
Make sure the app is signed the same and is the same debug/release
variant
I set up an alias in my ~/.bash_profile
, to make it a 2char command.
alias bi="gradlew && adb install -r exampleApp.apk"
(Short for Build and Install)
May be this is useful to you.
//Method writes a string to a text file
-(void) writeToTextFile{
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt",
documentsDirectory];
//create content - four lines of text
NSString *content = @"One\nTwo\nThree\nFour\nFive";
//save content to the documents directory
[content writeToFile:fileName
atomically:NO
encoding:NSUTF8StringEncoding
error:nil];
}
//Method retrieves content from documents directory and
//displays it in an alert
-(void) displayContent{
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt",
documentsDirectory];
NSString *content = [[NSString alloc] initWithContentsOfFile:fileName
usedEncoding:nil
error:nil];
//use simple alert from my library (see previous post for details)
[ASFunctions alert:content];
[content release];
}
If you define operator<<
as a member function it will have a different decomposed syntax than if you used a non-member operator<<
. A non-member operator<<
is a binary operator, where a member operator<<
is a unary operator.
// Declarations
struct MyObj;
std::ostream& operator<<(std::ostream& os, const MyObj& myObj);
struct MyObj
{
// This is a member unary-operator, hence one argument
MyObj& operator<<(std::ostream& os) { os << *this; return *this; }
int value = 8;
};
// This is a non-member binary-operator, 2 arguments
std::ostream& operator<<(std::ostream& os, const MyObj& myObj)
{
return os << myObj.value;
}
So.... how do you really call them? Operators are odd in some ways, I'll challenge you to write the operator<<(...)
syntax in your head to make things make sense.
MyObj mo;
// Calling the unary operator
mo << std::cout;
// which decomposes to...
mo.operator<<(std::cout);
Or you could attempt to call the non-member binary operator:
MyObj mo;
// Calling the binary operator
std::cout << mo;
// which decomposes to...
operator<<(std::cout, mo);
You have no obligation to make these operators behave intuitively when you make them into member functions, you could define operator<<(int)
to left shift some member variable if you wanted to, understand that people may be a bit caught off guard, no matter how many comments you may write.
Almost lastly, there may be times where both decompositions for an operator call are valid, you may get into trouble here and we'll defer that conversation.
Lastly, note how odd it might be to write a unary member operator that is supposed to look like a binary operator (as you can make member operators virtual..... also attempting to not devolve and run down this path....)
struct MyObj
{
// Note that we now return the ostream
std::ostream& operator<<(std::ostream& os) { os << *this; return os; }
int value = 8;
};
This syntax will irritate many coders now....
MyObj mo;
mo << std::cout << "Words words words";
// this decomposes to...
mo.operator<<(std::cout) << "Words words words";
// ... or even further ...
operator<<(mo.operator<<(std::cout), "Words words words");
Note how the cout
is the second argument in the chain here.... odd right?
protected void btnExportExcel_Click(object sender, EventArgs e)
{
DataTable _datatable = new DataTable();
for (int i = 0; i < grdReport.Columns.Count; i++)
{
_datatable.Columns.Add(grdReport.Columns[i].ToString());
}
foreach (GridViewRow row in grdReport.Rows)
{
DataRow dr = _datatable.NewRow();
for (int j = 0; j < grdReport.Columns.Count; j++)
{
if (!row.Cells[j].Text.Equals(" "))
dr[grdReport.Columns[j].ToString()] = row.Cells[j].Text;
}
_datatable.Rows.Add(dr);
}
ExportDataTableToExcel(_datatable);
}
I have started using IntelliJ IDEA Community Edition version 12.1.3 and I found the setting in the following place: -
File > Other Settings > Default Settings > {choose from Code Style dropdown}
The message that you are getting is not for the default Exception of Python:
For a fresh python list, IndexError
is thrown only on index not being in range (even docs say so).
>>> l = []
>>> l[1]
IndexError: list index out of range
If we try passing multiple items to list, or some other value, we get the TypeError
:
>>> l[1, 2]
TypeError: list indices must be integers, not tuple
>>> l[float('NaN')]
TypeError: list indices must be integers, not float
However, here, you seem to be using matplotlib
that internally uses numpy
for handling arrays. On digging deeper through the codebase for numpy
, we see:
static NPY_INLINE npy_intp
unpack_tuple(PyTupleObject *index, PyObject **result, npy_intp result_n)
{
npy_intp n, i;
n = PyTuple_GET_SIZE(index);
if (n > result_n) {
PyErr_SetString(PyExc_IndexError,
"too many indices for array");
return -1;
}
for (i = 0; i < n; i++) {
result[i] = PyTuple_GET_ITEM(index, i);
Py_INCREF(result[i]);
}
return n;
}
where, the unpack method will throw an error if it the size of the index is greater than that of the results.
So, Unlike Python which raises a TypeError
on incorrect Indexes, Numpy raises the IndexError
because it supports multidimensional arrays.
For .net Core in GET method, you can do like this:
StringValues value1;
string DeviceId = string.Empty;
if (Request.Headers.TryGetValue("param1", out value1))
{
DeviceId = value1.FirstOrDefault();
}
This is how I got an AspNetUser Id and displayed it on my home page
I placed the following code in my HomeController Index() method
ViewBag.userId = User.Identity.GetUserId();
In the view page just call
ViewBag.userId
Run the project and you will be able to see your userId
I would suggest an easy way:
function resize($file, $width, $height) {
switch(pathinfo($file)['extension']) {
case "png": return imagepng(imagescale(imagecreatefrompng($file), $width, $height), $file);
case "gif": return imagegif(imagescale(imagecreatefromgif($file), $width, $height), $file);
default : return imagejpeg(imagescale(imagecreatefromjpeg($file), $width, $height), $file);
}
}
The simplest modification (to the code in your question) is this:
Range("A" & Rows.Count).End(xlUp).Select
Selection.EntireRow.Delete
Which can be simplified to:
Range("A" & Rows.Count).End(xlUp).EntireRow.Delete
For those moments when you really want to avoid building lists:
import re
import operator
from functools import reduce
count = reduce(operator.add, (1 for _ in re.finditer(my_pattern, my_string)))
Sometimes you might need to operate on huge strings. This might help.
If your data is in a matrix named foo
, the line you would run is
foo.sorted=foo[order[foo[,1]]
Oh my. This is actually so simple!
grouped = df3.groupby(level=0)
df4 = grouped.last()
df4
A B rownum
2001-01-01 00:00:00 0 0 6
2001-01-01 01:00:00 1 1 7
2001-01-01 02:00:00 2 2 8
2001-01-01 03:00:00 3 3 3
2001-01-01 04:00:00 4 4 4
2001-01-01 05:00:00 5 5 5
Follow up edit 2013-10-29
In the case where I have a fairly complex MultiIndex
, I think I prefer the groupby
approach. Here's simple example for posterity:
import numpy as np
import pandas
# fake index
idx = pandas.MultiIndex.from_tuples([('a', letter) for letter in list('abcde')])
# random data + naming the index levels
df1 = pandas.DataFrame(np.random.normal(size=(5,2)), index=idx, columns=['colA', 'colB'])
df1.index.names = ['iA', 'iB']
# artificially append some duplicate data
df1 = df1.append(df1.select(lambda idx: idx[1] in ['c', 'e']))
df1
# colA colB
#iA iB
#a a -1.297535 0.691787
# b -1.688411 0.404430
# c 0.275806 -0.078871
# d -0.509815 -0.220326
# e -0.066680 0.607233
# c 0.275806 -0.078871 # <--- dup 1
# e -0.066680 0.607233 # <--- dup 2
and here's the important part
# group the data, using df1.index.names tells pandas to look at the entire index
groups = df1.groupby(level=df1.index.names)
groups.last() # or .first()
# colA colB
#iA iB
#a a -1.297535 0.691787
# b -1.688411 0.404430
# c 0.275806 -0.078871
# d -0.509815 -0.220326
# e -0.066680 0.607233
This function returns the nth part of input string MYSTRING. Second input parameter is separator ie., SEPARATOR_OF_SUBSTR and the third parameter is Nth Part which is required.
Note: MYSTRING should end with the separator.
create or replace FUNCTION PK_GET_NTH_PART(MYSTRING VARCHAR2,SEPARATOR_OF_SUBSTR VARCHAR2,NTH_PART NUMBER)
RETURN VARCHAR2
IS
NTH_SUBSTR VARCHAR2(500);
POS1 NUMBER(4);
POS2 NUMBER(4);
BEGIN
IF NTH_PART=1 THEN
SELECT REGEXP_INSTR(MYSTRING,SEPARATOR_OF_SUBSTR, 1, 1) INTO POS1 FROM DUAL;
SELECT SUBSTR(MYSTRING,0,POS1-1) INTO NTH_SUBSTR FROM DUAL;
ELSE
SELECT REGEXP_INSTR(MYSTRING,SEPARATOR_OF_SUBSTR, 1, NTH_PART-1) INTO POS1 FROM DUAL;
SELECT REGEXP_INSTR(MYSTRING,SEPARATOR_OF_SUBSTR, 1, NTH_PART) INTO POS2 FROM DUAL;
SELECT SUBSTR(MYSTRING,POS1+1,(POS2-POS1-1)) INTO NTH_SUBSTR FROM DUAL;
END IF;
RETURN NTH_SUBSTR;
END;
Hope this helps some body, you can use this function like this in a loop to get all the values separated:
SELECT REGEXP_COUNT(MYSTRING, '~', 1, 'i') INTO NO_OF_RECORDS FROM DUAL;
WHILE NO_OF_RECORDS>0
LOOP
PK_RECORD :=PK_GET_NTH_PART(MYSTRING,'~',NO_OF_RECORDS);
-- do some thing
NO_OF_RECORDS :=NO_OF_RECORDS-1;
END LOOP;
Here NO_OF_RECORDS,PK_RECORD are temp variables.
Hope this helps.
This should work
<a href="#" onclick="function hi(){alert('Hi!')};hi()">click</a>
You may inline any javascript inside the onclick as if you were assigning the method through javascript. I think is just a matter of making code cleaner keeping your js inside a script block
The easiest way to do it, at least for me, is:
Conditional format-> Add new rule->Set your own formula:
=ISNA(MATCH(A2;$B:$B;0))
Where A2 is the first element in column A to be compared and B is the column where A's element will be searched.
Once you have set the formula and picked the format, apply this rule to all elements in the column.
Hope this helps
For Oracle For Database:
ALTER TABLE table_name MODIFY column_name VARCHAR2(255 CHAR);
I can imagine following advantages of having a class method defined as static one:
remaining advantages are probably marginal if present at all:
It is worth mentioning that while starting the keys with numbers is valid, it could cause some unintended issues.
Example:
var testObject = {
"1tile": "test value"
};
console.log(testObject.1tile); // fails, invalid syntax
console.log(testObject["1tile"]; // workaround
You have to replace string line
QString line = in.readLine();
into while:
QFile file("/home/hamad/lesson11.txt");
if(!file.open(QIODevice::ReadOnly)) {
QMessageBox::information(0, "error", file.errorString());
}
QTextStream in(&file);
while(!in.atEnd()) {
QString line = in.readLine();
QStringList fields = line.split(",");
model->appendRow(fields);
}
file.close();
Use []
:
cookie_value_add.push([productID,itemColorTitle, itemColorPath]);
or
arrayToPush.push([value1, value2, ..., valueN]);
Try this:
import java.net.HttpURLConnection;
URL url = new URL("http://www.myurl.com/sample.xml");
HttpURLConnection huc = (HttpURLConnection) url.openConnection();
HttpURLConnection.setFollowRedirects(false);
huc.setConnectTimeout(15 * 1000);
huc.setRequestMethod("GET");
huc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)");
huc.connect();
InputStream input = huc.getInputStream();
import org.jsoup.nodes.Document;
Document doc = null;
try {
doc = Jsoup.connect("http://www.myurl.com/sample.xml").get();
} catch (Exception e) {
//log error
}
And take look on how to use Jsoup: http://jsoup.org/cookbook/input/load-document-from-url
Since we're in the PowerShell area, it's extra useful if we can return a proper PowerShell object ...
I personally like this method of parsing, for the terseness:
((quser) -replace '^>', '') -replace '\s{2,}', ',' | ConvertFrom-Csv
Note: this doesn't account for disconnected ("disc") users, but works well if you just want to get a quick list of users and don't care about the rest of the information. I just wanted a list and didn't care if they were currently disconnected.
If you do care about the rest of the data it's just a little more complex:
(((quser) -replace '^>', '') -replace '\s{2,}', ',').Trim() | ForEach-Object {
if ($_.Split(',').Count -eq 5) {
Write-Output ($_ -replace '(^[^,]+)', '$1,')
} else {
Write-Output $_
}
} | ConvertFrom-Csv
I take it a step farther and give you a very clean object on my blog.
Best function to detect associative array (hash array)
<?php
function is_assoc($arr) { return (array_values($arr) !== $arr); }
?>
Just in case someone stumbles upon this like I did and doesn't realise, the two variations above are for different use cases.
The following:
.blue-border, .background {
border: 1px solid #00f;
background: #fff;
}
is for when you want to add styles to elements that have either the blue-border or background class, for example:
<div class="blue-border">Hello</div>
<div class="background">World</div>
<div class="blue-border background">!</div>
would all get a blue border and white background applied to them.
However, the accepted answer is different.
.blue-border.background {
border: 1px solid #00f;
background: #fff;
}
This applies the styles to elements that have both classes so in this example only the <div>
with both classes should get the styles applied (in browsers that interpret the CSS properly):
<div class="blue-border">Hello</div>
<div class="background">World</div>
<div class="blue-border background">!</div>
So basically think of it like this, comma separating applies to elements with one class OR another class and dot separating applies to elements with one class AND another class.
You are so close!
import pyodbc
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=SQLSRV01;DATABASE=DATABASE;UID=USER;PWD=PASSWORD')
cursor = cnxn.cursor()
cursor.execute("SELECT WORK_ORDER.TYPE,WORK_ORDER.STATUS, WORK_ORDER.BASE_ID, WORK_ORDER.LOT_ID FROM WORK_ORDER")
for row in cursor.fetchall():
print row
(the "columns()" function collects meta-data about the columns in the named table, as opposed to the actual data).
If you are sure you haven't messed the jar, then please clean the project and perform mvn clean install
. This should solve the problem.
<>
is generally a good replacement for XOR wherever it can apply to booleans.
The typical answer is this:
In Excel, File/Save As, select CSV, save your current sheet.
transfer to a holding directory on the Pg server the postgres user can access
in PostgreSQL:
COPY mytable FROM '/path/to/csv/file' WITH CSV HEADER; -- must be superuser
But there are other ways to do this too. PostgreSQL is an amazingly programmable database. These include:
Write a module in pl/javaU, pl/perlU, or other untrusted language to access file, parse it, and manage the structure.
Use CSV and the fdw_file to access it as a pseudo-table
Use DBILink and DBD::Excel
Write your own foreign data wrapper for reading Excel files.
The possibilities are literally endless....
You are setting the extra with an array. You are then trying to get a single int.
Your code should be:
int[] arrayB = extras.getIntArray("numbers");
canvas.toDataURL
is not working if the original image URL (either relative or absolute) does not belong to the same domain as the web page. Tested from a bookmarklet and a simple javascript in the web page containing the images.
Have a look to David Walsh working example. Put the html and images on your own web server, switch original image to relative or absolute URL, change to an external image URL. Only the first two cases are working.
For Activities shown within TabActivities use getParent()
final AlertDialog.Builder builder = new AlertDialog.Builder(getParent());
instead of
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
I had the same problem for a long time now, I often needed to mix Matchers and values and I never managed to do that with Mockito.... until recently ! I put the solution here hoping it will help someone even if this post is quite old.
It is clearly not possible to use Matchers AND values together in Mockito, but what if there was a Matcher accepting to compare a variable ? That would solve the problem... and in fact there is : eq
when(recommendedAccessor.searchRecommendedHolidaysProduct(eq(metas), any(List.class), any(HotelsBoardBasisType.class), any(Config.class)))
.thenReturn(recommendedResults);
In this example 'metas' is an existing list of values
Assuming that you have a DHCP server running at your router I would use:
# /etc/network/interfaces
auto lo eth0
iface lo inet loopback
iface eth0 inet dhcp
After changing the file issue (as root):
/etc/init.d/networking restart
Ok, there already is an accepted answer but I think there is a better way to do it, you just have to had a new layer a bit larger than your view and do not mask it to the bounds of the view's layer (which actually is the default behaviour). Here is the sample code :
CALayer * externalBorder = [CALayer layer];
externalBorder.frame = CGRectMake(-1, -1, myView.frame.size.width+2, myView.frame.size.height+2);
externalBorder.borderColor = [UIColor blackColor].CGColor;
externalBorder.borderWidth = 1.0;
[myView.layer addSublayer:externalBorder];
myView.layer.masksToBounds = NO;
Of course this is if you want your border to be 1 unity large, if you want more you adapt the borderWidth
and the frame of the layer accordingly.
This is better than using a second view a bit larger as a CALayer
is lighter than a UIView
and you don't have do modify the frame of myView
, which is good for instance if myView
is aUIImageView
N.B : For me the result was not perfect on simulator (the layer was not exactly at the right position so the layer was thicker on one side sometimes) but was exactly what is asked for on real device.
EDIT
Actually the problem I talk about in the N.B was just because I had reduced the screen of the simulator, on normal size there is absolutely no issue
Hope it helps
The more exact way applied to all Booostrap objects using standard classes only would be to not set top and bottom margins (as image can inherit these from parent), so I am always using:
.text-center .img-responsive {
margin-left: auto;
margin-right: auto;
}
I have also made a Gist for that, so if any changes will apply because of any bugs, update version will be always here: https://gist.github.com/jdrda/09a38bf152dd6a8aff4151c58679cc66
i strongly suggest ditto
.
just works.
ditto my/location/poop.txt this/doesnt/exist/yet/poop.txt
You could learn about Python loops here: http://en.wikibooks.org/wiki/Python_Programming/Loops
You have to know that Python doesn't have { and } for start and end of loop, instead it depends on tab chars you enter in first of line, I mean line indents.
So you can do loop inside loop with double tab (indent)
An example of double loop is like this:
onetoten = range(1,11)
tentotwenty = range(10,21)
for count in onetoten:
for count2 in tentotwenty
print(count2)
You need to add else
in your lambda function. Because you are telling what to do in case your condition(here x < 90) is met, but you are not telling what to do in case the condition is not met.
sample['PR'] = sample['PR'].apply(lambda x: 'NaN' if x < 90 else x)
Another aspect is security (obfuscation). Once a piece of code is extracted from the main application and put in a "separated" Dynamic-Link Library, it is easier to attack, analyse (reverse-engineer) the code, since it has been isolated. When the same piece of code is kept in a LIB Library, it is part of the compiled (linked) target application, and this thus harder to isolate (differentiate) that piece of code from the rest of the target binaries.
you could use a one liner option
<div ng-repeat="key in keywords">
<button ng-click="keywords.splice($index, 1)">
{{key.name}}
</button>
</div>
$index
is used by angular to show current index of the array inside ng-repeat
This caused because of Illuminate\Session\TokenMismatchException
look at this code sample how to handle it properly:
There isn't any in printf
- the two are synonyms.
We have lot of answers to this question. This answer may be helpful in some scenarios If you want to ignore the null values you can use the NOT_NULL in class level. as below
@JsonInclude(Include.NON_NULL)
class Foo
{
String bar;
}
Some times you may need to ignore the empty values such as you may have initialized the arrayList but there is no elements in that list.In that time using NOT_EMPTY annotation to ignore those empty value fields
@JsonInclude(Include.NON_EMPTY)
class Foo
{
String bar;
}
You can use Instance.ToShortDateString() for the date,
and Instance.ToShortTimeString() for the time to get date and time from the same instance.
for all those linux users that are having this problem, check if the rxjs-compat folder is locked. I had this exact same issue and I went in terminal, used the sudo su to give permission to the whole rxjs-compat folder and it was fixed. Thats assuming you imported
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
in the project.ts file where the original .map error occurred.
I'm pretty sure there'll be some C# SDKs / toolkits on Google Code for this. I found this one, but there may be others so it's worth having a browse around.
You can use a modulo operation for that.
if (n ** (1.0/3)) % 1 != 0:
print("We have a decimal number here!")
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
GO
RECONFIGURE;
GO
On OS X nothing helps poor builtin sed to become adequate. The solution is:
brew install gnu-sed
And then use gsed instead of sed, which will just work as expected.
I am using ASP.NET MVC3 with SSRS 2008 and I couldn't get @Adrian's to work 100% for me when trying to get reports from a remote server.
Finally, I found that I needed to change the Page_Load method in ViewUserControl1.ascx to look like this:
ReportViewer1.ProcessingMode = ProcessingMode.Remote;
ServerReport serverReport = ReportViewer1.ServerReport;
serverReport.ReportServerUrl = new Uri("http://<Server Name>/reportserver");
serverReport.ReportPath = "/My Folder/MyReport";
serverReport.Refresh();
I had been missing the ProcessingMode.Remote.
References:
http://msdn.microsoft.com/en-us/library/aa337091.aspx - ReportViewer
increase the padding size of font and then try to increase font size:-
style="padding-bottom:40px; font-size: 50px;"
I'd like to throw in the whoami command, which basically is a nice alias for doing %USERDOMAIN%\%USERNAME%
as proposed in other answers.
Write-Host "current user:"
Write-Host $(whoami)
if you want the color to change when you have simply add the :hover
pseudo
div.e:hover {
background-color:red;
}
You can think of (tight or loose) coupling as being literally the amount of effort it would take you to separate a particular class from its reliance on another class. For example, if every method in your class had a little finally block at the bottom where you made a call to Log4Net to log something, then you would say your class was tightly coupled to Log4Net. If your class instead contained a private method named LogSomething which was the only place that called the Log4Net component (and the other methods all called LogSomething instead), then you would say your class was loosely coupled to Log4Net (because it wouldn't take much effort to pull Log4Net out and replace it with something else).
We can do it by MySQL Workbench. Just execute this:
kill id;
Example:
kill 13412
That will remove it.
I don't think you can do it in one line of code. Try opening your activities with startActivityForResult. As the result you can pass something like a CLOSE_FLAG, which will inform your parent activity that its child activity has finished.
That said, you should probably read this answer.
Try __weak
if you get any warning regarding retain cycle else use __block
Person *strongPerson = [Person new];
__weak Person *weakPerson = person;
Now you can refer weakPerson
object inside block.
Another cause for this might be case-insensitive file systems. If you have multiple folders in your repo on the same level whose names only differ by case, you will get hit by this. Browse the source repository using its web interface (e.g. GitHub or VSTS) to make sure.
For more information: https://stackoverflow.com/a/2016426/67824
to allow google translate to be mobile friendly get rid of the layout section, layout: google.translate.TranslateElement.InlineLayout.SIMPLE
<div id="google_translate_element">
</div>
<script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({pageLanguage: 'en'}, 'google_translate_element');
}
</script>
<script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
It works on my site and it is mobile friendly. https://livinghisword.org/articles/pages/whoiscernandisourworld.php
For this issue need to add the partition for date column values, If last partition 20201231245959, then inserting the 20210110245959 values, this issue will occurs.
For that need to add the 2021 partition into that table
ALTER TABLE TABLE_NAME ADD PARTITION PARTITION_NAME VALUES LESS THAN (TO_DATE('2021-12-31 24:59:59', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIAN')) NOCOMPRESS
You can use the following to generate a number between 1 and an upper limit.
Math.abs(new Random().nextInt() % [UPPER_LIMIT]) + 1
Here is a specific example:
Example - Generate pseudo random numbers in the range 1 to 600:
Math.abs(new Random().nextInt() % 600) + 1
This will generate a random number within a range for you. In this case 1-600. You can change the value 600 to anything you need in the range of integers.
If you want to use a lower bound that is not equal to 1 then you can use the following formula.
Math.abs(new Random().nextInt() % ([UPPER_LIMIT] - [LOWER_LIMIT])) + [LOWER_LIMIT]
Here is a specific example:
Example - Generate pseudo random numbers in the range of 40 to 99:
Math.abs( new Random().nextInt() % (99 - 40) ) + 40
This will generate a random number within a range of 40 and 99.
If you are behind a proxy, the following might be useful:
adb shell settings put global global_http_proxy_port YOUR_PROXY_PORT
adb shell settings put global global_http_proxy_host YOUR_PROXY_IP
reboot
As explained in other answers, to use this ParameterizedType
approach, you need to extend the class, but that seems like extra work to make a whole new class that extends it...
So, making the class abstract it forces you to extend it, thus satisfying the subclassing requirement. (using lombok's @Getter).
@Getter
public abstract class ConfigurationDefinition<T> {
private Class<T> type;
...
public ConfigurationDefinition(...) {
this.type = (Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
...
}
}
Now to extend it without defining a new class. (Note the {} on the end... extended, but don't overwrite anything - unless you want to).
private ConfigurationDefinition<String> myConfigA = new ConfigurationDefinition<String>(...){};
private ConfigurationDefinition<File> myConfigB = new ConfigurationDefinition<File>(...){};
...
Class stringType = myConfigA.getType();
Class fileType = myConfigB.getType();
From the documentation. The develop
will not install the package but it will create a .egg-link
in the deployment directory back to the project source code directory.
So it's like installing but instead of copying to the site-packages
it adds a symbolic link (the .egg-link
acts as a multiplatform symbolic link).
That way you can edit the source code and see the changes directly without having to reinstall every time that you make a little change. This is useful when you are the developer of that project hence the name develop
. If you are just installing someone else's package you should use install
The .css()
function doesn't queue behind running animations, it's instantaneous.
To match the behaviour that you're after, you'd need to do the following:
$(document).ready(function() {
$("button").mouseover(function() {
var p = $("p#44.test").css("background-color", "yellow");
p.hide(1500).show(1500);
p.queue(function() {
p.css("background-color", "red");
});
});
});
The .queue()
function waits for running animations to run out and then fires whatever's in the supplied function.
You can use onLayout
to get the width, height, and relative-to-parent position of a component at the earliest moment that they're available:
<View
onLayout={event => {
const layout = event.nativeEvent.layout;
console.log('height:', layout.height);
console.log('width:', layout.width);
console.log('x:', layout.x);
console.log('y:', layout.y);
}}
>
Compared to using .measure()
as shown in the accepted answer, this has the advantage that you'll never have to fiddle around deferring your .measure()
calls with setTimeout
to make sure that the measurements are available, but the disadvantage that it doesn't give you offsets relative to the entire page, only ones relative to the element's parent.
Using Value2
gives a performance benefit. As per Charles Williams blog
Range.Value2 works the same way as Range.Value, except that it does not check the cell format and convert to Date or Currency. And thats probably why its faster than .Value when retrieving numbers.
So
DirArray = [a1:a5].Value2
Some answers are slightly incorrect and point to the wrong part of the docs:
If you want a component to render nothing, just return null
, as per doc:
In rare cases you might want a component to hide itself even though it was rendered by another component. To do this return null instead of its render output.
If you try to return undefined
for example, you'll get the following error:
Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.
As pointed out by other answers, null
, true
, false
and undefined
are valid children which is useful for conditional rendering inside your jsx, but it you want your component to hide / render nothing, just return null
.
As well as noting the asynchronous nature of setState, be aware that you may have competing event handlers, one doing the state change you want and the other immediately undoing it again. For example onClick on a component whose parent also handles the onClick. Check by adding trace. Prevent this by using e.stopPropagation.
#include <stdbool.h>
For someone like me here to copy and paste.
Here is a simple approach in up to 4 steps:
0 - Advise the team you are going to fix the repository
Connect with the team and let them know of the upcoming changes.
1 - Remove the last commit
Assuming your target branch is master
:
$ git checkout master # move to the target branch
$ git reset --hard HEAD^ # remove the last commit
$ git push -f # push to fix the remote
At this point you are done if you are working alone.
2 - Fix your teammate's local repositories
On your teammate's:
$ git checkout master # move to the target branch
$ git fetch # update the local references but do not merge
$ git reset --hard origin/master # match the newly fetched remote state
If your teammate had no new commits, you are done at this point and you should be in sync.
3 - Bringing back lost commits
Let's say a teammate had a new and unpublished commit that were lost in this process.
$ git reflog # find the new commit hash
$ git cherry-pick <commit_hash>
Do this for as many commits as necessary.
I have successfully used this approach many times. It requires a team effort to make sure everything is synchronized.
myUtilDate.toInstant() // Convert from legacy class to modern. `Instant` is a point on the timeline in UTC.
.atZone( // Adjust from UTC to a particular time zone to determine date. Renders a `ZonedDateTime` object.
ZoneId.of( "America/Montreal" ) // Better to specify desired/expected zone explicitly than rely implicitly on the JVM’s current default time zone.
) // Returns a `ZonedDateTime` object.
.getMonthValue() // Extract a month number. Returns a `int` number.
java.time
DetailsThe Answer by Ortomala Lokni for using java.time is correct. And you should be using java.time as it is a gigantic improvement over the old java.util.Date/.Calendar classes. See the Oracle Tutorial on java.time.
I'll add some code showing how to use java.time without regard to java.util.Date, for when you are starting out with fresh code.
Using java.time in a nutshell… An Instant
is a moment on the timeline in UTC. Apply a time zone (ZoneId
) to get a ZonedDateTime
.
The Month
class is a sophisticated enum to represent a month in general. That enum has handy methods such as getting a localized name. And rest assured that the month number in java.time is a sane one, 1-12, not the zero-based nonsense (0-11) found in java.util.Date/.Calendar.
To get the current date-time, time zone is crucial. At any moment the date is not the same around the world. Therefore the month is not the same around the world if near the ending/beginning of the month.
ZoneId zoneId = ZoneId.of( "America/Montreal" ); // Or 'ZoneOffset.UTC'.
ZonedDateTime now = ZonedDateTime.now( zoneId );
Month month = now.getMonth();
int monthNumber = month.getValue(); // Answer to the Question.
String monthName = month.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH );
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
This works in Excel 2003 (& later with minor edit, see below). Press Ctrl+Shift+Enter (not just Enter) to enter this as an array formula.
=IF(ISBLANK(A65536),INDEX(A1:A65535,MAX((A1:A65535<>"")*(ROW(A1:A65535)))),A65536)
Be aware that Excel 2003 is unable to apply an array formula to an entire column. Doing so yields #NUM!
; unpredictable results may occur! (EDIT: Conflicting information from Microsoft: The same may or may not be true about Excel 2007; problem may have been fixed in 2010.)
That's why I apply the array formula to range A1:A65535
and give special treatment to the last cell, which is A65536
in Excel 2003. Can't just say A:A
or even A1:A65536
as the latter automatically reverts to A:A
.
If you're absolutely sure A65536
is blank, then you can skip the IF
part:
=INDEX(A1:A65535,MAX((A1:A65535<>"")*(ROW(A1:A65535))))
Note that if you're using Excel 2007 or 2010, the last row number is 1048576 not 65536, so adjust the above as appropriate.
If there are no blank cells in the middle of your data, then I would just use the simpler formula, =INDEX(A:A,COUNTA(A:A))
.
The answer will vary slightly depending on whether the application or applet is using AWT or Swing.
(Basically, classes that start with J
such as JApplet
and JFrame
are Swing, and Applet
and Frame
are AWT.)
In either case, the basic steps would be:
Image
object.Component
you want to draw the background in.Step 1. Loading the image can be either by using the Toolkit
class or by the ImageIO
class.
The Toolkit.createImage
method can be used to load an Image
from a location specified in a String
:
Image img = Toolkit.getDefaultToolkit().createImage("background.jpg");
Similarly, ImageIO
can be used:
Image img = ImageIO.read(new File("background.jpg");
Step 2. The painting method for the Component
that should get the background will need to be overridden and paint the Image
onto the component.
For AWT, the method to override is the paint
method, and use the drawImage
method of the Graphics
object that is handed into the paint
method:
public void paint(Graphics g)
{
// Draw the previously loaded image to Component.
g.drawImage(img, 0, 0, null);
// Draw sprites, and other things.
// ....
}
For Swing, the method to override is the paintComponent
method of the JComponent
, and draw the Image
as with what was done in AWT.
public void paintComponent(Graphics g)
{
// Draw the previously loaded image to Component.
g.drawImage(img, 0, 0, null);
// Draw sprites, and other things.
// ....
}
Simple Component Example
Here's a Panel
which loads an image file when instantiated, and draws that image on itself:
class BackgroundPanel extends Panel
{
// The Image to store the background image in.
Image img;
public BackgroundPanel()
{
// Loads the background image and stores in img object.
img = Toolkit.getDefaultToolkit().createImage("background.jpg");
}
public void paint(Graphics g)
{
// Draws the img to the BackgroundPanel.
g.drawImage(img, 0, 0, null);
}
}
For more information on painting:
You can have many java versions in your system.
I think you should add the java 8 in yours JREs installed or edit.
Take a look my screen:
If you click in edit (check your java 8 path):
Just remove .metadata from your eclipse workspace You can find it C:\Users\username\workspace
You can do it by giving margin or by positioning those elements absolutely.
For example
.button{
margin:0px auto; //it will center them
}
0px will be from top and bottom and auto will be from left and right.
pip is not give permission so can't do pip install.Try below command.
apt-get install python-virtualenv
import os
[val for sublist in [[os.path.join(i[0], j) for j in i[2]] for i in os.walk('./')] for val in sublist]
# Meta comment to ease selecting text
The outer most val for sublist in ...
loop flattens the list to be one dimensional. The j
loop collects a list of every file basename and joins it to the current path. Finally, the i
loop iterates over all directories and sub directories.
This example uses the hard-coded path ./
in the os.walk(...)
call, you can supplement any path string you like.
Note: os.path.expanduser
and/or os.path.expandvars
can be used for paths strings like ~/
Its easy to add in file basename tests and directoryname tests.
For Example, testing for *.jpg
files:
... for j in i[2] if j.endswith('.jpg')] ...
Additionally, excluding the .git
directory:
... for i in os.walk('./') if '.git' not in i[0].split('/')]
EDIT: chardet seems to be unmantained but most of the answer applies. Check https://pypi.org/project/charset-normalizer/ for an alternative
Correctly detecting the encoding all times is impossible.
(From chardet FAQ:)
However, some encodings are optimized for specific languages, and languages are not random. Some character sequences pop up all the time, while other sequences make no sense. A person fluent in English who opens a newspaper and finds “txzqJv 2!dasd0a QqdKjvz” will instantly recognize that that isn't English (even though it is composed entirely of English letters). By studying lots of “typical” text, a computer algorithm can simulate this kind of fluency and make an educated guess about a text's language.
There is the chardet library that uses that study to try to detect encoding. chardet is a port of the auto-detection code in Mozilla.
You can also use UnicodeDammit. It will try the following methods:
getView()
method create new View
or ViewGroup
for each row of Listview
or Spinner . You can define this View
or ViewGroup
in a Layout XML
file in res/layout
folder and can give the reference it to Adapter
class Object.
if you have 4 item in a Array passed to Adapter. getView()
method will create 4 View for 4 rows of Adaper.
LayoutInflater class has a Method inflate() whic create View Object from XML resource layout.
I would make a very simple VBScript file and call it using CScript to parse the command line parameters.
Something like the following saved in MessageBox.vbs
:
Set objArgs = WScript.Arguments
messageText = objArgs(0)
MsgBox messageText
Which you would call like:
cscript MessageBox.vbs "This will be shown in a popup."
MsgBox
reference if you are interested in going this route.
When you want to convert your code to result( executable, library or whatever ), there is 2 steps:
1) compile
2) link
In first step compiler should now about some things like sizeof objects that used by you, prototype of functions and maybe inheritance. on the other hand linker want to find implementation of functions and global variables in your code.
Now when you use ClassTwo
in File1.cpp
compiler know nothing about it and don't know how much memory should allocate for it or for example witch members it have or is it a class and enum or even a typedef of int, so compilation will be failed by the compiler. adding File2.cpp
solve the problem of linker that look for implementation but the compiler is still unhappy, because it know nothing about your type.
So remember, in compile phase you always work with just one file( and of course files that included by that one file ) and in link phase you need multiple files that contain implementations. and since C/C++ are statically typed and they allow their identifier to work for many purposes( definition, typedef, enum class, ... ) so you should always identify you identifier to the compiler and then use it and as a rule compiler should always know size of your variable!!
/*
Include this after bootstrap.css
Add a class of 'col-xs-offset-*' and
if you want to disable the offset at a larger size add in 'col-*-offset-0'
Examples:
All display sizes (xs,sm,md,lg) have an offset of 1
<div class="col-xs-11 col-xs-offset-1 col-sm-3">
xs has an offset of 1
<div class="col-xs-11 col-xs-offset-1 col-sm-offset-0 col-sm-3">
xs and sm have an offset of 1
<div class="col-xs-11 col-xs-offset-1 col-md-offset-0 col-sm-3">
xs, sm and md will have an offset of 1
<div class="col-xs-11 col-xs-offset-1 col-lg-offset-0 col-sm-3">
*/
.col-xs-offset-12 {
margin-left: 100%;
}
.col-xs-offset-11 {
margin-left: 91.66666666666666%;
}
.col-xs-offset-10 {
margin-left: 83.33333333333334%;
}
.col-xs-offset-9 {
margin-left: 75%;
}
.col-xs-offset-8 {
margin-left: 66.66666666666666%;
}
.col-xs-offset-7 {
margin-left: 58.333333333333336%;
}
.col-xs-offset-6 {
margin-left: 50%;
}
.col-xs-offset-5 {
margin-left: 41.66666666666667%;
}
.col-xs-offset-4 {
margin-left: 33.33333333333333%;
}
.col-xs-offset-3 {
margin-left: 25%;
}
.col-xs-offset-2 {
margin-left: 16.666666666666664%;
}
.col-xs-offset-1 {
margin-left: 8.333333333333332%;
}
.col-xs-offset-0 {
margin-left: 0;
}
/* Ensure that all of the zero offsets are available - recent SASS version did not include .col-sm-offset-0 */
@media (min-width: 768px) {
.col-sm-offset-0,
.col-md-offset-0,
.col-lg-offset-0 {
margin-left: 0;
}
}
if you provide a bad path or a broken link, if the compiler cannot find the image, the picture box would display an X icon on its body.
PictureBox picture = new PictureBox
{
Name = "pictureBox",
Size = new Size(100, 50),
Location = new Point(14, 17),
Image = Image.FromFile(@"c:\Images\test.jpg"),
SizeMode = PictureBoxSizeMode.CenterImage
};
p.Controls.Add(picture);
OR
PictureBox picture = new PictureBox
{
Name = "pictureBox",
Size = new Size(100, 50),
Location = new Point(14, 17),
ImageLocation = @"c:\Images\test.jpg",
SizeMode = PictureBoxSizeMode.CenterImage
};
p.Controls.Add(picture);
i'm not sure where you put images in your folder structure but you can find the path as bellow
picture.ImageLocation = Path.Combine(System.Windows.Forms.Application.StartupPath, "Resources\Images\1.jpg");
UPDATE:
Use glide:
dependencies {
implementation 'com.github.bumptech.glide:glide:4.0.0'
}
usage:
Glide.with(context).load(GIF_URI).into(new GlideDrawableImageViewTarget(IMAGE_VIEW));
Sorry for answering after 2-3 years. but you can hide activity of all system buttons. Just check this my answers How to disable virtual home button in any activity?.
I wanted to add this to @marczking's answer (Option 1) as a comment, but my lowly status on StackOverflow is preventing that.
I did a port of @marczking's answer to Objective C. Works like charm, thanks @marczking!
UIView+Border.h:
#import <UIKit/UIKit.h>
IB_DESIGNABLE
@interface UIView (Border)
-(void)setBorderColor:(UIColor *)color;
-(void)setBorderWidth:(CGFloat)width;
-(void)setCornerRadius:(CGFloat)radius;
@end
UIView+Border.m:
#import "UIView+Border.h"
@implementation UIView (Border)
// Note: cannot use synthesize in a Category
-(void)setBorderColor:(UIColor *)color
{
self.layer.borderColor = color.CGColor;
}
-(void)setBorderWidth:(CGFloat)width
{
self.layer.borderWidth = width;
}
-(void)setCornerRadius:(CGFloat)radius
{
self.layer.cornerRadius = radius;
self.layer.masksToBounds = radius > 0;
}
@end
In order to navigate to a different drive just use
cd /E/Study/Codes
It will solve your problem.
Just toggle each time it is called
this.boolValue = !this.boolValue;
If you need to conditionally apply inline styles (apply all or nothing) then this notation also works:
style={ someCondition ? { textAlign:'center', paddingTop: '50%'} : {}}
In case 'someCondition' not fulfilled then you pass empty object.
To import files from OS X Finder into Android Studio, just drag the relevant files to your resource folder.
Don't find a permanent config option for this, but this is the workaround I'm using
Since PostgreSQL 9.1 there is the convenient FOREACH
:
DO
$do$
DECLARE
m varchar[];
arr varchar[] := array[['key1','val1'],['key2','val2']];
BEGIN
FOREACH m SLICE 1 IN ARRAY arr
LOOP
RAISE NOTICE 'another_func(%,%)',m[1], m[2];
END LOOP;
END
$do$
Solution for older versions:
DO
$do$
DECLARE
arr varchar[] := '{{key1,val1},{key2,val2}}';
BEGIN
FOR i IN array_lower(arr, 1) .. array_upper(arr, 1)
LOOP
RAISE NOTICE 'another_func(%,%)',arr[i][1], arr[i][2];
END LOOP;
END
$do$
Also, there is no difference between varchar[]
and varchar[][]
for the PostgreSQL type system. I explain in more detail here.
The DO
statement requires at least PostgreSQL 9.0, and LANGUAGE plpgsql
is the default (so you can omit the declaration).
If you mean File.separator
and File.pathSeparator
then:
File.pathSeparator
is used to separate individual file paths in a list of file paths. Consider on windows, the PATH environment variable. You use a ;
to separate the file paths so on Windows File.pathSeparator
would be ;
.
File.separator
is either /
or \
that is used to split up the path to a specific file. For example on Windows it is \
or C:\Documents\Test
In CMake, you can add the following to your CMakelists
:
# install boost by apt-get method
include_directories(BEFORE SYSTEM "/usr/include")
# or install by building from src
# include_directories(BEFORE SYSTEM "/usr/local/include")
This method saved my serveral months. you can try it. By the way, as a temporary solution, you can rename directories you don't expect to find as below:
sudo mv /usr/local/include/boost /usr/local/include/boost_bak
Hopefully, it will help people who are in deep trouble like me.
Just use Analyze | Inspect Code
with appropriate inspection enabled (Unused declaration under Declaration redundancy group).
Using IntelliJ 11 CE you can now "Analyze | Run Inspection by Name ... | Unused declaration"
It's the same in terms of functionality and support. (most OS recognize both, most Search Engines recognize both)
For my everyday use, I choose .htm because it's shorter to type by 25%.
if using /bin/sh
you can use:
if [ <condition> ] && [ <condition> ]; then
...
fi
if using /bin/bash
you can use:
if [[ <condition> && <condition> ]]; then
...
fi
How about that?
function internalHandler(e) {
e.preventDefault(); // required in some browsers
e.returnValue = ""; // required in some browsers
return "Custom message to show to the user"; // only works in old browsers
}
if (window.addEventListener) {
window.addEventListener('beforeunload', internalHandler, true);
} else if (window.attachEvent) {
window.attachEvent('onbeforeunload', internalHandler);
}
You could use .find("is")
, it would return position of "is" in the string
or use .start() from re
>>> re.search("is", String).start()
2
Actually its match "is" from "This"
If you need to match per word, you should use \b
before and after "is", \b
is the word boundary.
>>> re.search(r"\bis\b", String).start()
5
>>>
for more info about python regular expressions, docs here
TIL This varies (a lot). Here are some results using gnu compiler (btw I also checked by compiling on machines, gnu g++ 5.4 from xenial is a hell of a lot faster than 4.6.3 from linaro on precise)
Intel i7 4700MQ xenial
short add: 0.822491
short sub: 0.832757
short mul: 1.007533
short div: 3.459642
long add: 0.824088
long sub: 0.867495
long mul: 1.017164
long div: 5.662498
long long add: 0.873705
long long sub: 0.873177
long long mul: 1.019648
long long div: 5.657374
float add: 1.137084
float sub: 1.140690
float mul: 1.410767
float div: 2.093982
double add: 1.139156
double sub: 1.146221
double mul: 1.405541
double div: 2.093173
Intel i3 2370M has similar results
short add: 1.369983
short sub: 1.235122
short mul: 1.345993
short div: 4.198790
long add: 1.224552
long sub: 1.223314
long mul: 1.346309
long div: 7.275912
long long add: 1.235526
long long sub: 1.223865
long long mul: 1.346409
long long div: 7.271491
float add: 1.507352
float sub: 1.506573
float mul: 2.006751
float div: 2.762262
double add: 1.507561
double sub: 1.506817
double mul: 1.843164
double div: 2.877484
Intel(R) Celeron(R) 2955U (Acer C720 Chromebook running xenial)
short add: 1.999639
short sub: 1.919501
short mul: 2.292759
short div: 7.801453
long add: 1.987842
long sub: 1.933746
long mul: 2.292715
long div: 12.797286
long long add: 1.920429
long long sub: 1.987339
long long mul: 2.292952
long long div: 12.795385
float add: 2.580141
float sub: 2.579344
float mul: 3.152459
float div: 4.716983
double add: 2.579279
double sub: 2.579290
double mul: 3.152649
double div: 4.691226
DigitalOcean 1GB Droplet Intel(R) Xeon(R) CPU E5-2630L v2 (running trusty)
short add: 1.094323
short sub: 1.095886
short mul: 1.356369
short div: 4.256722
long add: 1.111328
long sub: 1.079420
long mul: 1.356105
long div: 7.422517
long long add: 1.057854
long long sub: 1.099414
long long mul: 1.368913
long long div: 7.424180
float add: 1.516550
float sub: 1.544005
float mul: 1.879592
float div: 2.798318
double add: 1.534624
double sub: 1.533405
double mul: 1.866442
double div: 2.777649
AMD Opteron(tm) Processor 4122 (precise)
short add: 3.396932
short sub: 3.530665
short mul: 3.524118
short div: 15.226630
long add: 3.522978
long sub: 3.439746
long mul: 5.051004
long div: 15.125845
long long add: 4.008773
long long sub: 4.138124
long long mul: 5.090263
long long div: 14.769520
float add: 6.357209
float sub: 6.393084
float mul: 6.303037
float div: 17.541792
double add: 6.415921
double sub: 6.342832
double mul: 6.321899
double div: 15.362536
This uses code from http://pastebin.com/Kx8WGUfg as benchmark-pc.c
g++ -fpermissive -O3 -o benchmark-pc benchmark-pc.c
I've run multiple passes, but this seems to be the case that general numbers are the same.
One notable exception seems to be ALU mul vs FPU mul. Addition and subtraction seem trivially different.
Here is the above in chart form (click for full size, lower is faster and preferable):
https://gist.github.com/Lewiscowles1986/90191c59c9aedf3d08bf0b129065cccc
i7 4700MQ Linux Ubuntu Xenial 64-bit (all patches to 2018-03-13 applied) short add: 0.773049
short sub: 0.789793
short mul: 0.960152
short div: 3.273668
int add: 0.837695
int sub: 0.804066
int mul: 0.960840
int div: 3.281113
long add: 0.829946
long sub: 0.829168
long mul: 0.960717
long div: 5.363420
long long add: 0.828654
long long sub: 0.805897
long long mul: 0.964164
long long div: 5.359342
float add: 1.081649
float sub: 1.080351
float mul: 1.323401
float div: 1.984582
double add: 1.081079
double sub: 1.082572
double mul: 1.323857
double div: 1.968488
AMD Opteron(tm) Processor 4122 (precise, DreamHost shared-hosting)
short add: 1.235603
short sub: 1.235017
short mul: 1.280661
short div: 5.535520
int add: 1.233110
int sub: 1.232561
int mul: 1.280593
int div: 5.350998
long add: 1.281022
long sub: 1.251045
long mul: 1.834241
long div: 5.350325
long long add: 1.279738
long long sub: 1.249189
long long mul: 1.841852
long long div: 5.351960
float add: 2.307852
float sub: 2.305122
float mul: 2.298346
float div: 4.833562
double add: 2.305454
double sub: 2.307195
double mul: 2.302797
double div: 5.485736
Intel Xeon E5-2630L v2 @ 2.4GHz (Trusty 64-bit, DigitalOcean VPS)
short add: 1.040745
short sub: 0.998255
short mul: 1.240751
short div: 3.900671
int add: 1.054430
int sub: 1.000328
int mul: 1.250496
int div: 3.904415
long add: 0.995786
long sub: 1.021743
long mul: 1.335557
long div: 7.693886
long long add: 1.139643
long long sub: 1.103039
long long mul: 1.409939
long long div: 7.652080
float add: 1.572640
float sub: 1.532714
float mul: 1.864489
float div: 2.825330
double add: 1.535827
double sub: 1.535055
double mul: 1.881584
double div: 2.777245
Reflector and the File Disassembler add-in from Denis Bauer. It actually produces source projects from assemblies, where Reflector on its own only displays the disassembled source.
ADDED: My latest favourite is JetBrains' dotPeek.
If it's an ICollection
then you won't have a RemoveAll
method. Here's an extension method that will do it:
public static void RemoveAll<T>(this ICollection<T> source,
Func<T, bool> predicate)
{
if (source == null)
throw new ArgumentNullException("source", "source is null.");
if (predicate == null)
throw new ArgumentNullException("predicate", "predicate is null.");
source.Where(predicate).ToList().ForEach(e => source.Remove(e));
}
Based on: http://phejndorf.wordpress.com/2011/03/09/a-removeall-extension-for-the-collection-class/
Python3.x
The best aproach I could reach with my knowledge was this.
Note that this code treat set() too.
This approach is generic just needing the extension of class (in the second example).
Note that I'm just doing it to files, but it's easy to modify the behavior to your taste.
However this is a CoDec.
With a little more work you can construct your class in other ways. I assume a default constructor to instance it, then I update the class dict.
import json
import collections
class JsonClassSerializable(json.JSONEncoder):
REGISTERED_CLASS = {}
def register(ctype):
JsonClassSerializable.REGISTERED_CLASS[ctype.__name__] = ctype
def default(self, obj):
if isinstance(obj, collections.Set):
return dict(_set_object=list(obj))
if isinstance(obj, JsonClassSerializable):
jclass = {}
jclass["name"] = type(obj).__name__
jclass["dict"] = obj.__dict__
return dict(_class_object=jclass)
else:
return json.JSONEncoder.default(self, obj)
def json_to_class(self, dct):
if '_set_object' in dct:
return set(dct['_set_object'])
elif '_class_object' in dct:
cclass = dct['_class_object']
cclass_name = cclass["name"]
if cclass_name not in self.REGISTERED_CLASS:
raise RuntimeError(
"Class {} not registered in JSON Parser"
.format(cclass["name"])
)
instance = self.REGISTERED_CLASS[cclass_name]()
instance.__dict__ = cclass["dict"]
return instance
return dct
def encode_(self, file):
with open(file, 'w') as outfile:
json.dump(
self.__dict__, outfile,
cls=JsonClassSerializable,
indent=4,
sort_keys=True
)
def decode_(self, file):
try:
with open(file, 'r') as infile:
self.__dict__ = json.load(
infile,
object_hook=self.json_to_class
)
except FileNotFoundError:
print("Persistence load failed "
"'{}' do not exists".format(file)
)
class C(JsonClassSerializable):
def __init__(self):
self.mill = "s"
JsonClassSerializable.register(C)
class B(JsonClassSerializable):
def __init__(self):
self.a = 1230
self.c = C()
JsonClassSerializable.register(B)
class A(JsonClassSerializable):
def __init__(self):
self.a = 1
self.b = {1, 2}
self.c = B()
JsonClassSerializable.register(A)
A().encode_("test")
b = A()
b.decode_("test")
print(b.a)
print(b.b)
print(b.c.a)
Edit
With some more of research I found a way to generalize without the need of the SUPERCLASS register method call, using a metaclass
import json
import collections
REGISTERED_CLASS = {}
class MetaSerializable(type):
def __call__(cls, *args, **kwargs):
if cls.__name__ not in REGISTERED_CLASS:
REGISTERED_CLASS[cls.__name__] = cls
return super(MetaSerializable, cls).__call__(*args, **kwargs)
class JsonClassSerializable(json.JSONEncoder, metaclass=MetaSerializable):
def default(self, obj):
if isinstance(obj, collections.Set):
return dict(_set_object=list(obj))
if isinstance(obj, JsonClassSerializable):
jclass = {}
jclass["name"] = type(obj).__name__
jclass["dict"] = obj.__dict__
return dict(_class_object=jclass)
else:
return json.JSONEncoder.default(self, obj)
def json_to_class(self, dct):
if '_set_object' in dct:
return set(dct['_set_object'])
elif '_class_object' in dct:
cclass = dct['_class_object']
cclass_name = cclass["name"]
if cclass_name not in REGISTERED_CLASS:
raise RuntimeError(
"Class {} not registered in JSON Parser"
.format(cclass["name"])
)
instance = REGISTERED_CLASS[cclass_name]()
instance.__dict__ = cclass["dict"]
return instance
return dct
def encode_(self, file):
with open(file, 'w') as outfile:
json.dump(
self.__dict__, outfile,
cls=JsonClassSerializable,
indent=4,
sort_keys=True
)
def decode_(self, file):
try:
with open(file, 'r') as infile:
self.__dict__ = json.load(
infile,
object_hook=self.json_to_class
)
except FileNotFoundError:
print("Persistence load failed "
"'{}' do not exists".format(file)
)
class C(JsonClassSerializable):
def __init__(self):
self.mill = "s"
class B(JsonClassSerializable):
def __init__(self):
self.a = 1230
self.c = C()
class A(JsonClassSerializable):
def __init__(self):
self.a = 1
self.b = {1, 2}
self.c = B()
A().encode_("test")
b = A()
b.decode_("test")
print(b.a)
# 1
print(b.b)
# {1, 2}
print(b.c.a)
# 1230
print(b.c.c.mill)
# s
I'm not sure if returning the address of the thing pointed by the iterator is needed. All you need is the pointer itself. You will see STL's iterator class itself implementing the use of _Ptr for this purpose. So, just do:
return iterator._Ptr;
curl
sends POST requests with the default content type of application/x-www-form-urlencoded
. If you want to send a JSON request, you will have to specify the correct content type header:
$ curl -vX POST http://server/api/v1/places.json -d @testplace.json \
--header "Content-Type: application/json"
But that will only work if the server accepts json input. The .json
at the end of the url may only indicate that the output is json, it doesn't necessarily mean that it also will handle json input. The API documentation should give you a hint on whether it does or not.
The reason you get a 401
and not some other error is probably because the server can't extract the auth_token
from your request.
We have found that adding the Apptentive cocoa pod to an existing Xcode project may potentially not include some of our required frameworks.
Check your linker flags:
Target > Build Settings > Other Linker Flags
You should see -lApptentiveConnect
listed as a linker flag:
... -ObjC -lApptentiveConnect ...
You should also see our required Frameworks listed:
UIKit
-ObjC -lApptentiveConnect -framework Accelerate -framework CoreData -framework CoreGraphics -framework CoreText -framework Foundation -framework QuartzCore -framework SystemConfiguration -framework UIKit -framework CoreTelephony -framework StoreKit
<context:component-scan base-package="" />
tells Spring to scan those packages for Annotations.
<mvc:annotation-driven>
registers a RequestMappingHanderMapping, a RequestMappingHandlerAdapter, and an ExceptionHandlerExceptionResolver to support the annotated controller methods like @RequestMapping, @ExceptionHandler, etc. that come with MVC.
This also enables a ConversionService that supports Annotation driven formatting of outputs as well as Annotation driven validation for inputs. It also enables support for @ResponseBody which you can use to return JSON data.
You can accomplish the same things using Java-based Configuration using @ComponentScan(basePackages={"...", "..."} and @EnableWebMvc in a @Configuration class.
Check out the 3.1 documentation to learn more.
http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/mvc.html#mvc-config
The answer by @Federico Giorgi was a very good answer. It helpt me. Therefore, I did the following, in order to produce multiple lines in the same plot from the data of a single dataset, I used a for loop. Legend can be added as well.
plot(tab[,1],type="b",col="red",lty=1,lwd=2, ylim=c( min( tab, na.rm=T ),max( tab, na.rm=T ) ) )
for( i in 1:length( tab )) { [enter image description here][1]
lines(tab[,i],type="b",col=i,lty=1,lwd=2)
}
axis(1,at=c(1:nrow(tab)),labels=rownames(tab))
First, read this: https://httpd.apache.org/docs/current/howto/htaccess.html#when
Then read my post here: https://stackoverflow.com/a/59868481/10664600
sudo vim /etc/httpd/conf/httpd.conf
Directly calling a URL to get an image may concern with major security issues.
You need to ensure that you have sufficient rights to access that resource.
However You can use ByteOutputStream
to read image file. This is an example (Its just an example, you need to do necessary changes as per your requirement.)
ByteArrayOutputStream bis = new ByteArrayOutputStream();
InputStream is = null;
try {
is = url.openStream ();
byte[] bytebuff = new byte[4096];
int n;
while ( (n = is.read(bytebuff)) > 0 ) {
bis.write(bytebuff, 0, n);
}
}
Your first example,
@collection.each do |item|
# do whatever
end
is more idiomatic. While Ruby supports looping constructs like for
and while
, the block syntax is generally preferred.
Another subtle difference is that any variable you declare within a for
loop will be available outside the loop, whereas those within an iterator block are effectively private.
Add-Content is default ASCII and add new line however Add-Content brings locked files issues too.
It has been asked in the past, apparently it costs a lot to mobile browsers, so it's been disabled.
Check this comment by @PaulIrish:
Fixed-backgrounds have huge repaint cost and decimate scrolling performance, which is, I believe, why it was disabled.
you can see workarounds to this in this posts:
background.xml in drawable folder.
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#FFFFFF"/>
<stroke
android:width="3dp"
android:color="#0FECFF" />
//specify gradient
<gradient
android:startColor="#ffffffff"
android:endColor="#110000FF"
android:angle="90"/>
<padding
android:left="5dp"
android:top="5dp"
android:right="5dp"
android:bottom="5dp"/>
<corners
android:bottomRightRadius="7dp"
android:bottomLeftRadius="7dp"
android:topLeftRadius="7dp"
android:topRightRadius="7dp"/>
</shape>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="210dp"
android:orientation="vertical"
android:layout_marginBottom="10dp"
android:background="@drawable/background">
let button: UIButton = UIButton()
button.setImage(UIImage(named:"imagename"), for: .normal)
button.addTarget(self, action:#selector(YourClassName.backAction(_sender:)), for: .touchUpInside)
button.frame = CGRect.init(x: 5, y: 100, width: 45, height: 45)
view.addSubview(button)
@objc public func backAction(_sender: UIButton) {
}
For anyone looking to do this in vb (as I was and couldn't find anything)
From c In db.Company
Select c.Name Group By Name Into Group
Where Group.Count > 1
no need to do a replacement. the regex will give you what u wanted directly:
"(?<=_)[^_]*\.jpg"
tested with grep:
echo "3.04_somename.jpg"|grep -oP "(?<=_)[^_]*\.jpg"
somename.jpg
The previous answers are all good, but they all show origin/master. These days, following the best practices, I rarely work directly on a master branch, let alone from origin repo.
So if you are like me who work in a branch, here are tips:
Or more simply, just use HEAD:
import yaml
data = dict(
A = 'a',
B = dict(
C = 'c',
D = 'd',
E = 'e',
)
)
with open('data.yml', 'w') as outfile:
yaml.dump(data, outfile, default_flow_style=False)
The default_flow_style=False
parameter is necessary to produce the format you want (flow style), otherwise for nested collections it produces block style:
A: a
B: {C: c, D: d, E: e}
>
(greater-than sign) is a CSS Combinator.
A combinator is something that explains the relationship between the selectors.
A CSS selector can contain more than one simple selector. Between the simple selectors, we can include a combinator.
There are four different combinators in CSS3:
Note: <
is not valid in CSS selectors.
For example:
<!DOCTYPE html>
<html>
<head>
<style>
div > p {
background-color: yellow;
}
</style>
</head>
<body>
<div>
<p>Paragraph 1 in the div.</p>
<p>Paragraph 2 in the div.</p>
<span><p>Paragraph 3 in the div.</p></span> <!-- not Child but Descendant -->
</div>
<p>Paragraph 4. Not in a div.</p>
<p>Paragraph 5. Not in a div.</p>
</body>
</html>
Output:
However, avpicture_get_size is defined.
No, as the header (<libavcodec/avcodec.h>
) just declares it.
The definition is in the library itself.
So you might like to add the linker option to link libavcodec
when invoking gcc:
-lavcodec
Please also note that libraries need to be specified on the command line after the files needing them:
gcc -I$HOME/ffmpeg/include program.c -lavcodec
Not like this:
gcc -lavcodec -I$HOME/ffmpeg/include program.c
Referring to Wyzard's comment, the complete command might look like this:
gcc -I$HOME/ffmpeg/include program.c -L$HOME/ffmpeg/lib -lavcodec
For libraries not stored in the linkers standard location the option -L
specifies an additional search path to lookup libraries specified using the -l
option, that is libavcodec.x.y.z
in this case.
For a detailed reference on GCC's linker option, please read here.
Though I'm coming in late, what worked for me was to install transform-async-generator and transform-runtime plugin like so:
npm i babel-plugin-transform-async-to-generator babel-plugin-transform-runtime --save-dev
the package.json
would be like this:
"devDependencies": {
"babel-plugin-transform-async-to-generator": "6.24.1",
"babel-plugin-transform-runtime": "6.23.0"
}
create .babelrc
file and write this:
{
"plugins": ["transform-async-to-generator",
["transform-runtime", {
"polyfill": false,
"regenerator": true
}]
]
}
and then happy coding with async/await
Here's some more detailed information on what Client, Resource, and Session are all about.
Client:
Here's an example of client-level access to an S3 bucket's objects (at most 1000**):
import boto3
client = boto3.client('s3')
response = client.list_objects_v2(Bucket='mybucket')
for content in response['Contents']:
obj_dict = client.get_object(Bucket='mybucket', Key=content['Key'])
print(content['Key'], obj_dict['LastModified'])
** you would have to use a paginator, or implement your own loop, calling list_objects() repeatedly with a continuation marker if there were more than 1000.
Resource:
Here's the equivalent example using resource-level access to an S3 bucket's objects (all):
import boto3
s3 = boto3.resource('s3')
bucket = s3.Bucket('mybucket')
for obj in bucket.objects.all():
print(obj.key, obj.last_modified)
Note that in this case you do not have to make a second API call to get the objects; they're available to you as a collection on the bucket. These collections of subresources are lazily-loaded.
You can see that the Resource
version of the code is much simpler, more compact, and has more capability (it does pagination for you). The Client
version of the code would actually be more complicated than shown above if you wanted to include pagination.
Session:
A useful resource to learn more about these boto3 concepts is the introductory re:Invent video.
Two issues jump out:
Your getData
never returns anything, so its promise (async
functions always return a promise) will resolve with undefined
when it resolves
The error message clearly shows you're trying to directly render the promise getData
returns, rather than waiting for it to resolve and then rendering the resolution
Addressing #1: getData
should return the result of calling json
:
async getData(){
const res = await axios('/data');
return await res.json();
}
Addressig #2: We'd have to see more of your code, but fundamentally, you can't do
<SomeElement>{getData()}</SomeElement>
...because that doesn't wait for the resolution. You'd need instead to use getData
to set state:
this.getData().then(data => this.setState({data}))
.catch(err => { /*...handle the error...*/});
...and use that state when rendering:
<SomeElement>{this.state.data}</SomeElement>
Update: Now that you've shown us your code, you'd need to do something like this:
class App extends React.Component{
async getData() {
const res = await axios('/data');
return await res.json(); // (Or whatever)
}
constructor(...args) {
super(...args);
this.state = {data: null};
}
componentDidMount() {
if (!this.state.data) {
this.getData().then(data => this.setState({data}))
.catch(err => { /*...handle the error...*/});
}
}
render() {
return (
<div>
{this.state.data ? <em>Loading...</em> : this.state.data}
</div>
);
}
}
Futher update: You've indicated a preference for using await
in componentDidMount
rather than then
and catch
. You'd do that by nesting an async
IIFE function within it and ensuring that function can't throw. (componentDidMount
itself can't be async
, nothing will consume that promise.) E.g.:
class App extends React.Component{
async getData() {
const res = await axios('/data');
return await res.json(); // (Or whatever)
}
constructor(...args) {
super(...args);
this.state = {data: null};
}
componentDidMount() {
if (!this.state.data) {
(async () => {
try {
this.setState({data: await this.getData()});
} catch (e) {
//...handle the error...
}
})();
}
}
render() {
return (
<div>
{this.state.data ? <em>Loading...</em> : this.state.data}
</div>
);
}
}
If you are exporting another class in that module, make sure that it is not in between @Component
and your ClassComponent
. For example:
@Component({ ... })
export class ExampleClass{}
export class ComponentClass{} --> this will give this error.
FIX:
export class ExampleClass{}
@Component ({ ... })
export class ComponentClass{}
A reason can be duplicated libraries after importing from Eclipse IDE.
dependencies {
compile 'com.github.japgolly.android:svg-android:2.0.5'
compile 'com.google.android.gms:play-services:+'
compile 'com.android.support:appcompat-v7:21.0.3'
compile files('libs/androidannotations-api-2.7.1.jar')
compile files('libs/androidasync-2.1.2.jar')
//compile files('libs/google-play-services.jar')
compile files('libs/universal-image-loader-1.8.2.jar')}
I had the same problem, after comment:
//compile files('libs/google-play-services.jar')
The app get no errors.
Something along these lines ....
//default icon, custom title
int n = JOptionPane.showConfirmDialog(null,"Would you like green eggs and ham?","An Inane Question",JOptionPane.YES_NO_OPTION);
String result = "?";
switch (n) {
case JOptionPane.YES_OPTION:
result = "YES";
break;
case JOptionPane.NO_OPTION:
result = "NO";
break;
default:
;
}
System.out.println("Replace? " + result);
you may also want to look at DialogDemo
I come across this problem when I tried to convert to Australian date format in excel. I split the cell with delimiter and used the following code from split cells then altered the issue areas.
=date(dd,mm,yy)
Please check this. https://code.google.com/p/android/issues/detail?id=82850
I faced the same issue. Could notice that the "adb integration" was disabled. Please enable it at your IDE (Tools | Android)
You can use a window MAX() like this:
SELECT
*,
max_date = MAX(date) OVER (PARTITION BY group)
FROM table
to get max dates per group
alongside other data:
group date cash checks max_date
----- -------- ---- ------ --------
1 1/1/2013 0 0 1/3/2013
2 1/1/2013 0 800 1/1/2013
1 1/3/2013 0 700 1/3/2013
3 1/1/2013 0 600 1/5/2013
1 1/2/2013 0 400 1/3/2013
3 1/5/2013 0 200 1/5/2013
Using the above output as a derived table, you can then get only rows where date
matches max_date
:
SELECT
group,
date,
checks
FROM (
SELECT
*,
max_date = MAX(date) OVER (PARTITION BY group)
FROM table
) AS s
WHERE date = max_date
;
to get the desired result.
Basically, this is similar to @Twelfth's suggestion but avoids a join and may thus be more efficient.
You can try the method at SQL Fiddle.
Just add xmlns:tools="http://schemas.android.com/tools"
to your manifest tag, and then you need to add tools:replace="android:icon"
before android:icon="@mipmap/ic_launcher"
.
pygame
is not distributed via pip
. See this link which provides windows binaries ready for installation.
Finally, use these commands to install pygame wheel with pip
Python 2 (usually called pip)
pip install file.whl
Python 3 (usually called pip3)
pip3 install file.whl
Another tutorial for installing pygame for windows can be found here. Although the instructions are for 64bit windows, it can still be applied to 32bit
library(matrixStats)
> data <- rbind(c("M", "F", "M"), c("Student", "Analyst", "Analyst"))
> rowCounts(data, value = 'M') # output = 2 0
> rowCounts(data, value = 'F') # output = 1 0
Just thinking off the top of my head, you could do this:
public string[] Randomize(string[] input)
{
List<string> inputList = input.ToList();
string[] output = new string[input.Length];
Random randomizer = new Random();
int i = 0;
while (inputList.Count > 0)
{
int index = r.Next(inputList.Count);
output[i++] = inputList[index];
inputList.RemoveAt(index);
}
return (output);
}
All you'd need in your case is:
return expression;
The reason why is that the expression itself evaluates to a boolean value of true
or false
, so it's redundant to have an if
block (or even a ?:
operator).
Google used to recommend putting it just before the </body>
tag, because the original method they provided for loading ga.js
was blocking. The newer async syntax, though, can safely be put in the head with minimal blockage, so the current recommendation is just before the </head>
tag.
<head>
will add a little latency; in the footer will reduce the number of pageviews recorded at some small margin. It's a tradeoff. ga.js
is heavily cached and present on a large percentage of sites across the web, so its often served from the cache, reducing latency to almost nil.
As a matter of personal preference, I like to include it in the <head>
, but its really a matter of preference.
The approach of subclassing has also been used by the BARACUS framework. From my point of view subclassing Application was intended to work with the lifecycles of Android; this is what any Application Container does. Instead of having globals then, I register beans to this context an let them beeing injected into any class manageable by the context. Every injected bean instance actually is a singleton.
Why do manual work if you can have so much more?
No for the moment.
I doubt it will be possible for the future for ActiveX support will be discontinued in near future (as MS stated).
Look here about HTML Object tag, but not anything will be accepted. You should try.
Sometimes it is not eligible to set height to pixel values.
However, it is possible to show vertical scrollbar through setting height of div to 100%
and overflow
to auto
.
Let me show an example:
<div id="content" style="height: 100%; overflow: auto">
<p>some text</p>
<ul>
<li>text</li>
.....
<li>text</li>
</div>
Suppose we want to pass three values(u1,u2,u3) from say 'show.jsp' to another page say 'display.jsp' Make three hidden text boxes and a button that is click automatically(using javascript). //Code to written in 'show.jsp'
<body>
<form action="display.jsp" method="post">
<input type="hidden" name="u1" value="<%=u1%>"/>
<input type="hidden" name="u2" value="<%=u2%>" />
<input type="hidden" name="u3" value="<%=u3%>" />
<button type="hidden" id="qq" value="Login" style="display: none;"></button>
</form>
<script type="text/javascript">
document.getElementById("qq").click();
</script>
</body>
// Code to be written in 'display.jsp'
<% String u1 = request.getParameter("u1").toString();
String u2 = request.getParameter("u2").toString();
String u3 = request.getParameter("u3").toString();
%>
If you want to use these variables of servlets in javascript then simply write
<script type="text/javascript">
var a=<%=u1%>;
</script>
Hope it helps :)
Try this script
<script language="JavaScript">
function fullScreen(theURL) {
window.open(theURL, '', 'fullscreen=yes, scrollbars=auto' );
}
</script>
For calling from script use this code,
window.fullScreen('fullscreen.jsp');
or with hyperlink use this
<a href="javascript:void(0);" onclick="fullScreen('fullscreen.jsp');">
Open in Full Screen Window</a>
I am using the following code in one of my current projects where i download data from the internet. It is all inside my activity class.
private class GetData extends AsyncTask<String, Void, JSONObject> {
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(Calendar.this,
"", "");
}
@Override
protected JSONObject doInBackground(String... params) {
String response;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse responce = httpclient.execute(httppost);
HttpEntity httpEntity = responce.getEntity();
response = EntityUtils.toString(httpEntity);
Log.d("response is", response);
return new JSONObject(response);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(JSONObject result)
{
super.onPostExecute(result);
progressDialog.dismiss();
if(result != null)
{
try
{
JSONObject jobj = result.getJSONObject("result");
String status = jobj.getString("status");
if(status.equals("true"))
{
JSONArray array = jobj.getJSONArray("data");
for(int x = 0; x < array.length(); x++)
{
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", array.getJSONObject(x).getString("name"));
map.put("date", array.getJSONObject(x).getString("date"));
map.put("description", array.getJSONObject(x).getString("description"));
list.add(map);
}
CalendarAdapter adapter = new CalendarAdapter(Calendar.this, list);
list_of_calendar.setAdapter(adapter);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
Toast.makeText(Calendar.this, "Network Problem", Toast.LENGTH_LONG).show();
}
}
}
and execute it in OnCreate Method like new GetData().execute();
where Calendar is my calendarActivity and i have also created a CalendarAdapter to set these values to a list view.
You'll want something like this:
$("#next").click(function(){
var currentElement = currentElement.next();
$('html, body').animate({scrollLeft: $(currentElement).offset().left}, 800);
return false;
});
I believe this should work, it's adopted from a scrollTop
function.
Use:
$('#example').dataTable({
aLengthMenu: [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
iDisplayLength: -1
});
Or if using 1.10+
$('#example').dataTable({
paging: false
});
The option you should use is iDisplayLength:
$('#adminProducts').dataTable({
'iDisplayLength': 100
});
$('#table').DataTable({
"lengthMenu": [ [5, 10, 25, 50, -1], [5, 10, 25, 50, "All"] ]
});
It will Load by default all entries.
$('#example').dataTable({
aLengthMenu: [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
iDisplayLength: -1
});
Or if using 1.10+
$('#example').dataTable({
paging: false
});
If you want to load by default 25 not all do this.
$('#example').dataTable({
aLengthMenu: [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
});
This is a simple way to access a component's methods from other component
// This is external shared (reusable) component, so you can call its methods from other components
export default {
name: 'SharedBase',
methods: {
fetchLocalData: function(module, page){
// .....fetches some data
return { jsonData }
}
}
}
// This is your component where you can call SharedBased component's method(s)
import SharedBase from '[your path to component]';
var sections = [];
export default {
name: 'History',
created: function(){
this.sections = SharedBase.methods['fetchLocalData']('intro', 'history');
}
}
How do I loop through rows with a data reader in C#?
IDataReader.Read()
advances the reader to the next row in the resultset.
while(reader.Read()){
/* do whatever you'd like to do for each row. */
}
So, for each iteration of your loop, you'd do another loop, 0 to reader.FieldCount
, and call reader.GetValue(i)
for each field.
The bigger question is what kind of structure do you want to use to hold that data?
Use single quotes, like:
myPath=~/'my dir'
cd $myPath
I Had the same issue on a service running on IIS 7 the service connects to multiple suppliers servers (some SSL some not) when adding a new one of these (this new supplier was TLS 1.2) I would get the error after a few requests were made to the original servers (SSL).
To confirm this I simply logged the System.Net.ServicePointManager.SecurityProtocol
before each request to each supplier.
Low and behold after restarting the service (or restarting the application pool) I would get the output Ssl3, Tls
but after a few requests to the original supplier servers this changed to Ssl3
and requests to the TLS service gave the error.
To fix I simply did what user369142 suggested. Before each request to the new server:
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;
and no more errors.
PhpStorm supports all the features of WebStorm but some are not bundled so you might need to install the corresponding plugin for some framework via Settings > Plugins > Install JetBrains Plugin.
In the latest Mac OS You can use shift
+ home
or shift
+ end
You need element.scrollHeight. Compare it with $(element).height()
.
I've tried every way that was suggested but all of them have their own problems.
The best solution in my opinion would be to use a frame layout like below:
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
.... />
<View
android:id="@+id/invisible_click_watcher"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true" />
</FrameLayout>
and then adding the DatePickerDialog code which was beautifully written in @Android's answer.
//assuming b is BOOL. ternary operator helps us in any language.
NSLog(@"result is :%@",((b==YES)?@"YES":@"NO"));
this is pretty easy thing, but people's answers are confusing and complex at the same time.
let me show you how you can set global variable in your express
app. So you can access it from any route as needed.
Let's say you want set a global variable from your main /
route
router.get('/', (req, res, next) => {
req.app.locals.somethingNew = "Hi setting new global var";
});
So you'll get req.app from all the routes. and then you'll have to use the locals
to set global data into. like above show you're all set. now
I will show you how to use that data
router.get('/register', (req, res, next) => {
console.log(req.app.locals.somethingNew);
});
Like above from register
route you're accessing the data has been set earlier.
This is how you can get this thing working!
For arbitaray range of month numbers
month_integer=range(0,100)
map(lambda x: calendar.month_name[x%12+start],month_integer)
will yield correct list. Adjust start
-parameter from where January begins in the month-integer list.
I did it like this in my Jtable its autorefreshing after 300 ms;
DefaultTableModel tableModel = new DefaultTableModel(){
public boolean isCellEditable(int nRow, int nCol) {
return false;
}
};
JTable table = new JTable();
Timer t = new Timer(300, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
addColumns();
remakeData(set);
table.setModel(model);
}
});
t.start();
private void addColumns() {
model.setColumnCount(0);
model.addColumn("NAME");
model.addColumn("EMAIL");}
private void remakeData(CollectionType< Objects > name) {
model.setRowCount(0);
for (CollectionType Objects : name){
String n = Object.getName();
String e = Object.getEmail();
model.insertRow(model.getRowCount(),new Object[] { n,e });
}}
I doubt it will do good with large number of objects like over 500, only other way is to implement TableModelListener in your class, but i did not understand how to use it well. look at http://download.oracle.com/javase/tutorial/uiswing/components/table.html#modelchange
Simple way is to reset the index of the DataFrame prior to filtering:
df_reset = df.reset_index()
df_reset[df_reset['BoolCol']].index.tolist()
Bit hacky, but it's quick!
To expand on Jon Skeets answer the code for this in .Net 4
is:
string myCommaSeperatedString = string.Join(",",ls);
Try to use limit in your query. It's because of full disk as said by @Monsters X.
I have also faced this problem and solved by limit in query, because the thousands of records were there. Now working good :)
Seriously, question exists five years and no nice facade?
function is_dir(path) {
try {
var stat = fs.lstatSync(path);
return stat.isDirectory();
} catch (e) {
// lstatSync throws an error if path doesn't exist
return false;
}
}
When learning algorithms, the programming language (Java) should not be considered in deciding the representation. Each problem could benefit from a unique representation, and moreover designing it can add a bit of learning. Solve the problem first without relying on a particular language, then the representation for any particular language will flow naturally.
Of course, general representations and libraries are useful in real-world applications. But some of them could benefit from some customization as well. Use the other answers to know the different techniques available, but consider customization when appropriate.
Noneof the answers worked for me, I was getting "'HttpRequestBase' does not contain a definition for 'Query'", but this did work:
HttpContext.Current.Request.QueryString["index"]
I know that's an old one question, but its high in the search results.
If anyone wants timestamp conversion directly to a DateTime object, there's a simple one-liner:
$timestamp = 1299446702;
$date = DateTime::createFromFormat('U', $timestamp);
Following @sromero comment, timezone parameter (the 3rd param in DateTime::createFromFormat()) is ignored when unix timestamp is passed, so the below code is unnecessary.
$date = DateTime::createFromFormat('U', $timestamp, new DateTimeZone('UTC'); // not needed, 3rd parameter is ignored
You may check PHP's manual for DateTime::createFromFormat for more info and options.
This is not my work (well, I modified it slightly from the example), and it's late to the game, but this works on Server 2003 for me;
@echo off
set daysofweek=Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday
for /F "skip=2 tokens=2-4 delims=," %%A in ('WMIC Path Win32_LocalTime Get DayOfWeek /Format:csv') do set daynumber=%%A
for /F "tokens=%daynumber% delims=," %%B in ("%daysofweek%") do set day=%%B
Citation: TechSupportForum
For sequence diagrams you can also try Trace Modeler. It's not free but it has a great interface, very friendly and productive. You can use it on any platform.
Just remove all views of your layout Manager before notify. like:
myLayoutmanager.removeAllViews();
The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:
ffmpeg -i input.mov -qscale 0 output.mp4
Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0
):
ffmpeg -i input.mov -q:v 0 output.mp4
If you need to pass it to another app, you can do something like:
php --ini | grep Loaded | cut -d" " -f12
returns the path only. php -c $(php --ini | grep Loaded | cut -d" " -f12)
will pass in the config file (useful for fpm
)
I know this is an old question but I recently faced a similar issue which couldn't be solved by this way, as I had to return an empty array of a specific type.
I had
return [];
where []
was Criminal[]
type.
Neither return: Criminal[] [];
nor return []: Criminal[];
worked for me.
At first glance I solved it by creating a typed variable (as you correctly reported) just before returning it, but (I don't know how JavaScript engines work) it may create overhead and it's less readable.
For thoroughness I'll report this solution in my answer too:
let temp: Criminal[] = [];
return temp;
Eventually I found TypeScript type casting, which allowed me to solve the problem in a more concise and readable (and maybe efficient) way:
return <Criminal[]>[];
Hope this will help future readers!
android:layout_weight=".YOURVALUE" is best way to implement in percentage
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/logTextBox"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight=".20"
android:maxLines="500"
android:scrollbars="vertical"
android:singleLine="false"
android:text="@string/logText" >
</TextView>
</LinearLayout>
One hackish way to define an exit
method in context:
class Bar; def exit; end; end
This works because exit
in the initializer will be resolved as self.exit
1. In addition, this approach allows using the object after it has been created, as in: b = B.new
.
But really, one shouldn't be doing this: don't have exit
(or even puts
) there to begin with.
(And why is there an "infinite" loop and/or user input in an intiailizer? This entire problem is primarily the result of poorly structured code.)
1 Remember Kernel#exit is only a method. Since Kernel is included in every Object, then it's merely the case that exit
normally resolves to Object#exit
. However, this can be changed by introducing an overridden method as shown - nothing fancy.
I would heartily recommend relative URLs for pointing bits of the same site to other bits of the same site.
Don't forget that a change to HTTPS - even if in the same site - is going to need an absolute URL.
The cause for me was a function name that began with same characters as a type:
@IBOutlet weak var tableView: CustomTableView!
and in the implementation I had a function beginning with CustomTableView
func CustomTableView(tableView: CustomTableView, dataForRow row: Int) -> NSData {...}
The fix was to change the function signature so that it didn't begin with the same characters as the type (CustomTableView), e.g.:
func dataForRow(row: Int, tableView: CustomTableView) -> NSData {...}
This was a very misleading error message for the actual cause in my case.
I used to use the following from CSS-Tricks:
.transparent_class {
/* IE 8 */
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";
/* IE 5-7 */
filter: alpha(opacity=50);
/* Netscape */
-moz-opacity: 0.5;
/* Safari 1.x */
-khtml-opacity: 0.5;
/* Good browsers */
opacity: 0.5;
}
However, a better solution is to use the Opacity Compass mixin, all you need to do is to @include opacity(0.1);
and it will take care of any cross-browser issues for you. You can find an example here.
Following is for fetching even number:: Select * from MEN where Men_ID%2=0;
Following is for fetching odd number:: Select * from MEN where Men_ID%2!=0;
Here MEN is your table_name Men_ID is the column in MEN Table.
Your script is timing out. Take a look at the set_time_limit() function to up the execution time. Or profile the script to make it run faster :)
The functions getElementById
and getElementsByClassName
are very specific, while querySelector
and querySelectorAll
are more elaborate. My guess is that they will actually have a worse performance.
Also, you need to check for the support of each function in the browsers you are targetting. The newer it is, the higher probability of lack of support or the function being "buggy".
List<tblstatu> status = new List<tblstatu>();_x000D_
status = psobj.getstatus();_x000D_
model.statuslist = status;_x000D_
model.statusid = status.Select(x => new SelectListItem_x000D_
{_x000D_
Value = x.StatusId.ToString(),_x000D_
Text = x.StatusName_x000D_
});_x000D_
_x000D_
_x000D_
@Html.DropDownListFor(m => m.status_id, Model.statusid, "Select", new { @class = "form-control input-xlarge required", @type = "text", @autocomplete = "off" })
_x000D_
$("div[id^=" + controlid + "]")
will return all the controls with the same name but you need to ensure that the text should not present in any of the controls
If I understand what you're asking, this should do the trick:
// the more standards compliant browsers (mozilla/netscape/opera/IE7) use
// window.innerWidth and window.innerHeight
var windowHeight;
if (typeof window.innerWidth != 'undefined')
{
windowHeight = window.innerHeight;
}
// IE6 in standards compliant mode (i.e. with a valid doctype as the first
// line in the document)
else if (typeof document.documentElement != 'undefined'
&& typeof document.documentElement.clientWidth != 'undefined'
&& document.documentElement.clientWidth != 0)
{
windowHeight = document.documentElement.clientHeight;
}
// older versions of IE
else
{
windowHeight = document.getElementsByTagName('body')[0].clientHeight;
}
document.getElementById("yourDiv").height = windowHeight - 300 + "px";
None of the solution works for me. The td
last column still takes the full width. So here's the solution works.
Add table-fit
to your table
table.table-fit {
width: auto !important;
table-layout: auto !important;
}
table.table-fit thead th, table.table-fit tfoot th {
width: auto !important;
}
table.table-fit tbody td, table.table-fit tfoot td {
width: auto !important;
}
Here's the one for sass
uses.
@mixin width {
width: auto !important;
}
table {
&.table-fit {
@include width;
table-layout: auto !important;
thead th, tfoot th {
@include width;
}
tbody td, tfoot td {
@include width;
}
}
}
Differences:
{a: &b [*b]}
, which will loop infinitely in some converters. Even with circular detection, a "yaml bomb" is still possible (see xml bomb).Observations:
string[] lines = File.ReadAllLines("sample.txt"); List<string> list1 = new List<string>(); List<string> list2 = new List<string>(); foreach (var line in lines) { string[] values = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); list1.Add(values[0]); list2.Add(values[1]); }
Use range
. In Python 2.x it returns a list so all you need is:
>>> range(11, 17)
[11, 12, 13, 14, 15, 16]
In Python 3.x range
is a iterator. So, you need to convert it to a list:
>>> list(range(11, 17))
[11, 12, 13, 14, 15, 16]
Note: The second number is exclusive. So, here it needs to be 16+1
= 17
EDIT:
To respond to the question about incrementing by 0.5
, the easiest option would probably be to use numpy's arange()
and .tolist()
:
>>> import numpy as np
>>> np.arange(11, 17, 0.5).tolist()
[11.0, 11.5, 12.0, 12.5, 13.0, 13.5,
14.0, 14.5, 15.0, 15.5, 16.0, 16.5]
I have found a simple solution to banding by content at Pearson Software Consulting: Let's say the header is from A1 to B1, table data is from A2 to B5, the controling cell is in the A column
Use Below Code
your_button_id.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
} catch (Exception e) {
}
}
});
final
indicates that the value cannot be changed once set. static
allows you to set the value, and that value will be the same for ALL instances of the class which utilize it. Also, you may access the value of a public static
string w/o having an instance of a class.
With jquery (only tested in firefox):
function getScrollBarHeight() {
var jTest = $('<div style="display:none;width:50px;overflow: scroll"><div style="width:100px;"><br /><br /></div></div>');
$('body').append(jTest);
var h = jTest.innerHeight();
jTest.css({
overflow: 'auto',
width: '200px'
});
var h2 = jTest.innerHeight();
return h - h2;
}
function getScrollBarWidth() {
var jTest = $('<div style="display:none;height:50px;overflow: scroll"><div style="height:100px;"></div></div>');
$('body').append(jTest);
var w = jTest.innerWidth();
jTest.css({
overflow: 'auto',
height: '200px'
});
var w2 = jTest.innerWidth();
return w - w2;
}
But I actually like @Steve's answer better.
Simply You can do it with the help of cvlc- I did it in this way:
import os
os.popen2("cvlc /home/maulo/selfProject/task.mp3 --play-and-exit")
/home/maulo/selfProject/task.mp3. This is the location of my mp3 file. with the help of "--play-and-exit" you will be able to play again the sound without ending the vlc process.
Use FileUtils from Apache commons.
listFiles
public static Collection<File> listFiles(File directory,
String[] extensions,
boolean recursive)
Finds files within a given directory (and optionally its subdirectories) which match an array of extensions.
Parameters:
directory - the directory to search in
extensions - an array of extensions, ex. {"java","xml"}. If this parameter is null, all files are returned.
recursive - if true all subdirectories are searched as well
Returns:
an collection of java.io.File with the matching files
This code will exit the loop after the first iteration in a for of
loop:
const objc = [{ name: 1 }, { name: 2 }, { name: 3 }];
for (const iterator of objc) {
if (iterator.name == 2) {
return;
}
console.log(iterator.name);// 1
}
the below code will jump on the condition and continue on a for of
loop:
const objc = [{ name: 1 }, { name: 2 }, { name: 3 }];
for (const iterator of objc) {
if (iterator.name == 2) {
continue;
}
console.log(iterator.name); // 1 , 3
}
Use a list instead and replace your foreach
loop with a for
loop:
@model IList<BlockedIPViewModel>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@for (var i = 0; i < Model.Count; i++)
{
<tr>
<td>
@Html.HiddenFor(x => x[i].IP)
@Html.CheckBoxFor(x => x[i].Checked)
</td>
<td>
@Html.DisplayFor(x => x[i].IP)
</td>
</tr>
}
<div>
<input type="submit" value="Unblock IPs" />
</div>
}
Alternatively you could use an editor template:
@model IEnumerable<BlockedIPViewModel>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.EditorForModel()
<div>
<input type="submit" value="Unblock IPs" />
</div>
}
and then define the template ~/Views/Shared/EditorTemplates/BlockedIPViewModel.cshtml
which will automatically be rendered for each element of the collection:
@model BlockedIPViewModel
<tr>
<td>
@Html.HiddenFor(x => x.IP)
@Html.CheckBoxFor(x => x.Checked)
</td>
<td>
@Html.DisplayFor(x => x.IP)
</td>
</tr>
The reason you were getting null in your controller is because you didn't respect the naming convention for your input fields that the default model binder expects to successfully bind to a list. I invite you to read the following article
.
Once you have read it, look at the generated HTML (and more specifically the names of the input fields) with my example and yours. Then compare and you will understand why yours doesn't work.
You could try:
print ''.join(ch for ch in some_string if ch.isalnum())
You have to use <Integer>
instead of <int>
:
int a1[] = {1,2,3};
ArrayList<Integer> arl=new ArrayList<Integer>();
for(int i : a1) {
arl.add(i);
System.out.println("Arraylist contains:" + arl.get(0));
}
>>> s1="abc def ghi"
>>> s2="def ghi abc"
>>> s1 == s2 # For string comparison
False
>>> sorted(list(s1)) == sorted(list(s2)) # For comparing if they have same characters.
True
>>> sorted(list(s1))
[' ', ' ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
>>> sorted(list(s2))
[' ', ' ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
From here: http://docs.oracle.com/javase/tutorial/information/glossary.html
field
property
attribute
variable
The code marked @Before
is executed before each test, while @BeforeClass
runs once before the entire test fixture. If your test class has ten tests, @Before
code will be executed ten times, but @BeforeClass
will be executed only once.
In general, you use @BeforeClass
when multiple tests need to share the same computationally expensive setup code. Establishing a database connection falls into this category. You can move code from @BeforeClass
into @Before
, but your test run may take longer. Note that the code marked @BeforeClass
is run as static initializer, therefore it will run before the class instance of your test fixture is created.
In JUnit 5, the tags @BeforeEach
and @BeforeAll
are the equivalents of @Before
and @BeforeClass
in JUnit 4. Their names are a bit more indicative of when they run, loosely interpreted: 'before each tests' and 'once before all tests'.