According to this discussion, Promise
has finally been called CompletableFuture
for inclusion in Java 8, and its javadoc explains:
A Future that may be explicitly completed (setting its value and status), and may be used as a CompletionStage, supporting dependent functions and actions that trigger upon its completion.
An example is also given on the list:
f.then((s -> aStringFunction(s)).thenAsync(s -> ...);
Note that the final API is slightly different but allows similar asynchronous execution:
CompletableFuture<String> f = ...;
f.thenApply(this::modifyString).thenAccept(System.out::println);
In case that you want combine a List of CompletableFutures, you can do this :
List<CompletableFuture<Void>> futures = new ArrayList<>();
// ... Add futures to this ArrayList of CompletableFutures
// CompletableFuture.allOf() method demand a variadic arguments
// You can use this syntax to pass a List instead
CompletableFuture<Void> allFutures = CompletableFuture.allOf(
futures.toArray(new CompletableFuture[futures.size()]));
// Wait for all individual CompletableFuture to complete
// All individual CompletableFutures are executed in parallel
allFutures.get();
For more details on Future & CompletableFuture, useful links:
1. Future: https://www.baeldung.com/java-future
2. CompletableFuture: https://www.baeldung.com/java-completablefuture
3. CompletableFuture: https://www.callicoder.com/java-8-completablefuture-tutorial/
Code for Future Date only with disable today's date.
var d = new Date();
$("#delivdate").datepicker({
showOn: "button",
buttonImage: base_url+"images/cal.png",
minDate:new Date(d.setDate(d.getDate() + 1)),
buttonImageOnly: true
});
$('.ui-datepicker-trigger').attr('title','');
promise
represents a value that is not yet known deferred
represents work that is not yet finishedA promise is a placeholder for a result which is initially unknown while a deferred represents the computation that results in the value.
Reference
By default, the C library buffers the output until it sees a return. To print out the results immediately, use fflush
:
while((c=getchar())!= EOF)
{
putchar(c);
fflush(stdout);
}
Not all code paths set a value for lateFee
. You may want to set a default value for it at the top.
I don't know about android, but Safari on the iPhone or iPod touch will play all videos full screen because of the small screen size. On the iPad it will play the video on the page but allow the user to make it full screen.
I've been using this functional style for many group operations:
df = pd.DataFrame({
'Sp' : ['MM1', 'MM1', 'MM1', 'MM2', 'MM2', 'MM2', 'MM4', 'MM4', 'MM4'],
'Mt' : ['S1', 'S1', 'S3', 'S3', 'S4', 'S4', 'S2', 'S2', 'S2'],
'Val' : ['a', 'n', 'cb', 'mk', 'bg', 'dgb', 'rd', 'cb', 'uyi'],
'Count' : [3,2,5,8,10,1,2,2,7]
})
df.groupby('Mt')\
.apply(lambda group: group[group.Count == group.Count.max()])\
.reset_index(drop=True)
sp mt val count
0 MM1 S1 a 3
1 MM4 S2 uyi 7
2 MM2 S3 mk 8
3 MM2 S4 bg 10
.reset_index(drop=True)
gets you back to the original index by dropping the group-index.
In NodeJS if you know the ID
, the looping through the array is very slow compared to object[ID]
.
const uniqueString = require('unique-string');
const obj = {};
const arr = [];
var seeking;
//create data
for(var i=0;i<1000000;i++){
var getUnique = `${uniqueString()}`;
if(i===888555) seeking = getUnique;
arr.push(getUnique);
obj[getUnique] = true;
}
//retrieve item from array
console.time('arrTimer');
for(var x=0;x<arr.length;x++){
if(arr[x]===seeking){
console.log('Array result:');
console.timeEnd('arrTimer');
break;
}
}
//retrieve item from object
console.time('objTimer');
var hasKey = !!obj[seeking];
console.log('Object result:');
console.timeEnd('objTimer');
And the results:
Array result:
arrTimer: 12.857ms
Object result:
objTimer: 0.051ms
Even if the seeking ID is the first one in the array/object:
Array result:
arrTimer: 2.975ms
Object result:
objTimer: 0.068ms
It solved throung second parameter in Model load:
$this->load->model('user','User');
first parameter is the model's filename, and second it defining the name of model to be used in the controller:
function alluser()
{
$this->load->model('User');
$result = $this->User->showusers();
}
Another way to get the same result:
date <- strptime(v,format="%Y%m%d")
To account for leading and trailing whitespace, you probably want to use normalize-space()
//div[contains(@class, 'Caption') and normalize-space(.)='Model saved']
and
//div[@id='alertLabel' and normalize-space(.)='Save to server successful']
Note that //div[contains(@class, 'Caption') and normalize-space(.//text())='Model saved']
also works.
From Windows Command Line, delete all except the current checked out branch using:
for /f "tokens=*" %f in ('git branch ^| find /v "*"') do git branch -D %f
For a svn+ssh configuration, use ssh to run svnserve --version on the host machine:
$ ssh user@host svnserve --version
It is necessary to run the svnserve command on the machine that is actually serving as the server.
event.target
returns the node that was targeted by the function. This means you can do anything you would do with any other node like one you'd get from document.getElementById
Evidently, Eclipse does not automatically know where the source code for the dependent jars are. It is not clear why debugger could not inspect variables once the source was attached. One possibility is incorrect/incompatible source.
Assuming you have a maven project and the sources of the dependencies are downloaded and available in the local repository, you may want to install m2eclipse, the maven eclipse plugin and see if that helps in addressing your issue.
the_input = raw_input("Enter input: ")
And that's it.
Moreover, if you want to make a list of inputs, you can do something like:
a = []
for x in xrange(1,10):
a.append(raw_input("Enter Data: "))
In that case, you'll be asked for data 10 times to store 9 items in a list.
Output:
Enter data: 2
Enter data: 3
Enter data: 4
Enter data: 5
Enter data: 7
Enter data: 3
Enter data: 8
Enter data: 22
Enter data: 5
>>> a
['2', '3', '4', '5', '7', '3', '8', '22', '5']
You can search that list the fundamental way with something like (after making that list):
if '2' in a:
print "Found"
else: print "Not found."
You can replace '2' with "raw_input()" like this:
if raw_input("Search for: ") in a:
print "Found"
else:
print "Not found"
If you want to take the input from a file you feed through commandline (which is normally what you need when doing code problems for competitions, like Google Code Jam or the ACM/IBM ICPC):
example.py
while(True):
line = raw_input()
print "input data: %s" % line
In command line interface:
example.py < input.txt
Hope that helps.
I would have your main thread pass a callback method to your first thread, and when it's done, it will invoke the callback method on the mainthread, which can launch the second thread. This keeps your main thread from hanging while its waiting for a Join or Waithandle. Passing methods as delegates is a useful thing to learn with C# anyway.
The only problem with threads is accessing the same object from different threads without synchronization.
If each function only uses parameters for reading and local variables, they don't need any synchronization to be thread-safe.
That's because you shouldn't do it (at least with an immutable list). If you really really need to append an element to the end of a data structure and this data structure really really needs to be a list and this list really really has to be immutable then do eiher this:
(4 :: List(1,2,3).reverse).reverse
or that:
List(1,2,3) ::: List(4)
In Spring Boot 1.4.1 using Mustache templates, placing error.html under templates folder will be enough:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<h1>Error {{ status }}</h1>
<p>{{ error }}</p>
<p>{{ message }}</p>
<p>{{ path }}</p>
</body>
</html>
Additional variables can be passed by creating an interceptor for /error
I found this is in the runtime permissions example from Google's github.
private static String[] PERMISSIONS_CONTACT = {Manifest.permission.READ_CONTACTS,
Manifest.permission.WRITE_CONTACTS};
private static final int REQUEST_CONTACTS = 1;
ActivityCompat.requestPermissions(this, PERMISSIONS_CONTACT, REQUEST_CONTACTS);
It only seems to because that is what it is printing out. But actually, you shouldn't write the logic this way. This is equivalent:
insert into errortable (dateupdated, table1id)
values (sysdate, 1083);
It seems silly to convert the system date to a string just to convert it back to a date.
If you want to see the full date, then you can do:
select TO_CHAR(dateupdated, 'YYYY-MM-DD HH24:MI:SS'), table1id
from errortable;
The best way to solve this problem is, go to directory laravel/bootstrap/cache
and delete config.php
file. or you can rename it as well like config.php.old
And your problem will be fix.
Happy coding :-)
foreach($array as $v) echo $v, PHP_EOL;
UPDATE: A more sophisticated solution would be:
$test = [
'key1' => 'val1',
'key2' => 'val2',
'key3' => [
'subkey1' => 'subval1',
'subkey2' => 'subval2',
'subkey3' => [
'subsubkey1' => 'subsubval1',
'subsubkey2' => 'subsubval2',
],
],
];
function printArray($arr, $pad = 0, $padStr = "\t") {
$outerPad = $pad;
$innerPad = $pad + 1;
$out = '[' . PHP_EOL;
foreach ($arr as $k => $v) {
if (is_array($v)) {
$out .= str_repeat($padStr, $innerPad) . $k . ' => ' . printArray($v, $innerPad) . PHP_EOL;
} else {
$out .= str_repeat($padStr, $innerPad) . $k . ' => ' . $v;
$out .= PHP_EOL;
}
}
$out .= str_repeat($padStr, $outerPad) . ']';
return $out;
}
echo printArray($test);
This prints out:
[
key1 => val1
key2 => val2
key3 => [
subkey1 => subval1
subkey2 => subval2
subkey3 => [
subsubkey1 => subsubval1
subsubkey2 => subsubval2
]
]
]
Here is a solution using win32 api and std string in case you need your application to run on a OS with no CLR. I found it here on github.
#include "stdafx.h"
#include <windows.h>
#include <memory>
#include <string>
//returns the serial number of the first physical drive in a std::string or an empty std::string in case of failure
//based on http://codexpert.ro/blog/2013/10/26/get-physical-drive-serial-number-part-1/
std::string getFirstHddSerialNumber() {
//get a handle to the first physical drive
HANDLE h = CreateFileW(L"\\\\.\\PhysicalDrive0", 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (h == INVALID_HANDLE_VALUE) return{};
//an std::unique_ptr is used to perform cleanup automatically when returning (i.e. to avoid code duplication)
std::unique_ptr<std::remove_pointer<HANDLE>::type, void(*)(HANDLE)> hDevice{ h, [](HANDLE handle){CloseHandle(handle); } };
//initialize a STORAGE_PROPERTY_QUERY data structure (to be used as input to DeviceIoControl)
STORAGE_PROPERTY_QUERY storagePropertyQuery{};
storagePropertyQuery.PropertyId = StorageDeviceProperty;
storagePropertyQuery.QueryType = PropertyStandardQuery;
//initialize a STORAGE_DESCRIPTOR_HEADER data structure (to be used as output from DeviceIoControl)
STORAGE_DESCRIPTOR_HEADER storageDescriptorHeader{};
//the next call to DeviceIoControl retrieves necessary size (in order to allocate a suitable buffer)
//call DeviceIoControl and return an empty std::string on failure
DWORD dwBytesReturned = 0;
if (!DeviceIoControl(hDevice.get(), IOCTL_STORAGE_QUERY_PROPERTY, &storagePropertyQuery, sizeof(STORAGE_PROPERTY_QUERY),
&storageDescriptorHeader, sizeof(STORAGE_DESCRIPTOR_HEADER), &dwBytesReturned, NULL))
return{};
//allocate a suitable buffer
const DWORD dwOutBufferSize = storageDescriptorHeader.Size;
std::unique_ptr<BYTE[]> pOutBuffer{ new BYTE[dwOutBufferSize]{} };
//call DeviceIoControl with the allocated buffer
if (!DeviceIoControl(hDevice.get(), IOCTL_STORAGE_QUERY_PROPERTY, &storagePropertyQuery, sizeof(STORAGE_PROPERTY_QUERY),
pOutBuffer.get(), dwOutBufferSize, &dwBytesReturned, NULL))
return{};
//read and return the serial number out of the output buffer
STORAGE_DEVICE_DESCRIPTOR* pDeviceDescriptor = reinterpret_cast<STORAGE_DEVICE_DESCRIPTOR*>(pOutBuffer.get());
const DWORD dwSerialNumberOffset = pDeviceDescriptor->SerialNumberOffset;
if (dwSerialNumberOffset == 0) return{};
const char* serialNumber = reinterpret_cast<const char*>(pOutBuffer.get() + dwSerialNumberOffset);
return serialNumber;
}
#include <iostream>
int main() {
std::string serialNumber = getFirstHddSerialNumber();
if (serialNumber.empty())
std::cout << "failed to retrieve serial number\n";
else
std::cout << "serial number: " << serialNumber << "\n";
return 0;
}
If you are doing it from the emulator you can do it like this:
Run emulator -tcpdump emulator.cap -avd my_avd
to write all the emulator's traffic to a local file on your PC and then open it in wireshark
There is a similar post that might help HERE
I had the same question and found using a ListIterator
worked. Similar to the test above:
List<String> list = Arrays.asList("zero", "one", "two");
ListIterator iter = list.listIterator();
while (iter.hasNext()) {
System.out.println("index: " + iter.nextIndex() + " value: " + iter.next());
}
Make sure you call the nextIndex()
before you actually get the next()
.
If you are using Table.query
property:
from sqlalchemy import func
Table.query.with_entities(Table.column, func.count(Table.column)).group_by(Table.column).all()
If you are using session.query()
method (as stated in miniwark's answer):
from sqlalchemy import func
session.query(Table.column, func.count(Table.column)).group_by(Table.column).all()
Use the onsubmit
event to execute JavaScript code when the form is submitted. You can then return false or call the passed event's preventDefault
method to disable the form submission.
For example:
<script>
function doSomething() {
alert('Form submitted!');
return false;
}
</script>
<form onsubmit="return doSomething();" class="my-form">
<input type="submit" value="Submit">
</form>
This works, but it's best not to litter your HTML with JavaScript, just as you shouldn't write lots of inline CSS rules. Many Javascript frameworks facilitate this separation of concerns. In jQuery you bind an event using JavaScript code like so:
<script>
$('.my-form').on('submit', function () {
alert('Form submitted!');
return false;
});
</script>
<form class="my-form">
<input type="submit" value="Submit">
</form>
I would think it could still be quite RESTful to have query arguments that identify the resource on the URL while keeping the content payload confined to the POST body. This would seem to separate the considerations of "What am I sending?" versus "Who am I sending it to?".
To start with, from the Oracle Database Data Warehousing Guide:
Restrictions on Fast Refresh on Materialized Views with Joins Only
...
- Rowids of all the tables in the FROM list must appear in the SELECT list of the query.
This means that your statement will need to look something like this:
CREATE MATERIALIZED VIEW MV_Test
NOLOGGING
CACHE
BUILD IMMEDIATE
REFRESH FAST ON COMMIT
AS
SELECT V.*, P.*, V.ROWID as V_ROWID, P.ROWID as P_ROWID
FROM TPM_PROJECTVERSION V,
TPM_PROJECT P
WHERE P.PROJECTID = V.PROJECTID
Another key aspect to note is that your materialized view logs must be created as with rowid
.
Below is a functional test scenario:
CREATE TABLE foo(foo NUMBER, CONSTRAINT foo_pk PRIMARY KEY(foo));
CREATE MATERIALIZED VIEW LOG ON foo WITH ROWID;
CREATE TABLE bar(foo NUMBER, bar NUMBER, CONSTRAINT bar_pk PRIMARY KEY(foo, bar));
CREATE MATERIALIZED VIEW LOG ON bar WITH ROWID;
CREATE MATERIALIZED VIEW foo_bar
NOLOGGING
CACHE
BUILD IMMEDIATE
REFRESH FAST ON COMMIT AS SELECT foo.foo,
bar.bar,
foo.ROWID AS foo_rowid,
bar.ROWID AS bar_rowid
FROM foo, bar
WHERE foo.foo = bar.foo;
Ive been looking for an nice select dropdown for some time now and I found a good one. So im just gonna leave it here. Its called bootsrap-select
here's the link. check it out. it has editable dropdowns, combo drop downs and more. And its a breeze to add to your project.
If the link dies just search for bootstrap-select by silviomoreto.github.io. This is better because its a normal select tag
I think from the author's point of view, the main reason is to reduce the overhead for string concatenation.I just read the logger's documentation, you could find following words:
/**
* <p>This form avoids superfluous string concatenation when the logger
* is disabled for the DEBUG level. However, this variant incurs the hidden
* (and relatively small) cost of creating an <code>Object[]</code> before
invoking the method,
* even if this logger is disabled for DEBUG. The variants taking
* {@link #debug(String, Object) one} and {@link #debug(String, Object, Object) two}
* arguments exist solely in order to avoid this hidden cost.</p>
*/
*
* @param format the format string
* @param arguments a list of 3 or more arguments
*/
public void debug(String format, Object... arguments);
To make it handy, use POJO.
try like this..
List<YourPojoObject> yourPojos = new ArrayList<YourPojoObject>();
JSONObject jsonObject = new JSONObject(jsonString);
YourPojoObject yourPojo = new YourPojoObject();
yourPojo.setId(jsonObject.getString("idName"));
...
...
yourPojos.add(yourPojo);
eval()
can not handle the list object
tf.reset_default_graph()
a = tf.Variable(0.2, name="a")
b = tf.Variable(0.3, name="b")
z = tf.constant(0.0, name="z0")
for i in range(100):
z = a * tf.cos(z + i) + z * tf.sin(b - i)
grad = tf.gradients(z, [a, b])
init = tf.global_variables_initializer()
with tf.Session() as sess:
init.run()
print("z:", z.eval())
print("grad", grad.eval())
but Session.run()
can
print("grad", sess.run(grad))
correct me if I am wrong
This way you can set the initial day of the week.
moment.locale('en', {
week: {
dow: 6
}
});
moment.locale('en');
Make sure to use it with moment().weekday(1);
instead of moment.isoWeekday(1)
In this answer I am using an example posted by Justin Grammens.
JSON stands for JavaScript Object Notation. In JavaScript properties can be referenced both like this object1.name
and like this object['name'];
. The example from the article uses this bit of JSON.
The Parts
A fan object with email as a key and [email protected] as a value
{
fan:
{
email : '[email protected]'
}
}
So the object equivalent would be fan.email;
or fan['email'];
. Both would have the same value
of '[email protected]'
.
The following is what our author used to make a HttpClient Request. I do not claim to be an expert at all this so if anyone has a better way to word some of the terminology feel free.
public static HttpResponse makeRequest(String path, Map params) throws Exception
{
//instantiates httpclient to make request
DefaultHttpClient httpclient = new DefaultHttpClient();
//url with the post data
HttpPost httpost = new HttpPost(path);
//convert parameters into JSON object
JSONObject holder = getJsonObjectFromMap(params);
//passes the results to a string builder/entity
StringEntity se = new StringEntity(holder.toString());
//sets the post request as the resulting string
httpost.setEntity(se);
//sets a request header so the page receving the request
//will know what to do with it
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json");
//Handles what is returned from the page
ResponseHandler responseHandler = new BasicResponseHandler();
return httpclient.execute(httpost, responseHandler);
}
If you are not familiar with the Map
data structure please take a look at the Java Map reference. In short, a map is similar to a dictionary or a hash.
private static JSONObject getJsonObjectFromMap(Map params) throws JSONException {
//all the passed parameters from the post request
//iterator used to loop through all the parameters
//passed in the post request
Iterator iter = params.entrySet().iterator();
//Stores JSON
JSONObject holder = new JSONObject();
//using the earlier example your first entry would get email
//and the inner while would get the value which would be '[email protected]'
//{ fan: { email : '[email protected]' } }
//While there is another entry
while (iter.hasNext())
{
//gets an entry in the params
Map.Entry pairs = (Map.Entry)iter.next();
//creates a key for Map
String key = (String)pairs.getKey();
//Create a new map
Map m = (Map)pairs.getValue();
//object for storing Json
JSONObject data = new JSONObject();
//gets the value
Iterator iter2 = m.entrySet().iterator();
while (iter2.hasNext())
{
Map.Entry pairs2 = (Map.Entry)iter2.next();
data.put((String)pairs2.getKey(), (String)pairs2.getValue());
}
//puts email and '[email protected]' together in map
holder.put(key, data);
}
return holder;
}
Please feel free to comment on any questions that arise about this post or if I have not made something clear or if I have not touched on something that your still confused about... etc whatever pops in your head really.
(I will take down if Justin Grammens does not approve. But if not then thanks Justin for being cool about it.)
I just happend to get a comment about how to use the code and realized that there was a mistake in the return type. The method signature was set to return a string but in this case it wasnt returning anything. I changed the signature to HttpResponse and will refer you to this link on Getting Response Body of HttpResponse the path variable is the url and I updated to fix a mistake in the code.
Add /Y to the command line
Not totally related, but you can also check for both undefined
AND empty
(for e.g my_variable:
) variable. (NOTE: only works with ansible version > 1.9, see: link)
- name: Create user
user:
name: "{{ ((my_variable == None) | ternary('default_value', my_variable)) \
if my_variable is defined else 'default_value' }}"
From Increase MySQL connection limit:-
MySQL’s default configuration sets the maximum simultaneous connections to 100. If you need to increase it, you can do it fairly easily:
For MySQL 3.x:
# vi /etc/my.cnf
set-variable = max_connections = 250
For MySQL 4.x and 5.x:
# vi /etc/my.cnf
max_connections = 250
Restart MySQL once you’ve made the changes and verify with:
echo "show variables like 'max_connections';" | mysql
EDIT:-(From comments)
The maximum concurrent connection can be maximum range: 4,294,967,295. Check MYSQL docs
For parsing do this-
$http.jsonp(url).
success(function(data, status, headers, config) {
//what do I do here?
$scope.data=data;
}).
Or you can use `$scope.data=JSON.Stringify(data);
In Angular template you can use it as
{{data}}
FQDN means the resolved name over DNS. It should be like "server-name.search-domain".
The warning you get just provides a notice that httpd can not find a FQDN, so it might not work right to handle a name-based virtual host. So make sure the expected FQDN is registered in your DNS server, or manually add the entry in /etc/hosts
which is prior to hitting DNS.
Try the bash
built-in help:
$ help for
for: for NAME [in WORDS ... ;] do COMMANDS; done
The `for' loop executes a sequence of commands for each member in a
list of items. If `in WORDS ...;' is not present, then `in "$@"' is
assumed. For each element in WORDS, NAME is set to that element, and
the COMMANDS are executed.
for ((: for (( exp1; exp2; exp3 )); do COMMANDS; done
Equivalent to
(( EXP1 ))
while (( EXP2 )); do
COMMANDS
(( EXP3 ))
done
EXP1, EXP2, and EXP3 are arithmetic expressions. If any expression is
omitted, it behaves as if it evaluates to 1.
Please check you are using //
not \\
by-mistake , like below
Wrong:"http:\\stackoverflow.com"
Right:"http://stackoverflow.com"
Remember:
"Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%".
(Thanks to metamorphosis for the full quote)
Don't use a C array instead of a vector (or whatever) just because you believe it's faster as it is supposed to be lower-level. You would be wrong.
Use by default vector (or the safe container adapted to your need), and then if your profiler says it is a problem, see if you can optimize it, either by using a better algorithm, or changing container.
This said, we can go back to the original question.
The C++ array classes are better behaved than the low-level C array because they know a lot about themselves, and can answer questions C arrays can't. They are able to clean after themselves. And more importantly, they are usually written using templates and/or inlining, which means that what appears to a lot of code in debug resolves to little or no code produced in release build, meaning no difference with their built-in less safe competition.
All in all, it falls on two categories:
Using a pointer to a malloc-ed/new-ed array will be at best as fast as the std::vector version, and a lot less safe (see litb's post).
So use a std::vector.
Using a static array will be at best:
So use a std::array.
Sometimes, using a vector
instead of a raw buffer incurs a visible cost because the vector
will initialize the buffer at construction, while the code it replaces didn't, as remarked bernie by in his answer.
If this is the case, then you can handle it by using a unique_ptr
instead of a vector
or, if the case is not exceptional in your codeline, actually write a class buffer_owner
that will own that memory, and give you easy and safe access to it, including bonuses like resizing it (using realloc
?), or whatever you need.
In my case the problem was that debugging configuration become invalid somehow, even that the test method name, class or package has not changed.
I deleted the configurations from Run->Edit Configurations, at here:
Android studio will create a new one automatically.
Since you want to pivot multiple columns of data, I would first suggest unpivoting the result
, score
and grade
columns so you don't have multiple columns but you will have multiple rows.
Depending on your version of SQL Server you can use the UNPIVOT function or CROSS APPLY. The syntax to unpivot the data will be similar to:
select ratio, col, value
from GRAND_TOTALS
cross apply
(
select 'result', cast(result as varchar(10)) union all
select 'score', cast(score as varchar(10)) union all
select 'grade', grade
) c(col, value)
See SQL Fiddle with Demo. Once the data has been unpivoted, then you can apply the PIVOT function:
select ratio = col,
[current ratio], [gearing ratio], [performance ratio], total
from
(
select ratio, col, value
from GRAND_TOTALS
cross apply
(
select 'result', cast(result as varchar(10)) union all
select 'score', cast(score as varchar(10)) union all
select 'grade', grade
) c(col, value)
) d
pivot
(
max(value)
for ratio in ([current ratio], [gearing ratio], [performance ratio], total)
) piv;
See SQL Fiddle with Demo. This will give you the result:
| RATIO | CURRENT RATIO | GEARING RATIO | PERFORMANCE RATIO | TOTAL |
|--------|---------------|---------------|-------------------|-----------|
| grade | Good | Good | Satisfactory | Good |
| result | 1.29400 | 0.33840 | 0.04270 | (null) |
| score | 60.00000 | 70.00000 | 50.00000 | 180.00000 |
You Can't write JSON file while in assets. as already described assets are read-only. But you can copy assets (json file/anything else in assets ) to local storage of mobile and then edit(write/read) from local storage. More storage options like shared Preference(for small data) and sqlite database(for large data) are available.
This works for me:
CSS
.form-group.required.control-label:before{
content: "*";
color: red;
}
OR
.form-group.required.control-label:after{
content: "*";
color: red;
}
Basic HTML
<div class="form-group required control-label">
<input class="form-control" />
</div>
Adding responseType to the request that is made from angular is indeed the solution, but for me it didn't work until I've set responseType to blob, not to arrayBuffer. The code is self explanatory:
$http({
method : 'GET',
url : 'api/paperAttachments/download/' + id,
responseType: "blob"
}).then(function successCallback(response) {
console.log(response);
var blob = new Blob([response.data]);
FileSaver.saveAs(blob, getFileNameFromHttpResponse(response));
}, function errorCallback(response) {
});
I had a very similar problem, I had an array ready to be posted. in my post function I had this:
json = JSON.stringfy(json);
the detail here is that I'm using blade inside laravel to build a three view form, so I can go back and forward, I have in between every back and forward button validations and when I go back in the form without reloading the page my json get filled by backslashes. I console.log(json)
in every validation and realized that the json was treated as a string instead of an object.
In conclution i shouldn't have assinged json = JSON.stringfy(json)
instead i assigned it to another variable.
var aux = JSON.stringfy(json);
This way i keep json as an object, and not a string.
EDITED ANSWER PER DAVID'S RESPONSE:
Here's a kind of hackish way. I'm guessing there's an easier way. But you could suppress the bar labels and the plot text of the labels by saving the bar positions from barplot
and do a little tweaking up and down. Here's an example with the mtcars data set:
x <- barplot(table(mtcars$cyl), xaxt="n")
labs <- paste(names(table(mtcars$cyl)), "cylinders")
text(cex=1, x=x-.25, y=-1.25, labs, xpd=TRUE, srt=45)
If you just want to iterate over the tokens, this is pretty neat:
line = "one, two and 3!"
for token in string.gmatch(line, "[^%s]+") do
print(token)
end
Output:
one,
two
and
3!
Short explanation: the "[^%s]+" pattern matches to every non-empty string in between space characters.
There's a kind of hack-tastic way to do it if you have php enabled on your server. Change this line:
url: 'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml',
to this line:
url: '/path/to/phpscript.php',
and then in the php script (if you have permission to use the file_get_contents() function):
<?php
header('Content-type: application/xml');
echo file_get_contents("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");
?>
Php doesn't seem to mind if that url is from a different origin. Like I said, this is a hacky answer, and I'm sure there's something wrong with it, but it works for me.
Edit: If you want to cache the result in php, here's the php file you would use:
<?php
$cacheName = 'somefile.xml.cache';
// generate the cache version if it doesn't exist or it's too old!
$ageInSeconds = 3600; // one hour
if(!file_exists($cacheName) || filemtime($cacheName) > time() + $ageInSeconds) {
$contents = file_get_contents('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml');
file_put_contents($cacheName, $contents);
}
$xml = simplexml_load_file($cacheName);
header('Content-type: application/xml');
echo $xml;
?>
Caching code take from here.
You actually want TestClass.instance_methods
, unless you're interested in what TestClass
itself can do.
class TestClass
def method1
end
def method2
end
def method3
end
end
TestClass.methods.grep(/method1/) # => []
TestClass.instance_methods.grep(/method1/) # => ["method1"]
TestClass.methods.grep(/new/) # => ["new"]
Or you can call methods
(not instance_methods
) on the object:
test_object = TestClass.new
test_object.methods.grep(/method1/) # => ["method1"]
use chomp
or strip
functions from Ruby:
"abcd\n".chomp => "abcd"
"abcd\n".strip => "abcd"
I had the same problem, and it turned out I hadn't installed the library.
this link was super usefull.
You can set its before
and after
to force a constant width-to-height ratio
HTML:
<div class="squared"></div>
CSS:
.squared {
background: #333;
width: 300px;
}
.squared::before {
content: '';
padding-top: 100%;
float: left;
}
.squared::after {
content: '';
display: block;
clear: both;
}
I finally realized now that instead of
git fetch --all && git reset --hard origin/master
it should be
git fetch --all && git reset --hard origin/<branch_name>
instead (if one works on a different branch)
The advice you were given is flawed. Unconditionally setting GIT_AUTHOR_DATE in an --env-filter
would rewrite the date of every commit. Also, it would be unusual to use git commit inside --index-filter
.
You are dealing with multiple, independent problems here.
Each commit has two dates: the author date and the committer date. You can override each by supplying values through the environment variables GIT_AUTHOR_DATE and GIT_COMMITTER_DATE for any command that writes a new commit. See “Date Formats” in git-commit(1) or the below:
Git internal format = <unix timestamp> <time zone offset>, e.g. 1112926393 +0200
RFC 2822 = e.g. Thu, 07 Apr 2005 22:13:13 +0200
ISO 8601 = e.g. 2005-04-07T22:13:13
The only command that writes a new commit during normal use is git commit. It also has a --date
option that lets you directly specify the author date. Your anticipated usage includes git filter-branch --env-filter
also uses the environment variables mentioned above (these are part of the “env” after which the option is named; see “Options” in git-filter-branch(1) and the underlying “plumbing” command git-commit-tree(1).
If your repository is very simple (i.e. you only have a single branch, no tags), then you can probably use git rebase to do the work.
In the following commands, use the object name (SHA-1 hash) of the commit instead of “A”. Do not forget to use one of the “date override” methods when you run git commit.
---A---B---C---o---o---o master
git checkout master
git checkout A~0
git add path/to/file
git commit --date='whenever'
git tag ,new-commit -m'delete me later'
git checkout -
git rebase --onto ,new-commit A
git tag -d ,new-commit
---A---N (was ",new-commit", but we delete the tag)
\
B'---C'---o---o---o master
If you wanted to update A to include the new file (instead of creating a new commit where it was added), then use git commit --amend
instead of git commit
. The result would look like this:
---A'---B'---C'---o---o---o master
The above works as long as you can name the commit that should be the parent of your new commit. If you actually want your new file to be added via a new root commit (no parents), then you need something a bit different:
B---C---o---o---o master
git checkout master
git checkout --orphan new-root
git rm -rf .
git add path/to/file
GIT_AUTHOR_DATE='whenever' git commit
git checkout -
git rebase --root --onto new-root
git branch -d new-root
N (was new-root, but we deleted it)
\
B'---C'---o---o---o master
git checkout --orphan
is relatively new (Git 1.7.2), but there are other ways of doing the same thing that work on older versions of Git.
If your repository is more complex (i.e. it has more than one ref (branches, tags, etc.)), then you will probably need to use git filter-branch. Before using git filter-branch, you should make a backup copy of your entire repository. A simple tar archive of your entire working tree (including the .git directory) is sufficient. git filter-branch does make backup refs, but it is often easier to recover from a not-quite-right filtering by just deleting your .git
directory and restoring it from your backup.
Note: The examples below use the lower-level command git update-index --add
instead of git add
. You could use git add, but you would first need to copy the file from some external location to the expected path (--index-filter
runs its command in a temporary GIT_WORK_TREE that is empty).
If you want your new file to be added to every existing commit, then you can do this:
new_file=$(git hash-object -w path/to/file)
git filter-branch \
--index-filter \
'git update-index --add --cacheinfo 100644 '"$new_file"' path/to/file' \
--tag-name-filter cat \
-- --all
git reset --hard
I do not really see any reason to change the dates of the existing commits with --env-filter 'GIT_AUTHOR_DATE=…'
. If you did use it, you would have make it conditional so that it would rewrite the date for every commit.
If you want your new file to appear only in the commits after some existing commit (“A”), then you can do this:
file_path=path/to/file
before_commit=$(git rev-parse --verify A)
file_blob=$(git hash-object -w "$file_path")
git filter-branch \
--index-filter '
if x=$(git rev-list -1 "$GIT_COMMIT" --not '"$before_commit"') &&
test -n "$x"; then
git update-index --add --cacheinfo 100644 '"$file_blob $file_path"'
fi
' \
--tag-name-filter cat \
-- --all
git reset --hard
If you want the file to be added via a new commit that is to be inserted into the middle of your history, then you will need to generate the new commit prior to using git filter-branch and add --parent-filter
to git filter-branch:
file_path=path/to/file
before_commit=$(git rev-parse --verify A)
git checkout master
git checkout "$before_commit"
git add "$file_path"
git commit --date='whenever'
new_commit=$(git rev-parse --verify HEAD)
file_blob=$(git rev-parse --verify HEAD:"$file_path")
git checkout -
git filter-branch \
--parent-filter "sed -e s/$before_commit/$new_commit/g" \
--index-filter '
if x=$(git rev-list -1 "$GIT_COMMIT" --not '"$new_commit"') &&
test -n "$x"; then
git update-index --add --cacheinfo 100644 '"$file_blob $file_path"'
fi
' \
--tag-name-filter cat \
-- --all
git reset --hard
You could also arrange for the file to be first added in a new root commit: create your new root commit via the “orphan” method from the git rebase section (capture it in new_commit
), use the unconditional --index-filter
, and a --parent-filter
like "sed -e \"s/^$/-p $new_commit/\""
.
If You want to compile a Delphi project, look at "ERROR MSB4040 There is no target in the project" when using msbuild+Delphi2009
Correct answer there are said: "There is a batch file called rsvars.bat (search for it in the RAD Studio folder). Call that before calling MSBuild, and it will setup the necessary environment variables. Make sure the folders are correct in rsvars.bat if you have the compiler in a different location to the default."
This bat will not only update the PATH environment variable to proper .NET folder with proper MSBuild.exe version, but also registers other necessary variables.
Put the date in single quotes and move the parenthesis (after the 'yes'
) to the end:
INSERT INTO custorder
VALUES ('Kevin', 'yes' , STR_TO_DATE('1-01-2012', '%d-%m-%Y') ) ;
^ ^
---parenthesis removed--| and added here ------|
But you can always use dates without STR_TO_DATE()
function, just use the (Y-m-d) '20120101'
or '2012-01-01'
format. Check the MySQL docs: Date and Time Literals
INSERT INTO custorder
VALUES ('Kevin', 'yes', '2012-01-01') ;
With either string concatenation or string interpolation (via template literals).
Here with JavaScript template literal:
function geoPreview() {
var lat = document.getElementById("lat").value;
var long = document.getElementById("long").value;
window.location.href = `http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat=${lat}&lon=${long}&setLatLon=Set`;
}
Both parameters are unused and can be removed.
Join strings with the +
operator:
window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat=" + elemA + "&lon=" + elemB + "&setLatLon=Set";
For more concise code, use JavaScript template literals to replace expressions with their string representations.
Template literals are enclosed by ``
and placeholders surrounded with ${}
:
window.location.href = `http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat=${elemA}&lon=${elemB}&setLatLon=Set`;
Template literals are available since ECMAScript 2015 (ES6).
You can use the step attribute to the input type number:
<input type="number" id="totalAmt" step="0.1"></input>
step="any"
will allow any decimal.
step="1"
will allow no decimal.
step="0.5"
will allow 0.5; 1; 1.5; ...
step="0.1"
will allow 0.1; 0.2; 0.3; 0.4; ...
If this is what you want ...simply add button inside the Fragment.
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.LocationChooser">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right|top"
android:text="Demo Button"
android:padding="10dp"
android:layout_marginTop="20dp"
android:paddingRight="10dp"/>
</fragment>
You started with ManyToOne mapping , then you put OneToMany mapping as well for BiDirectional way. Then at OneToMany side (usually your parent table/class), you have to mention "mappedBy" (mapping is done by and in child table/class), so hibernate will not create EXTRA mapping table in DB (like TableName = parent_child).
check out
http://www.thesitewizard.com/general/set-cron-job.shtml
for the specifics of setting your crontab directives.
45 10 * * *
will run in the 10th hour, 45th minute of every day.
for midnight... maybe
0 0 * * *
I got here with a bit more general problem - I wanted to find files in directories matching pattern but not in their subdirectories.
My solution (assuming we're looking for all cpp
files living directly in arch
directories):
find . -path "*/arch/*/*" -prune -o -path "*/arch/*.cpp" -print
I couldn't use maxdepth since it limited search in the first place, and didn't know names of subdirectories that I wanted to exclude.
I faced the same error with:
import codecs as cd
f=cd.open(filePath,'r','ISO-8859-1')
I solved the problem by changing the encoding to utf-16
f=cd.open(filePath,'r','utf-16')
It is most likely a mismatch between the model class name and the table name as mentioned by 'adrift'. Make these the same or use the example below for when you want to keep the model class name different from the table name (that I did for OAuthMembership). Note that the model class name is OAuthMembership whereas the table name is webpages_OAuthMembership.
Either provide a table attribute to the Model:
[Table("webpages_OAuthMembership")]
public class OAuthMembership
OR provide the mapping by overriding DBContext OnModelCreating:
class webpages_OAuthMembershipEntities : DbContext
{
protected override void OnModelCreating( DbModelBuilder modelBuilder )
{
var config = modelBuilder.Entity<OAuthMembership>();
config.ToTable( "webpages_OAuthMembership" );
}
public DbSet<OAuthMembership> OAuthMemberships { get; set; }
}
More readable way of achieving this (not a fan of single line ansible tasks)
- local_action:
module: copy
content: "{{ foo_result }}"
dest: /path/to/destination/file
Check http://www.aranedabienesraices.com.ar
This site is built with XML/XSLT client-side. It works on IE6-7-8, FF, O, Safari and Chrome. Are you sending HTTP headers correctly? Are you respecting the same-origin policy?
I think there is no standard syntax for command line usage, but most use this convention:
Microsoft Command-Line Syntax, IBM has similar Command-Line Syntax
Text without brackets or braces
Items you must type as shown
<Text inside angle brackets>
Placeholder for which you must supply a value
[Text inside square brackets]
Optional items
{Text inside braces}
Set of required items; choose one
{a|b}
Separator for mutually exclusive items; choose one
<file> …
Items that can be repeated
hr {
height: 1px;
color: #123455;
background-color: #123455;
border: none;
}
Doing it this way allows you to change the height if needed. Good luck. Source: How To Style HR with CSS
you can use like these "txtpassword.PasswordChar = '•';"
the use location is ...
namespace Library_Management_System
{
public partial class Login : Form
{
public Login()
{
InitializeComponent();
txtpassword.PasswordChar = '•';
I think all you need to do for your function is just add PtrSafe: i.e. the first line of your first function should look like this:
Private Declare PtrSafe Function swe_azalt Lib "swedll32.dll" ......
You should add a __eq__
and a __hash__
method to your Data
class, it could check if the __dict__
attributes are equal (same properties) and then if their values are equal, too.
If you did that, you can use
test = Data()
test.n = 5
found = test in myList
The in
keyword checks if test
is in myList
.
If you only want to a a n
property in Data
you could use:
class Data(object):
__slots__ = ['n']
def __init__(self, n):
self.n = n
def __eq__(self, other):
if not isinstance(other, Data):
return False
if self.n != other.n:
return False
return True
def __hash__(self):
return self.n
myList = [ Data(1), Data(2), Data(3) ]
Data(2) in myList #==> True
Data(5) in myList #==> False
I ended up using IcoMoon app to create a custom font using only the new themed icons I required for a recent web app build. It's not perfect but you can mimic the existing Google Font functionality pretty nicely with a little bit of setup. Here's a writeup:
If someone is feeling daring, they could convert the entire theme using IcoMoon. Hell, IcoMoon probably has an internal process that would make it easy since they already have the original Material Icons set in their library.
Anyway, this isn't a perfect solution, but it worked for me.
I ran into this problem where the one liner provided by the first answer worked well. However, I had the extra complication where the second copy of the column had all of the data. The first copy did not.
The solution was to create two data frames by splitting the one data frame by toggling the negation operator. Once I had the two data frames, I ran a join statement using the lsuffix
. This way, I could then reference and delete the column without the data.
- E
You Can Use Regex Like This:
^[0-9\-\(\)\, ]+$
Based on ?eurobur?, test an sub-class case
class Foo: NSObject {
func test() {
print("1")
objc_sync_enter(self)
defer {
objc_sync_exit(self)
print("3")
}
print("2")
}
}
class Foo2: Foo {
override func test() {
super.test()
print("11")
objc_sync_enter(self)
defer {
print("33")
objc_sync_exit(self)
}
print("22")
}
}
let test = Foo2()
test.test()
1
2
3
11
22
33
The oracle tag was not on the question when this answer was offered, and apparently it doesn't work with oracle, but it does work with at least postgres and mysql
No, just use the value directly:
begin
if (select count(*) from table) > 0 then
update table
end if;
end;
Note there is no need for an "else".
You can simply do it all within the update statement (ie no if
construct):
update table
set ...
where ...
and exists (select 'x' from table where ...)
The best way around this would be to create an Excel called 'launcher.xlsm' in the same folder as the file you wish to open. In the 'launcher' file put the following code in the 'Workbook' object, but set the constant TargetWBName
to be the name of the file you wish to open.
Private Const TargetWBName As String = "myworkbook.xlsx"
'// First, a function to tell us if the workbook is already open...
Function WorkbookOpen(WorkBookName As String) As Boolean
' returns TRUE if the workbook is open
WorkbookOpen = False
On Error GoTo WorkBookNotOpen
If Len(Application.Workbooks(WorkBookName).Name) > 0 Then
WorkbookOpen = True
Exit Function
End If
WorkBookNotOpen:
End Function
Private Sub Workbook_Open()
'Check if our target workbook is open
If WorkbookOpen(TargetWBName) = False Then
'set calculation to manual
Application.Calculation = xlCalculationManual
Workbooks.Open ThisWorkbook.Path & "\" & TargetWBName
DoEvents
Me.Close False
End If
End Sub
Set the constant 'TargetWBName' to be the name of the workbook that you wish to open.
This code will simply switch calculation to manual, then open the file. The launcher file will then automatically close itself.
*NOTE: If you do not wish to be prompted to 'Enable Content' every time you open this file (depending on your security settings) you should temporarily remove the 'me.close' to prevent it from closing itself, save the file and set it to be trusted, and then re-enable the 'me.close' call before saving again. Alternatively, you could just set the False to True
after Me.Close
You need to "clear" the float after every 6 images. So with your current code, change the styles for containerdivNewLine
to:
.containerdivNewLine { clear: both; float: left; display: block; position: relative; }
You can try this fineuploader
It works fine under IE6(and above), Chrome or Firefox
Borders of different colors. I used 3 items.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="@color/colorAccent" />
</shape>
</item>
<item android:top="3dp">
<shape android:shape="rectangle">
<solid android:color="@color/light_grey" />
</shape>
</item>
<item
android:bottom="1dp"
android:left="1dp"
android:right="1dp"
android:top="3dp">
<shape android:shape="rectangle">
<solid android:color="@color/colorPrimary" />
</shape>
</item>
</layer-list>
Who are you trying to convince? Engineers or manager? If you are trying to convince your engineer co-workers I think your best bet is to appeal to their desire to make a high quality piece of software. There are numerous studies that show it finds bugs, and if they care about doing a good job, that should be enough for them.
If you are trying to convince management, you will most likely have to do some kind of cost/benefit reasoning saying that the cost of the defects that will be undetected is greater than the cost of writing the tests. Be sure to include intagable costs too, such as loss of customer confidence, etc.
When you are in the Command, click Create to create a new parameter; call it project_name
. Once you've created it, double click its name to add it to the command's text. You query should resemble:
SELECT Projecttname, ReleaseDate, TaskName
FROM DB_Table
WHERE Project_Name LIKE {?project_name} + '*'
AND ReleaseDate >= getdate() --assumes sql server
If desired, link the main report to the subreport on this ({?project_name}
) field. If you don't establish a link between the main and subreport, CR will prompt you for the subreport's parameter.
In versions prior to 2008, a command's parameter was only allowed to be a scalar value.
REPEAT
...
UNTIL cond
Is equivalent to
while True:
...
if cond:
break
If you only care about the local machine, you can rely on the psutil package. You can either:
Check all ports used by a specific pid:
proc = psutil.Process(pid)
print proc.connections()
Check all ports used on the local machine:
print psutil.net_connections()
It works on Windows too.
Your answer is below the perfect solution to hide to file extension in php.
<?php
$path = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
echo basename($path, ".php");
?>
Use:
trim() {
local orig="$1"
local trmd=""
while true;
do
trmd="${orig#[[:space:]]}"
trmd="${trmd%[[:space:]]}"
test "$trmd" = "$orig" && break
orig="$trmd"
done
printf -- '%s\n' "$trmd"
}
Unit test (for manual review):
#!/bin/bash
. trim.sh
enum() {
echo " a b c"
echo "a b c "
echo " a b c "
echo " a b c "
echo " a b c "
echo " a b c "
echo " a b c "
echo " a b c "
echo " a b c "
echo " a b c "
echo " a b c "
echo " a N b c "
echo "N a N b c "
echo " Na b c "
echo " a b c N "
echo " a b c N"
}
xcheck() {
local testln result
while IFS='' read testln;
do
testln=$(tr N '\n' <<<"$testln")
echo ": ~~~~~~~~~~~~~~~~~~~~~~~~~ :" >&2
result="$(trim "$testln")"
echo "testln='$testln'" >&2
echo "result='$result'" >&2
done
}
enum | xcheck
In Visual Studio, you can't just open a .cpp
file and expect it to run. You must create a project first, or open the .cpp in some existing project.
In your case, there is no project, so there is no project to build.
Go to File --> New --> Project --> Visual C++ --> Win32 Console Application
. You can uncheck "create a directory for solution". On the next page, be sure to check "Empty project".
Then, You can add .cpp
files you created outside the Visual Studio by right clicking in the Solution explorer
on folder icon "Source" and Add->Existing Item.
Obviously You can create new .cpp this way too (Add --> New). The .cpp file will be created in your project directory.
Then you can press ctrl+F5 to compile without debugging and can see output on console window.
This question already has a good answer, but I want to supplement it with some more pictures. My full answer is here.
To help me remember frame, I think of a picture frame on a wall. Just like a picture can be moved anywhere on the wall, the coordinate system of a view's frame is the superview. (wall=superview, frame=view)
To help me remember bounds, I think of the bounds of a basketball court. The basketball is somewhere within the court just like the coordinate system of the view's bounds is within the view itself. (court=view, basketball/players=content inside the view)
Like the frame, view.center is also in the coordinates of the superview.
The yellow rectangle represents the view's frame. The green rectangle represents the view's bounds. The red dot in both images represents the origin of the frame or bounds within their coordinate systems.
Frame
origin = (0, 0)
width = 80
height = 130
Bounds
origin = (0, 0)
width = 80
height = 130
Frame
origin = (40, 60) // That is, x=40 and y=60
width = 80
height = 130
Bounds
origin = (0, 0)
width = 80
height = 130
Frame
origin = (20, 52) // These are just rough estimates.
width = 118
height = 187
Bounds
origin = (0, 0)
width = 80
height = 130
This is the same as example 2, except this time the whole content of the view is shown as it would look like if it weren't clipped to the bounds of the view.
Frame
origin = (40, 60)
width = 80
height = 130
Bounds
origin = (0, 0)
width = 80
height = 130
Frame
origin = (40, 60)
width = 80
height = 130
Bounds
origin = (280, 70)
width = 80
height = 130
Again, see here for my answer with more details.
Your regex pattern should have the g modifier:
var pattern = /[somepattern]+/g;
notice the g at the end. it tells the replacer to do a global replace.
Also you dont need to use the RegExp object you can construct your pattern as above. Example pattern:
var pattern = /[0-9a-zA-Z]+/g;
a pattern is always surrounded by / on either side - with modifiers after the final /, the g modifier being the global.
EDIT: Why does it matter if pattern is a variable? In your case it would function like this (notice that pattern is still a variable):
var pattern = /[0-9a-zA-Z]+/g;
repeater.replace(pattern, "1234abc");
But you would need to change your replace function to this:
this.markup = this.markup.replace(pattern, value);
You need the following permissions in your manifest file:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
Then you can use the following in your activity class:
WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
wifiManager.setWifiEnabled(false);
Use the following to check if it's enabled or not
boolean wifiEnabled = wifiManager.isWifiEnabled()
You'll find a nice tutorial on the subject on this site.
In a nutshell, the main differences between a Promise and an Observable are as follows:
a more detailed can be found in this article
This feature was added in 1.45, demoed here.
Launch the command palette Ctrl+Shift+P
, run Publish to Github
, and follow the prompt. You will be given the choice between a private and public repository, so be careful that you choose the right one.
It may ask you to login to github. It will then prompt for the repo name (defaults to the name of the folder), and for creating a .gitignore file (defaults to empty .gitignore). Just hit enter if you are fine with the defaults. When you are done it should give you a popup notification in the bottom right with a link to the repo https://github.com/<username>/<reponame>
Minor warning: if your project already has a .gitignore file in it this process will overwrite it
use with responsive website (view in mobile or ipad)
jQuery(window).height(); // return height of browser viewport
jQuery(window).width(); // return width of browser viewport
rarely use
jQuery(document).height(); // return height of HTML document
jQuery(document).width(); // return width of HTML document
Okay adding to @null's awesome post about using the Asset Catalog.
You may need to do the following to get the App's Icon linked and working for Ad-Hoc distributions / production to be seen in Organiser, Test flight and possibly unknown AppStore locations.
After creating the Asset Catalog, take note of the name of the Launch Images and App Icon names listed in the .xassets
in Xcode.
By Default this should be
AppIcon
LaunchImage
[To see this click on your .xassets folder/icon in Xcode.] (this can be changed, so just take note of this variable for later)
What is created now each build is the following data structures in your .app:
For App Icons:
iPhone
AppIcon57x57.png
(iPhone non retina) [Notice the Icon name prefix][email protected]
(iPhone retina)And the same format for each of the other icon resolutions.
iPad
AppIcon72x72~ipad.png
(iPad non retina) AppIcon72x72@2x~ipad.png
(iPad retina)(For iPad it is slightly different postfix)
Main Problem
Now I noticed that in my Info.plist
in Xcode 5.0.1 it automatically attempted and failed to create a key for "Icon files (iOS 5)
" after completing the creation of the Asset Catalog.
If it did create a reference successfully / this may have been patched by Apple or just worked, then all you have to do is review the image names to validate the format listed above.
Final Solution:
Add the following key to you main .plist
I suggest you open your main .plist
with a external text editor such as TextWrangler rather than in Xcode to copy and paste the following key in.
<key>CFBundleIcons</key>
<dict>
<key>CFBundlePrimaryIcon</key>
<dict>
<key>CFBundleIconFiles</key>
<array>
<string>AppIcon57x57.png</string>
<string>[email protected]</string>
<string>AppIcon72x72~ipad.png</string>
<string>AppIcon72x72@2x~ipad.png</string>
</array>
</dict>
</dict>
Please Note I have only included my example resolutions, you will need to add them all.
If you want to add this Key in Xcode without an external editor, Use the following:
Icon files (iOS 5)
- DictionaryPrimary Icon
- DictionaryIcon files
- ArrayItem 0
- String = AppIcon57x57.png
And for each other item / app icon.Now when you finally archive your project the final .xcarchive payload .plist will now include the above stated icon locations to build and use.
<key>IconPaths</key>
<array>
<string>Applications/Example.app/AppIcon57x57.png</string>
<string>Applications/Example.app/[email protected]</string>
<string>Applications/Example.app/AppIcon72x72~ipad.png</string>
<string>Applications/Example.app/AppIcon72x72@2x~ipad.png</string>
</array>
Based on your comments in this answer, I do what you're trying to do like this:
module.exports = function (app, db) {
var module = {};
module.auth = function (req, res) {
// This will be available 'outside'.
// Authy stuff that can be used outside...
};
// Other stuff...
module.pickle = function(cucumber, herbs, vinegar) {
// This will be available 'outside'.
// Pickling stuff...
};
function jarThemPickles(pickle, jar) {
// This will be NOT available 'outside'.
// Pickling stuff...
return pickleJar;
};
return module;
};
I structure pretty much all my modules like that. Seems to work well for me.
When you run the Windows Command Prompt, and type in python
, it starts the Python interpreter.
Typing it again tries to interpret python
as a variable, which doesn't exist and thus won't work:
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
C:\Users\USER>python
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> python
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'python' is not defined
>>> print("interpreter has started")
interpreter has started
>>> quit() # leave the interpreter, and go back to the command line
C:\Users\USER>
If you're not doing this from the command line, and instead running the Python interpreter (python.exe or IDLE's shell) directly, you are not in the Windows Command Line, and python
is interpreted as a variable, which you have not defined.
The better approach may be to utilize the NT Service as a wrapper for your application. When the NT Service is started, your application can start in an "idle" mode waiting for the command to start (or be configured to start automatically).
Think of a car, when it's started it begins in an idle state, waiting for your command to go forward or reverse. This also allows for other benefits, such as better remote administration as you can choose how to expose your application.
You can easily redirect different parts of your shell script to a file (or several files) using sub-shells:
{
command1
command2
command3
command4
} > file1
{
command5
command6
command7
command8
} > file2
i have same problem
you can use IntentCompat
, like this :
import android.support.v4.content.IntentCompat;
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
this code work for me .
Android api 17
Just for completeness, since MySQL and Postgres have already been mentioned: With SQLite, use "pragma table_info()
"
sqlite> pragma table_info('table_name');
cid name type notnull dflt_value pk
---------- ---------- ---------- ---------- ---------- ----------
0 id integer 99 1
1 name 0 0
brew rmtree
doesn't work at all. From the links on that issue I found rmrec which actually does work. God knows why brew
doesn't have this as a native command.
brew tap ggpeti/rmrec
brew rmrec pkgname
I have tried this
C:\Users\radhason\AppData\Local\NetBeans\Cache
Press Ok button , then cache folder will be shown and delete this cache folder of netbeans.
The easiest and purest method without relying on C headers is PyYaml (documentation), which can be installed via pip install pyyaml
:
#!/usr/bin/env python
import yaml
with open("example.yaml", 'r') as stream:
try:
print(yaml.safe_load(stream))
except yaml.YAMLError as exc:
print(exc)
And that's it. A plain yaml.load()
function also exists, but yaml.safe_load()
should always be preferred unless you explicitly need the arbitrary object serialization/deserialization provided in order to avoid introducing the possibility for arbitrary code execution.
Note the PyYaml project supports versions up through the YAML 1.1 specification. If YAML 1.2 specification support is needed, see ruamel.yaml as noted in this answer.
Just index using you ind_pos
ind_pos = [1,5,7]
print (a[ind_pos])
[88 85 16]
In [55]: a = [0,88,26,3,48,85,65,16,97,83,91]
In [56]: import numpy as np
In [57]: arr = np.array(a)
In [58]: ind_pos = [1,5,7]
In [59]: arr[ind_pos]
Out[59]: array([88, 85, 16])
All the considerations made by @EdChum in 2014 are still valid, but the pandas.Dataframe.ix
method is deprecated from the version 0.0.20 of pandas. Directly from the docs:
Warning: Starting in 0.20.0, the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers.
In subsequent versions of pandas, this method has been replaced by new indexing methods pandas.Dataframe.loc and pandas.Dataframe.iloc.
If you want to learn more, in this post you can find comparisons between the methods mentioned above.
Ultimately, to date (and there does not seem to be any change in the upcoming versions of pandas from this point of view), the answer to this question is as follows:
foo = df.loc[(df['column1']==value) | (df['columns2'] == 'b') | (df['column3'] == 'c')]
What you should do is, create a Java Project, but make sure you put this file in the package file of that project, otherwise you'll encounter same error.
pytest captures the stdout from individual tests and displays them only on certain conditions, along with the summary of the tests it prints by default.
Extra summary info can be shown using the '-r' option:
pytest -rP
shows the captured output of passed tests.
pytest -rx
shows the captured output of failed tests (default behaviour).
The formatting of the output is prettier with -r than with -s.
Are you simply appending string literals? Or are you going to be appending various data types (ints, floats, etc.)?
It might be easier to abstract this out into its own function (the following assumes C99):
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
int appendToStr(char *target, size_t targetSize, const char * restrict format, ...)
{
va_list args;
char temp[targetSize];
int result;
va_start(args, format);
result = vsnprintf(temp, targetSize, format, args);
if (result != EOF)
{
if (strlen(temp) + strlen(target) > targetSize)
{
fprintf(stderr, "appendToStr: target buffer not large enough to hold additional string");
return 0;
}
strcat(target, temp);
}
va_end(args);
return result;
}
And you would use it like so:
char target[100] = {0};
...
appendToStr(target, sizeof target, "%s %d %f\n", "This is a test", 42, 3.14159);
appendToStr(target, sizeof target, "blah blah blah");
etc.
The function returns the value from vsprintf
, which in most implementations is the number of bytes written to the destination. There are a few holes in this implementation, but it should give you some ideas.
You can also add underscore.js to your project and will be able to do it in one line:
_.map($("input[name='category_ids[]']:checked"), function(el){return $(el).val()})
The selected answer will only work if there are no gaps in the sequence. However if you are using an autogenerated id, there are likely to be gaps in the sequence due to inserts that were rolled back.
This method should work if you have gaps
declare @temp (value int, primaryKey int, tempid int identity)
insert value, primarykey from mytable order by primarykey
select t1.value - t2.value from @temp t1
join @temp t2
on t1.tempid = t2.tempid - 1
Several people pointed out the specific answers for heap size with the jvm options of -Xms
and -Xms
. I want to point out that this is not the only type of memory options for the jvm. Specifically if you are get stack over flows, then you'll want to increase the size of the stack by adding an additional option like -Xss8m
.
For this problem, the jvm options of something like -Xms2g -Xmx6g -Xss8m
would be a solution.
I'm sharing this information as my google searches on how to increase jvm memory took me to this solution, and the solutions didn't work with high amounts of memory allocation. Once I figured out what the specific settings were for, I was able to google how to increase the stack size and found the missing param. :) Hope this saves others time, as it would of saved me a ton of time. :)
if you are using bigint in your database table, you can use Long in C#
I had this issue.
The way I fixed it was by completely deleting the Pod implementing and re-implementing it. Make sure to delete "Copy Pods Resources" and "Check Pods Manifest.lock" from "Build Phases" on all targets as stated here: How to remove CocoaPods from a project?
This is a shot in the dark but try putting the two operands for the AND in parentheses
On ((A = B) And (C = D))
In cases where the name attribute is different it is easiest to control the radio group via JQuery. When an option is selected use JQuery to un-select the other options.
If the above response by @Ilya Dyoshin didn't still retrieve, try to get the response into a String Object.
(For my self thought the error got solved by the code snippet by Ilya, the response retrieved was a failure(error) from the server.)
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.add(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
ResponseEntity<String> st = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
And Cast to the ResponseObject DTO (Json)
Gson g = new Gson();
DTO dto = g.fromJson(st.getBody(), DTO.class);
It is varchar
and not var_char
CREATE DATABASE IF NOT EXISTS courses;
USE courses;
CREATE TABLE IF NOT EXISTS teachers(
id INT(10) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
addr VARCHAR(255) NOT NULL,
phone INT NOT NULL
);
You should use a SQL tool to visualize possbile errors like MySQL Workbench.
For me, I defined column type as BIT (e.g. "boolean")
When I tried to set column value "1" via UI (Workbench), I was getting a "Data too long for column" error.
Turns out that there is a special syntax for setting BIT values, which is:
b'1'
You can change the class of the entire table and use the cascade in the CSS: http://jsbin.com/oyunuy/1/
To avoid any ambiguity, use the utilities methods from SwingUtilities :
SwingUtilities.isLeftMouseButton(MouseEvent anEvent)
SwingUtilities.isRightMouseButton(MouseEvent anEvent)
SwingUtilities.isMiddleMouseButton(MouseEvent anEvent)
Here is what you do in Excel 2003:
Here is what you do in Excel 2007:
Once this is done, the sheet is hidden and cannot be unhidden without the password. Make sense?
If you really need to keep some calculations secret, try this: use Access (or another Excel workbook or some other DB of your choice) to calculate what you need calculated, and export only the "unclassified" results to your Excel workbook.
If you have just installed macports just run and it should work
source ~/.bash_profile
The below css code always keep the button at the bottom of the page
position:absolute;
bottom:0;
Since you want to do it in relative positioning, you should go for margin-top:100%
position:relative;
margin-top:100%;
EDIT1: JSFiddle1
EDIT2: To place button at center of the screen,
position:relative;
left: 50%;
margin-top:50%;
Quite a busy one-liner, but here it is:
myarray
, is normalised with the max value at 1.0
.myarray
.0-255
range.np.uint8()
.Image.fromarray()
.And you're done:
from PIL import Image
from matplotlib import cm
im = Image.fromarray(np.uint8(cm.gist_earth(myarray)*255))
with plt.savefig()
:
with im.save()
:
Usually to use the library you need to install the dev version.
Try
sudo apt-get install libusb-1.0-0-dev
It is possible to get this working in VS Code and have the Cmder terminal be integrated (not pop up).
To do so:
"terminal.integrated.shell.windows": "cmd.exe"
"terminal.integrated.shellArgs.windows": ["/k", "%CMDER_ROOT%\\vendor\\init.bat"]
Actually the correct answer is on http://jsfiddle.net/HDakN/
Zoltan answer will allow user entry "(99) 9999" and then leave the field incomplete
$("#phone").mask("(99) 9999-9999?9");
$("#phone").on("blur", function() {
var last = $(this).val().substr( $(this).val().indexOf("-") + 1 );
if( last.length == 5 ) {
var move = $(this).val().substr( $(this).val().indexOf("-") + 1, 1 );
var lastfour = last.substr(1,4);
var first = $(this).val().substr( 0, 9 );
$(this).val( first + move + '-' + lastfour );
}
});?
None of the above answers worked for me using git version 1.8.3.msysgit.0 and TortoiseGit 1.8.4.0.
In my particular situation, I have to connect to the remote git repo over HTTPS, using a full blown e-mail address as username.
In this situation, wincred
did not appear to work.
Using the email address as a part of the repo URL also did not work, as the software seems to be confused by the double appearance of the '@' character in the URL.
I did manage to overcome the problem using winstore
. Here is what I did:
winstore
from http://gitcredentialstore.codeplex.com/git-credential-winstore.exe
to install it.This will copy the git-credential-winstore.exe
to a local directory and add two lines to your global .gitconfig
. You can verify this by examining your global .gitconfig
. This is easiest done via right mouse button on a folder, "TortoiseGit > Settings > Git > Edit global .gitconfig". The file should contain two lines like:
[credential]
helper = !'C:\\Users\\yourlogin\\AppData\\Roaming\\GitCredStore\\git-credential-winstore.exe'
You are now ready to go:
winstore
works. Enter the correct authentication and the pull should succeed.Done!
Enjoy your interactions with the remote repo while winstore
takes care of the authentication.
(*) Alternatively, if you don't like the blank selection in the TortoiseGit Credential settings helper pull down menu, you can use the "Advanced" option:
Enter the Helper path as below. Note: a regular Windows path notation (e.g. "C:\Users...") will not work here, you have to replicate the exact line that installing winstore
created in the global .gitconf
without the "helper =" bit.
!'C:\\Users\\yourlogin\\AppData\\Roaming\\GitCredStore\\git-credential-winstore.exe'
Click the "Add New/Save" button
<?php
set_time_limit(0);
//This is the file where we save the information
$fp = fopen (dirname(__FILE__) . '/localfile.tmp', 'w+');
//Here is the file we are downloading, replace spaces with %20
$ch = curl_init(str_replace(" ","%20",$url));
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
// write curl response to file
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// get curl response
curl_exec($ch);
curl_close($ch);
fclose($fp);
?>
Open a new worksheet on the related instance (Alt-F10)
and run the following query
SELECT view_name, owner
FROM sys.all_views
ORDER BY owner, view_name
Use control
+option
+O
to auto-import the package or auto remove unused packages on MacOS
For Swift 4
I used @Passkit's logic but i had to update as per Swift 4
Step.1 Created extension for String Class
import UIKit
extension String
{
var parseJSONString: AnyObject?
{
let data = self.data(using: String.Encoding.utf8, allowLossyConversion: false)
if let jsonData = data
{
// Will return an object or nil if JSON decoding fails
do
{
let message = try JSONSerialization.jsonObject(with: jsonData, options:.mutableContainers)
if let jsonResult = message as? NSMutableArray
{
print(jsonResult)
return jsonResult //Will return the json array output
}
else
{
return nil
}
}
catch let error as NSError
{
print("An error occurred: \(error)")
return nil
}
}
else
{
// Lossless conversion of the string was not possible
return nil
}
}
}
Step.2 This is how I used in my view controller
var jsonString = "[\n" +
"{\n" +
"\"id\":72,\n" +
"\"name\":\"Batata Cremosa\",\n" +
"},\n" +
"{\n" +
"\"id\":183,\n" +
"\"name\":\"Caldeirada de Peixes\",\n" +
"},\n" +
"{\n" +
"\"id\":76,\n" +
"\"name\":\"Batata com Cebola e Ervas\",\n" +
"},\n" +
"{\n" +
"\"id\":56,\n" +
"\"name\":\"Arroz de forma\",\n" +
"}]"
//Convert jsonString to jsonArray
let json: AnyObject? = jsonString.parseJSONString
print("Parsed JSON: \(json!)")
print("json[2]: \(json![2])")
All credit goes to original user, I just updated for latest swift version
I find the FileSystemObject with a TxtStream the easiest way to read files
Dim fso As FileSystemObject: Set fso = New FileSystemObject
Set txtStream = fso.OpenTextFile(filePath, ForReading, False)
Then with this txtStream
object you have all sorts of tools which intellisense picks up (unlike using the FreeFile()
method) so there is less guesswork. Plus you don' have to assign a FreeFile and hope it is actually still free since when you assigned it.
You can read a file like:
Do While Not txtStream.AtEndOfStream
txtStream.ReadLine
Loop
txtStream.Close
NOTE: This requires a reference to Microsoft Scripting Runtime.
Some modern browsers have support for parsing JSON into a native object:
var var1 = '{"cols": [{"i" ....... 66}]}';
var result = JSON.parse(var1);
For the browsers that don't support it, you can download json2.js from json.org for safe parsing of a JSON object. The script will check for native JSON support and if it doesn't exist, provide the JSON global object instead. If the faster, native object is available it will just exit the script leaving it intact. You must, however, provide valid JSON or it will throw an error — you can check the validity of your JSON with http://jslint.com or http://jsonlint.com.
The Maven profile and the Spring profile are two completely different things. Your pom.xml defines spring.profiles.active
variable which is available in the build process, but not at runtime. That is why only the default profile is activated.
How to bind Maven profile with Spring?
You need to pass the build variable to your application so that it is available when it is started.
Define a placeholder in your application.properties
:
[email protected]@
The @spring.profiles.active@
variable must match the declared property from the Maven profile.
Enable resource filtering in you pom.xml:
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
…
</build>
When the build is executed, all files in the src/main/resources
directory will be processed by Maven and the placeholder in your application.properties
will be replaced with the variable you defined in your Maven profile.
For more details you can go to my post where I described this use case.
Since you want to call a non-static method from main, you just need to create an object of that class consisting non-static method and then you will be able to call the method using objectname.methodname(); But if you write the method as static then you won't need to create object and you will be able to call the method using methodname(); from main. And this will be more efficient as it will take less memory than the object created without static method.
I had the same problem. I removed mySQL completely, and reinstall it using homebrew.
Maybe you are out of inodes. Try df -i
2591792 136322 2455470 6% /home
/dev/sdb1 1887488 1887488 0 100% /data
Disk used 6% but inode table full.
You can easily get what you want by adding the line in ax:
ax.plot([], [], '-r', label = 'temp')
or
ax.plot(np.nan, '-r', label = 'temp')
This would plot nothing but add a label to legend of ax.
I think this is a much easier way. It's not necessary to track lines automatically when you have only a few lines in the second axes, as fixing by hand like above would be quite easy. Anyway, it depends on what you need.
The whole code is as below:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('mathtext', default='regular')
time = np.arange(22.)
temp = 20*np.random.rand(22)
Swdown = 10*np.random.randn(22)+40
Rn = 40*np.random.rand(22)
fig = plt.figure()
ax = fig.add_subplot(111)
ax2 = ax.twinx()
#---------- look at below -----------
ax.plot(time, Swdown, '-', label = 'Swdown')
ax.plot(time, Rn, '-', label = 'Rn')
ax2.plot(time, temp, '-r') # The true line in ax2
ax.plot(np.nan, '-r', label = 'temp') # Make an agent in ax
ax.legend(loc=0)
#---------------done-----------------
ax.grid()
ax.set_xlabel("Time (h)")
ax.set_ylabel(r"Radiation ($MJ\,m^{-2}\,d^{-1}$)")
ax2.set_ylabel(r"Temperature ($^\circ$C)")
ax2.set_ylim(0, 35)
ax.set_ylim(-20,100)
plt.show()
The plot is as below:
Update: add a better version:
ax.plot(np.nan, '-r', label = 'temp')
This will do nothing while plot(0, 0)
may change the axis range.
One extra example for scatter
ax.scatter([], [], s=100, label = 'temp') # Make an agent in ax
ax2.scatter(time, temp, s=10) # The true scatter in ax2
ax.legend(loc=1, framealpha=1)
C# version:
public class UrlShortener
{
private static String ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
private static int BASE = 62;
public static String encode(int num)
{
StringBuilder sb = new StringBuilder();
while ( num > 0 )
{
sb.Append( ALPHABET[( num % BASE )] );
num /= BASE;
}
StringBuilder builder = new StringBuilder();
for (int i = sb.Length - 1; i >= 0; i--)
{
builder.Append(sb[i]);
}
return builder.ToString();
}
public static int decode(String str)
{
int num = 0;
for ( int i = 0, len = str.Length; i < len; i++ )
{
num = num * BASE + ALPHABET.IndexOf( str[(i)] );
}
return num;
}
}
I tried a number of the suggestions above without success.
I use the NuGeT packages. The are (for some reason) multiple named version (font-awesome, fontawesome, font.awesome, etc.)
For what it's worth: I removed all the version installed and then only installed the latest version of font.awesome. font.awesome just worked without the need to tweak or configure anything.
I assume there are a number of things are missing from the other named versions.
Try using ifconfig -a
. Look for "inet xxx.xxx.xxx.xxx", that is your IP address
Adding on to what Hubro said, apparently get_highest_row()
has been deprecated. Using the max_row
and max_column
properties returns the row and column count. For example:
wb = load_workbook(path, use_iterators=True)
sheet = wb.worksheets[0]
row_count = sheet.max_row
column_count = sheet.max_column
You could look into this: http://www.codeproject.com/KB/showcase/pdfrasterizer.aspx It's not completely free, but it looks very nice.
Alex
You could also use https://github.com/googlei18n/libphonenumber. Here is an example:
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
String s = "18005551234";
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
Phonenumber.PhoneNumber phoneNumber = phoneUtil.parse(s, Locale.US.getCountry());
String formatted = phoneUtil.format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.NATIONAL);
Here you can get the library on your classpath: http://mvnrepository.com/artifact/com.googlecode.libphonenumber/libphonenumber
In addition to the above posts, i'd like to point out that "man ls" will give you a nice manual about the "ls" ( List " command.
Also, using ls -la myFile will list & show all the facts about that file.
parseFloat
parses according to the JavaScript definition of a decimal literal, not your locale's definition. (E.g., parseFloat
is not locale-aware.) Decimal literals in JavaScript use .
for the decimal point.
Since it's just false and json object, why don't you check whether it's false, otherwise it must be json.
if(ret == false || ret == "false") {
// json
}
In short, size_t
is never negative, and it maximizes performance because it's typedef'd to be the unsigned integer type that's big enough -- but not too big -- to represent the size of the largest possible object on the target platform.
Sizes should never be negative, and indeed size_t
is an unsigned type. Also, because size_t
is unsigned, you can store numbers that are roughly twice as big as in the corresponding signed type, because we can use the sign bit to represent magnitude, like all the other bits in the unsigned integer. When we gain one more bit, we are multiplying the range of numbers we can represents by a factor of about two.
So, you ask, why not just use an unsigned int
? It may not be able to hold big enough numbers. In an implementation where unsigned int
is 32 bits, the biggest number it can represent is 4294967295
. Some processors, such as the IP16L32, can copy objects larger than 4294967295
bytes.
So, you ask, why not use an unsigned long int
? It exacts a performance toll on some platforms. Standard C requires that a long
occupy at least 32 bits. An IP16L32 platform implements each 32-bit long as a pair of 16-bit words. Almost all 32-bit operators on these platforms require two instructions, if not more, because they work with the 32 bits in two 16-bit chunks. For example, moving a 32-bit long usually requires two machine instructions -- one to move each 16-bit chunk.
Using size_t
avoids this performance toll. According to this fantastic article, "Type size_t
is a typedef that's an alias for some unsigned integer type, typically unsigned int
or unsigned long
, but possibly even unsigned long long
. Each Standard C implementation is supposed to choose the unsigned integer that's big enough--but no bigger than needed--to represent the size of the largest possible object on the target platform."
Also, if you have two subsequent words in regular text and you want to avoid a line break between them, you can use the ~ character.
For example:
As we can see in Fig.~\ref{BlaBla}, there is nothing interesting to see. A~better place..
This can ensure that you don't have a line starting with a figure number (without the Fig. part) or with an uppercase A.
In my case... with MySQL:
SELECT ... GROUP BY TIMESTAMPADD(HOUR, HOUR(columName), DATE(columName))
You can also convert by creating a dictionary of elements and then directly converting to a data frame:
import xml.etree.ElementTree as ET
import pandas as pd
# Contents of test.xml
# <?xml version="1.0" encoding="utf-8"?> <tags> <row Id="1" TagName="bayesian" Count="4699" ExcerptPostId="20258" WikiPostId="20257" /> <row Id="2" TagName="prior" Count="598" ExcerptPostId="62158" WikiPostId="62157" /> <row Id="3" TagName="elicitation" Count="10" /> <row Id="5" TagName="open-source" Count="16" /> </tags>
root = ET.parse('test.xml').getroot()
tags = {"tags":[]}
for elem in root:
tag = {}
tag["Id"] = elem.attrib['Id']
tag["TagName"] = elem.attrib['TagName']
tag["Count"] = elem.attrib['Count']
tags["tags"]. append(tag)
df_users = pd.DataFrame(tags["tags"])
df_users.head()
When I tried to execute my stored procedure I had the same problem because the size of the column that I need to add some data is shorter than the data I want to add.
You can increase the size of the column data type or reduce the length of your data.
Apple does not allow:
CGImageRef UIGetScreenImage();
Applications should take a screenshot using the drawRect
method as specified in:
http://developer.apple.com/library/ios/#qa/qa2010/qa1703.html
Here's the one that is working for me.
from datetime import datetime
date_format = "%H:%M:%S"
# You could also pass datetime.time object in this part and convert it to string.
time_start = str('09:00:00')
time_end = str('18:00:00')
# Then get the difference here.
diff = datetime.strptime(time_end, date_format) - datetime.strptime(time_start, date_format)
# Get the time in hours i.e. 9.60, 8.5
result = diff.seconds / 3600;
Hope this helps!
Since you have master page and your control is in content place holder, Your control id will be generated different in client side. you need to do like...
var TestVar = document.getElementById('<%= txt_model_code.ClientID %>').value;
Javascript runs on client side and to get value you have to provide client id of your control
Combine JS & CSS :
button{
/* 1st state */
}
button:hover{
/* hover state */
}
button:active{
/* click state */
}
button.active{
/* after click state */
}
jQuery('button').click(function(){
jQuery(this).toggleClass('active');
});
The below code gets the full path, where the anchor points:
document.getElementById("aaa").href; // http://example.com/sec/IF00.html
while the one below gets the value of the href
attribute:
document.getElementById("aaa").getAttribute("href"); // sec/IF00.html
Or if the Boolean value is not been returned, you can do something like this:
bool boolValue = (returnValue == "1");
When you use --user
option with pip, the package gets installed in user's folder instead of global folder and you won't need to run pip command with admin privileges.
The location of user's packages folder can be found using:
python -m site --user-site
This will print something like:
C:\Users\%USERNAME%\AppData\Roaming\Python\Python35\site-packages
When you don't use --user
option with pip, the package gets installed in global folder given by:
python -c "import site; print(site.getsitepackages())"
This will print something like:
['C:\\Program Files\\Anaconda3', 'C:\\Program Files\\Anaconda3\\lib\\site-packages'
Note: Above printed values are for On Windows 10 with Anaconda 4.x installed with defaults.
Try setting maxReceivedMessageSize on the server too, e.g. to 4MB:
<binding name="MyService.MyServiceBinding"
maxReceivedMessageSize="4194304">
The main reason the default (65535 I believe) is so low is to reduce the risk of Denial of Service (DoS) attacks. You need to set it bigger than the maximum request size on the server, and the maximum response size on the client. If you're in an Intranet environment, the risk of DoS attacks is probably low, so it's probably safe to use a value much higher than you expect to need.
By the way a couple of tips for troubleshooting problems connecting to WCF services:
Enable tracing on the server as described in this MSDN article.
Use an HTTP debugging tool such as Fiddler on the client to inspect the HTTP traffic.
I would just raise ValueError, unless you need a more specific exception..
def import_to_orm(name, save=False, recurse=False):
if recurse and not save:
raise ValueError("save must be True if recurse is True")
There's really no point in doing class BadValueError(ValueError):pass
- your custom class is identical in use to ValueError, so why not use that?
Very simple stuff. Before returning the tableview Cell use the style property of the table view cell.
Just write this line of code before returning table view cell
cell.selectionStyle = .none
Removing double-quotes
solve my problem, now its:
DEBUG_STORE_PASSWORD=androiddebug
DEBUG_KEY_ALIAS=androiddebug
DEBUG_KEY_PASSWORD=androiddebug
I would use:
CAST
(
CAST(YEAR(DATEFIELD) as varchar(4)) + '/' CAST(MM(DATEFIELD) as varchar(2)) + '/' CAST(DD(DATEFIELD) as varchar(2)) as datetime
)
Thus effectively creating a new field from the date field you already have.
This is my version referring @Virako 's code snippet
def adjust_column_width_from_col(ws, min_row, min_col, max_col):
column_widths = []
for i, col in \
enumerate(
ws.iter_cols(min_col=min_col, max_col=max_col, min_row=min_row)
):
for cell in col:
value = cell.value
if value is not None:
if isinstance(value, str) is False:
value = str(value)
try:
column_widths[i] = max(column_widths[i], len(value))
except IndexError:
column_widths.append(len(value))
for i, width in enumerate(column_widths):
col_name = get_column_letter(min_col + i)
value = column_widths[i] + 2
ws.column_dimensions[col_name].width = value
And how to use is as follows,
adjust_column_width_from_col(ws, 1,1, ws.max_column)
You can try this
$scope.$watch('tags ',function(){
$scope.tags = $filter('lowercase')($scope.tags);
});
You can search for "Ajax Behavior Events" in PrimeFaces User's Guide, and you will find plenty of them for all supported components. That's also what PrimeFaces lead Optimus Prime suggest to do in this related question at the PrimeFaces forum <p:ajax>
event list?
There is no onblur
event, that's the HTML attribute name, but there is a blur
event. It's just without the "on" prefix like as the HTML attribute name. You can also look at all "on*" attributes of the tag documentation of the component in question to see which are all available, e.g. <p:inputText>
.
You have to use while
since foreach
does not know about index. Below is an example code.
int counter = 0;
string line;
Console.Write("Input your search text: ");
var text = Console.ReadLine();
System.IO.StreamReader file =
new System.IO.StreamReader("SampleInput1.txt");
while ((line = file.ReadLine()) != null)
{
if (line.Contains(text))
{
break;
}
counter++;
}
Console.WriteLine("Line number: {0}", counter);
file.Close();
Console.ReadLine();
If you're not in an ipython notebook (like the OP), you can also just declare the size when you declare the figure:
width = 12
height = 12
plt.figure(figsize=(width, height))
Use example with from the post of Szilágyi Donát.
I use two querys, one to know what roles I have, excluding connect grant:
SELECT * FROM USER_ROLE_PRIVS WHERE GRANTED_ROLE != 'CONNECT'; -- Roles of the actual Oracle Schema
Know I like to find what privileges/roles my schema/user have; examples of my roles ROLE_VIEW_PAYMENTS & ROLE_OPS_CUSTOMERS. But to find the tables/objecst of an specific role I used:
SELECT * FROM ALL_TAB_PRIVS WHERE GRANTEE='ROLE_OPS_CUSTOMERS'; -- Objects granted at role.
The owner schema for this example could be PRD_CUSTOMERS_OWNER (or the role/schema inself).
Regards.
Why do like tuples? It's like anonymous types: no names. Can not understand structure of data.
I like classic classes
class FoodItem
{
public int Position { get; set; }
public string Name { get; set; }
}
List<FoodItem> list = new List<FoodItem>
{
new FoodItem { Position = 1, Name = "apple" },
new FoodItem { Position = 2, Name = "kiwi" }
};
I came across this question as I had exact same problem. Although accepted answer works good but with matplotlib version 2.1.0
, it is pretty straight forward to have two scatter plots in one plot without using a reference to Axes
import matplotlib.pyplot as plt
plt.scatter(x,y, c='b', marker='x', label='1')
plt.scatter(x, y, c='r', marker='s', label='-1')
plt.legend(loc='upper left')
plt.show()
Instructions for Tortoise SVN
Navigate to the directory where you see this error. If you do not have any changes perform the following
a. Right click and do a 'Revert'
b. Select all the files
c. Then update the directory again
For current ActiveRecord (4.2.4+) there is a method to_hash
on the Result
object that returns an array of hashes. You can then map over it and convert to symbolized hashes:
# Get an array of hashes representing the result (column => value):
result.to_hash
# => [{"id" => 1, "title" => "title_1", "body" => "body_1"},
{"id" => 2, "title" => "title_2", "body" => "body_2"},
...
]
result.to_hash.map(&:symbolize_keys)
# => [{:id => 1, :title => "title_1", :body => "body_1"},
{:id => 2, :title => "title_2", :body => "body_2"},
...
]
Yes, it is because you are using auto layout. Setting the view frame and resizing mask will not work.
You should read Working with Auto Layout Programmatically and Visual Format Language.
You will need to get the current constraints, add the text field, adjust the contraints for the text field, then add the correct constraints on the text field.
$('.btnMedio').click(function(event) {
// Preventing default action of the event
event.preventDefault();
// Getting the height of the document
var n = $(document).height();
$('html, body').animate({ scrollTop: n }, 50);
// | |
// | --- duration (milliseconds)
// ---- distance from the top
});
For reference, here is a minimal implementation using Java 8 :
@Override
public void start(Stage mainStage) throws Exception {
Scene scene = new Scene(new Region());
mainStage.setWidth(640);
mainStage.setHeight(480);
mainStage.setScene(scene);
//this makes all stages close and the app exit when the main stage is closed
mainStage.setOnCloseRequest(e -> Platform.exit());
//add real stuff to the scene...
//open secondary stages... etc...
}
I just had this error when I opened a (quite) old project, created in Xcode 4~ish, in Xcode 6.4. While the linked Frameworks were visible in the Project sidebar, I overlooked that there were no linked libraries in the Target Build Phases tab. Once I fixed that, it compiled fine.
SELECT CONVERT(date, GETDATE())
A standard Java HashMap cannot store multiple values per key, any new entry you add will overwrite the previous one.
Warning: A component is changing an uncontrolled input of type text to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.
Solution : Check if value is not undefined
React / Formik / Bootstrap / TypeScript
example :
{ values?.purchaseObligation.remainingYear ?
<Input
tag={Field}
name="purchaseObligation.remainingYear"
type="text"
component="input"
/> : null
}
The main difference between name()
and toString()
is that name()
is a final
method, so it cannot be overridden. The toString()
method returns the same value that name()
does by default, but toString()
can be overridden by subclasses of Enum.
Therefore, if you need the name of the field itself, use name()
. If you need a string representation of the value of the field, use toString()
.
For instance:
public enum WeekDay {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY;
public String toString() {
return name().charAt(0) + name().substring(1).toLowerCase();
}
}
In this example,
WeekDay.MONDAY.name()
returns "MONDAY", and
WeekDay.MONDAY.toString()
returns "Monday".
WeekDay.valueOf(WeekDay.MONDAY.name())
returns WeekDay.MONDAY
, but WeekDay.valueOf(WeekDay.MONDAY.toString())
throws an IllegalArgumentException
.
An observable allows you to subscribe only whereas a subject allows you to both publish and subscribe.
So a subject allows your services to be used as both a publisher and a subscriber.
As of now, I'm not so good at Observable
so I'll share only an example of Subject
.
Let's understand better with an Angular CLI example. Run the below commands:
npm install -g @angular/cli
ng new angular2-subject
cd angular2-subject
ng serve
Replace the content of app.component.html
with:
<div *ngIf="message">
{{message}}
</div>
<app-home>
</app-home>
Run the command ng g c components/home
to generate the home component. Replace the content of home.component.html
with:
<input type="text" placeholder="Enter message" #message>
<button type="button" (click)="setMessage(message)" >Send message</button>
#message
is the local variable here. Add a property message: string;
to the app.component.ts
's class.
Run this command ng g s service/message
. This will generate a service at src\app\service\message.service.ts
. Provide this service to the app.
Import Subject
into MessageService
. Add a subject too. The final code shall look like this:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class MessageService {
public message = new Subject<string>();
setMessage(value: string) {
this.message.next(value); //it is publishing this value to all the subscribers that have already subscribed to this message
}
}
Now, inject this service in home.component.ts
and pass an instance of it to the constructor. Do this for app.component.ts
too. Use this service instance for passing the value of #message
to the service function setMessage
:
import { Component } from '@angular/core';
import { MessageService } from '../../service/message.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent {
constructor(public messageService:MessageService) { }
setMessage(event) {
console.log(event.value);
this.messageService.setMessage(event.value);
}
}
Inside app.component.ts
, subscribe and unsubscribe (to prevent memory leaks) to the Subject
:
import { Component, OnDestroy } from '@angular/core';
import { MessageService } from './service/message.service';
import { Subscription } from 'rxjs/Subscription';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
message: string;
subscription: Subscription;
constructor(public messageService: MessageService) { }
ngOnInit() {
this.subscription = this.messageService.message.subscribe(
(message) => {
this.message = message;
}
);
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
That's it.
Now, any value entered inside #message
of home.component.html
shall be printed to {{message}}
inside app.component.html
As I outline in this other answer here on StackOverflow, you can do this by timing the download of files of various sizes (start small, ramp up if the connection seems to allow it), ensuring through cache headers and such that the file is really being read from the remote server and not being retrieved from cache. This doesn't necessarily require that you have a server of your own (the files could be coming from S3 or similar), but you will need somewhere to get the files from in order to test connection speed.
That said, point-in-time bandwidth tests are notoriously unreliable, being as they are impacted by other items being downloaded in other windows, the speed of your server, links en route, etc., etc. But you can get a rough idea using this sort of technique.
If you don't have an id on the image but have a parent div this is also a technique you can use.
<div id="myDiv"><img src="http://www.example.com/image.png"></div>
var myVar = document.querySelectorAll('#myDiv img')[0].src
I'm using Visual Studio 2015. To stop build you can follow:
You can download from below link. ftp://ftp.comtrol.com/dev_mstr/sdk/other/1800136.tar.gz After downloading just extract the image and install.
def datetime_to_epoch(d1):
# create 1,1,1970 in same timezone as d1
d2 = datetime(1970, 1, 1, tzinfo=d1.tzinfo)
time_delta = d1 - d2
ts = int(time_delta.total_seconds())
return ts
def epoch_to_datetime_string(ts, tz_name="UTC"):
x_timezone = timezone(tz_name)
d1 = datetime.fromtimestamp(ts, x_timezone)
x = d1.strftime("%d %B %Y %H:%M:%S")
return x
temp = bankAccNos.contains(no) ? 1 : 2;
STR_TO_DATE allows you to do this, and it has a format argument.
echo $date = date('H:i:s', strtotime('13:00:00 + 30 minutes') );
13:00:00 - any inputted time
30 minutes - any interval you wish (20 hours, 10 minutes, 1 seconds etc...)
If you try to decrypt PKCS5-padded data with the wrong key, and then unpad it (which is done by the Cipher class automatically), you most likely will get the BadPaddingException (with probably of slightly less than 255/256, around 99.61%), because the padding has a special structure which is validated during unpad and very few keys would produce a valid padding.
So, if you get this exception, catch it and treat it as "wrong key".
This also can happen when you provide a wrong password, which then is used to get the key from a keystore, or which is converted into a key using a key generation function.
Of course, bad padding can also happen if your data is corrupted in transport.
That said, there are some security remarks about your scheme:
For password-based encryption, you should use a SecretKeyFactory and PBEKeySpec instead of using a SecureRandom with KeyGenerator. The reason is that the SecureRandom could be a different algorithm on each Java implementation, giving you a different key. The SecretKeyFactory does the key derivation in a defined manner (and a manner which is deemed secure, if you select the right algorithm).
Don't use ECB-mode. It encrypts each block independently, which means that identical plain text blocks also give always identical ciphertext blocks.
Preferably use a secure mode of operation, like CBC (Cipher block chaining) or CTR (Counter). Alternatively, use a mode which also includes authentication, like GCM (Galois-Counter mode) or CCM (Counter with CBC-MAC), see next point.
You normally don't want only confidentiality, but also authentication, which makes sure the message is not tampered with. (This also prevents chosen-ciphertext attacks on your cipher, i.e. helps for confidentiality.) So, add a MAC (message authentication code) to your message, or use a cipher mode which includes authentication (see previous point).
DES has an effective key size of only 56 bits. This key space is quite small, it can be brute-forced in some hours by a dedicated attacker. If you generate your key by a password, this will get even faster. Also, DES has a block size of only 64 bits, which adds some more weaknesses in chaining modes. Use a modern algorithm like AES instead, which has a block size of 128 bits, and a key size of 128 bits (for the standard variant).