You can increase the Heap Size by passing JVM parameters -Xms and -Xmx like below:
For Jar Files:
java -jar -Xms4096M -Xmx6144M jarFilePath.jar
For Java Files:
java -Xms4096M -Xmx6144M ClassName
The above parameters increase the InitialHeapSize (-Xms) to 4GB (4096 MB) and MaxHeapSize(-Xmx) to 6GB (6144 MB).
But, the Young Generation Heap Size will remain same and the additional HeapSize will be added to the Old Generation Heap Size. To equalize the size of Young Gen Heap and Old Gen Heap, use -XX:NewRatio=1 -XX:-UseAdaptiveSizePolicy params.
java -jar -Xms4096M -Xmx6144M -XX:NewRatio=1 -XX:-UseAdaptiveSizePolicy pathToJarFile.jar
-XX:NewRatio = Old Gen Heap Size : Young Gen HeapSize (You can play with this ratio to get your desired ratio).
There is no need to either call non-portable APIs like sendfile
, or shell out to external utilities. The same method that worked back in the 70s still works now:
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
int cp(const char *to, const char *from)
{
int fd_to, fd_from;
char buf[4096];
ssize_t nread;
int saved_errno;
fd_from = open(from, O_RDONLY);
if (fd_from < 0)
return -1;
fd_to = open(to, O_WRONLY | O_CREAT | O_EXCL, 0666);
if (fd_to < 0)
goto out_error;
while (nread = read(fd_from, buf, sizeof buf), nread > 0)
{
char *out_ptr = buf;
ssize_t nwritten;
do {
nwritten = write(fd_to, out_ptr, nread);
if (nwritten >= 0)
{
nread -= nwritten;
out_ptr += nwritten;
}
else if (errno != EINTR)
{
goto out_error;
}
} while (nread > 0);
}
if (nread == 0)
{
if (close(fd_to) < 0)
{
fd_to = -1;
goto out_error;
}
close(fd_from);
/* Success! */
return 0;
}
out_error:
saved_errno = errno;
close(fd_from);
if (fd_to >= 0)
close(fd_to);
errno = saved_errno;
return -1;
}
Below code utilizes System.Drawing.Bitmap
to load the image.
using System.Drawing;
using System.Drawing.Imaging;
public IActionResult Get()
{
string filename = "Image/test.jpg";
var bitmap = new Bitmap(filename);
var ms = new System.IO.MemoryStream();
bitmap.Save(ms, ImageFormat.Jpeg);
ms.Position = 0;
return new FileStreamResult(ms, "image/jpeg");
}
Another option is to use linear-gradient()
to cover up the edges of your image. Note that this is a stupid solution, so I'm not going to put much effort into explaining it...
.flair {_x000D_
min-width: 50px; /* width larger than sprite */_x000D_
text-indent: 60px;_x000D_
height: 25px;_x000D_
display: inline-block;_x000D_
background:_x000D_
linear-gradient(#F00, #F00) 50px 0/999px 1px repeat-y,_x000D_
url('https://championmains.github.io/dynamicflairs/riven/spritesheet.png') #F00;_x000D_
}_x000D_
_x000D_
.flair-classic {_x000D_
background-position: 50px 0, 0 -25px;_x000D_
}_x000D_
_x000D_
.flair-r2 {_x000D_
background-position: 50px 0, -50px -175px;_x000D_
}_x000D_
_x000D_
.flair-smite {_x000D_
text-indent: 35px;_x000D_
background-position: 25px 0, -50px -25px;_x000D_
}
_x000D_
<img src="https://championmains.github.io/dynamicflairs/riven/spritesheet.png" alt="spritesheet" /><br />_x000D_
<br />_x000D_
<span class="flair flair-classic">classic sprite</span><br /><br />_x000D_
<span class="flair flair-r2">r2 sprite</span><br /><br />_x000D_
<span class="flair flair-smite">smite sprite</span><br /><br />
_x000D_
I'm using this method on this page: https://championmains.github.io/dynamicflairs/riven/ and can't use ::before
or ::after
elements because I'm already using them for another hack.
Remember set sendfile off;
or cache headers doesn't work.
I use this snipped:
location / {
index index.php index.html index.htm;
try_files $uri $uri/ =404; #.s. el /index.html para html5Mode de angular
#.s. kill cache. use in dev
sendfile off;
add_header Last-Modified $date_gmt;
add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
if_modified_since off;
expires off;
etag off;
proxy_no_cache 1;
proxy_cache_bypass 1;
}
Here's another approach using Vuetify grid
system available in Vuetify 2.x
: https://vuetifyjs.com/en/components/grids
<v-container>
<v-row align="center">
Hello I am center to vertically using "grid".
</v-row>
</v-container>
You can get the server port from the
HttpServletRequest
@Autowired
private HttpServletRequest request;
@GetMapping(value = "/port")
public Object getServerPort() {
System.out.println("I am from " + request.getServerPort());
return "I am from " + request.getServerPort();
}
I think this single awk call is equivalent to your grep|grep|awk|awk
pipeline: please test it. Your last awk command appears to change nothing at all.
The problem with COUNTER is that the while loop is running in a subshell, so any changes to the variable vanish when the subshell exits. You need to access the value of COUNTER in that same subshell. Or take @DennisWilliamson's advice, use a process substitution, and avoid the subshell altogether.
awk '
/GET \/log_/ && /upstream timed out/ {
split($0, a, ", ")
split(a[2] FS a[4] FS $0, b)
print "http://example.com" b[5] "&ip=" b[2] "&date=" b[7] "&time=" b[8] "&end=1"
}
' | {
while read WFY_URL
do
echo $WFY_URL #Some more action
(( COUNTER++ ))
done
echo $COUNTER
}
By far the nicest and simplest DateTime picker option is http://trentrichardson.com/examples/timepicker/.
It is an extension of the jQuery UI Datepicker so it will support the same themes as well it works very much the same way, similar syntax, etc. This should be packaged with the jQuery UI imo.
You can approach it from either an "allow list" or a "block list" way:
// Block list
// Remove the values you don't want
var result = _.omit(credentials, ['age']);
// Allow list
// Only allow certain values
var result = _.pick(credentials, ['fname', 'lname']);
If it's reusable business logic, you can partial it out as well:
// Partial out a "block list" version
var clean = _.partial(_.omit, _, ['age']);
// and later
var result = clean(credentials);
A similar approach can be achieved without Lodash:
const transform = (obj, predicate) => {
return Object.keys(obj).reduce((memo, key) => {
if(predicate(obj[key], key)) {
memo[key] = obj[key]
}
return memo
}, {})
}
const omit = (obj, items) => transform(obj, (value, key) => !items.includes(key))
const pick = (obj, items) => transform(obj, (value, key) => items.includes(key))
// Partials
// Lazy clean
const cleanL = (obj) => omit(obj, ['age'])
// Guarded clean
const cleanG = (obj) => pick(obj, ['fname', 'lname'])
// "App"
const credentials = {
fname:"xyz",
lname:"abc",
age:23
}
const omitted = omit(credentials, ['age'])
const picked = pick(credentials, ['age'])
const cleanedL = cleanL(credentials)
const cleanedG = cleanG(credentials)
Lets look at ways to reference the image.
Back a directory
../
Folder in a directory:
foldername/
File in a directory
imagename.jpg
Now, lets combine them with the addresses you specified.
/Resources/views/Default/index.html
/Resources/public/images/iwojimaflag.jpg
The first common directory referenced from the html file is three back:
../../../
It is in within two folders in that:
../../../public/images/
And you've reached the image:
../../../public/images/iwojimaflag.jpg
Note: This is assuming you are accessing a page at domain.com/Resources/views/Default/index.html as you specified in your comment.
If you can't make DNode serializable a good solution would be to add "transient" to the variable.
Example:
public static transient DNode dNode = null;
This will ignore the variable when using Intent.putExtra(...).
Use LinkedList
instead. Than, you can create an array if necessary.
I did quite a bit of investigation on that topic recently since I was not satisfied with the many libraries I found out there.
I ended up developing a library to address this, it is named valid8. As explained in the documentation, it is for value validation mostly (although it comes bundled with simple type validation functions too), and you might wish to associate it with a PEP484-based type checker such as enforce or pytypes.
This is how you would perform validation with valid8
alone (and mini_lambda
actually, to define the validation logic - but it is not mandatory) in your case:
# for type validation
from numbers import Integral
from valid8 import instance_of
# for value validation
from valid8 import validate_arg
from mini_lambda import x, s, Len
@validate_arg('a', instance_of(Integral))
@validate_arg('b', (0 < x) & (x < 10))
@validate_arg('c', instance_of(str), Len(s) > 0)
def my_function(a: Integral, b, c: str):
"""an example function I'd like to check the arguments of."""
# check that a is an int
# check that 0 < b < 10
# check that c is not an empty string
# check that it works
my_function(0.2, 1, 'r') # InputValidationError for 'a' HasWrongType: Value should be an instance of <class 'numbers.Integral'>. Wrong value: [0.2].
my_function(0, 0, 'r') # InputValidationError for 'b' [(x > 0) & (x < 10)] returned [False]
my_function(0, 1, 0) # InputValidationError for 'c' Successes: [] / Failures: {"instance_of_<class 'str'>": "HasWrongType: Value should be an instance of <class 'str'>. Wrong value: [0]", 'len(s) > 0': "TypeError: object of type 'int' has no len()"}.
my_function(0, 1, '') # InputValidationError for 'c' Successes: ["instance_of_<class 'str'>"] / Failures: {'len(s) > 0': 'False'}
And this is the same example leveraging PEP484 type hints and delegating type checking to enforce
:
# for type validation
from numbers import Integral
from enforce import runtime_validation, config
config(dict(mode='covariant')) # type validation will accept subclasses too
# for value validation
from valid8 import validate_arg
from mini_lambda import x, s, Len
@runtime_validation
@validate_arg('b', (0 < x) & (x < 10))
@validate_arg('c', Len(s) > 0)
def my_function(a: Integral, b, c: str):
"""an example function I'd like to check the arguments of."""
# check that a is an int
# check that 0 < b < 10
# check that c is not an empty string
# check that it works
my_function(0.2, 1, 'r') # RuntimeTypeError 'a' was not of type <class 'numbers.Integral'>
my_function(0, 0, 'r') # InputValidationError for 'b' [(x > 0) & (x < 10)] returned [False]
my_function(0, 1, 0) # RuntimeTypeError 'c' was not of type <class 'str'>
my_function(0, 1, '') # InputValidationError for 'c' [len(s) > 0] returned [False].
I had the same problem using Ionic framework (Angular + Cordova). I know this not solve the problem, but it's the code for Angular Apps based on the answers above. You will have a ephemeral solution for localStorage on iOS version of Safari.
Here is the code:
angular.module('myApp.factories', [])
.factory('$fakeStorage', [
function(){
function FakeStorage() {};
FakeStorage.prototype.setItem = function (key, value) {
this[key] = value;
};
FakeStorage.prototype.getItem = function (key) {
return typeof this[key] == 'undefined' ? null : this[key];
}
FakeStorage.prototype.removeItem = function (key) {
this[key] = undefined;
};
FakeStorage.prototype.clear = function(){
for (var key in this) {
if( this.hasOwnProperty(key) )
{
this.removeItem(key);
}
}
};
FakeStorage.prototype.key = function(index){
return Object.keys(this)[index];
};
return new FakeStorage();
}
])
.factory('$localstorage', [
'$window', '$fakeStorage',
function($window, $fakeStorage) {
function isStorageSupported(storageName)
{
var testKey = 'test',
storage = $window[storageName];
try
{
storage.setItem(testKey, '1');
storage.removeItem(testKey);
return true;
}
catch (error)
{
return false;
}
}
var storage = isStorageSupported('localStorage') ? $window.localStorage : $fakeStorage;
return {
set: function(key, value) {
storage.setItem(key, value);
},
get: function(key, defaultValue) {
return storage.getItem(key) || defaultValue;
},
setObject: function(key, value) {
storage.setItem(key, JSON.stringify(value));
},
getObject: function(key) {
return JSON.parse(storage.getItem(key) || '{}');
},
remove: function(key){
storage.removeItem(key);
},
clear: function() {
storage.clear();
},
key: function(index){
storage.key(index);
}
}
}
]);
Source: https://gist.github.com/jorgecasar/61fda6590dc2bb17e871
Enjoy your coding!
Because the SCHEDULER_ADMIN role is a powerful role allowing a grantee to execute code as any user, you should consider granting individual Scheduler system privileges instead. Object and system privileges are granted using regular SQL grant syntax. An example is if the database administrator issues the following statement:
GRANT CREATE JOB TO scott;
After this statement is executed, scott can create jobs, schedules, or programs in his schema.
copied from http://docs.oracle.com/cd/B19306_01/server.102/b14231/schedadmin.htm#i1006239
I just came across this tonight. Can't say if they are legit, how long in business, and whether they'll be around long, but seems interesting. I may give them a try, and will post update if I do.
Per the website, they say they offer hourly pay-as-you-go and weekly/monthly plans, plus there's a free trial.
Per @Iterator, posting update on my findings for this service, moving out from my comments:
I did the trial/evaluation. The trial can be misleading on how the trial works. You may need to signup to see prices but the trial so far, per the trial software download, doesn't appear to be time limited. It's just feature restricted. You signup to get your own account, but you actually use a generic trial login account to do the trial, not your own account. Your own account is used when you actually pay for the service. The trial limits what you can do, install, save, etc. but good enough to give you an idea of how things work. So it doesn't hurt to signup to evaluate and not pay anything.
Persistence of data is offered via saving files to DropBox (pre-installed, you just need login/configure), etc. There is no concept of AMIs, EBS, or some VM image. Their service is actually like a shared website hosting solution, where users timeshare a Mac machine (like timesharing a Unix/Linux server), and I think they limit or periodically purge what you put on the machine, or perhaps rather they don't backup your files, hence use of DropBox to do the backup. One should contact them to clarify this if desired.
They have various pricing options, as you mention the all day pass, monthly plans at $20, and their is a pay as you go plan at $1/hr. I'd probably go with pay as you go based on my usage. The pay as you go is based on prepaid credits (1 credit = 1 hour, billed at 30 credit increments). One caveat is that you need to periodically use the plan at least once every 60 days for the pay as you go plan or else you lose unused credits. So that's like minimum of spending 1 credit /1 hour every 60 days.
One last comment for now, from my evaluation, you'll need high bandwidth to use the service effectively. It's usable over 1.5 Mbps DSL but kind of slow in response. You'd want to use it from a corporate network with Gbps bandwidth for optimal use. Or at least a higher speed cable/DSL broadband connection. On my last test ~3Mbps seemed sufficient on the low bandwidth profile (they have multiple bandwidth connection profiles, low, medium, high, optimized for some bandwidth ranges). I didn't test on the higher ones. Your mileage may vary.
At the root context of the namespace is a binding with the name "comp", which is bound to a subtree reserved for component-related bindings. The name "comp" is short for component. There are no other bindings at the root context. However, the root context is reserved for the future expansion of the policy, specifically for naming resources that are tied not to the component itself but to other types of entities such as users or departments. For example, future policies might allow you to name users and organizations/departments by using names such as "java:user/alice" and "java:org/engineering".
In the "comp" context, there are two bindings: "env" and "UserTransaction". The name "env" is bound to a subtree that is reserved for the component's environment-related bindings, as defined by its deployment descriptor. "env" is short for environment. The J2EE recommends (but does not require) the following structure for the "env" namespace.
So the binding you did from spring or, for example, from a tomcat context descriptor go by default under java:comp/env/
For example, if your configuration is:
<bean id="someId" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="foo"/>
</bean>
Then you can access it directly using:
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("java:comp/env/foo");
or you could make an intermediate step so you don't have to specify "java:comp/env" for every resource you retrieve:
Context ctx = new InitialContext();
Context envCtx = (Context)ctx.lookup("java:comp/env");
DataSource ds = (DataSource)envCtx.lookup("foo");
I had the same problem. The solution was to change the useState initial state value from string to array. In App.js, previous useState was
const [favoriteFilms, setFavoriteFilms] = useState('');
I changed it to
const [favoriteFilms, setFavoriteFilms] = useState([]);
and the component that uses those values stopped throwing error with .map function.
tl;dr: (try it here)
If you have the following HTML:
<div id="menu" style="display: none;">
<!-- menu stuff in here -->
<ul><li>Menu item</li></ul>
</div>
<div class="parent">Hover over me to show the menu here</div>
then you can use the following JavaScript code:
$(".parent").mouseover(function() {
// .position() uses position relative to the offset parent,
var pos = $(this).position();
// .outerWidth() takes into account border and padding.
var width = $(this).outerWidth();
//show the menu directly over the placeholder
$("#menu").css({
position: "absolute",
top: pos.top + "px",
left: (pos.left + width) + "px"
}).show();
});
But it doesn't work!
This will work as long as the menu and the placeholder have the same offset parent. If they don't, and you don't have nested CSS rules that care where in the DOM the #menu
element is, use:
$(this).append($("#menu"));
just before the line that positions the #menu
element.
But it still doesn't work!
You might have some weird layout that doesn't work with this approach. In that case, just use jQuery.ui's position plugin (as mentioned in an answer below), which handles every conceivable eventuality. Note that you'll have to show()
the menu element before calling position({...})
; the plugin can't position hidden elements.
Update notes 3 years later in 2012:
(The original solution is archived here for posterity)
So, it turns out that the original method I had here was far from ideal. In particular, it would fail if:
Luckily, jQuery introduced methods (position()
and outerWidth()
) way back in 1.2.6 that make finding the right values in the latter case here a lot easier. For the former case, append
ing the menu element to the placeholder works (but will break CSS rules based on nesting).
HTML 5 video does go fullscreen in the latest nightly build of Safari, though I'm not sure how it is technically accomplished.
The documentation has the complete answer. Anyway this is how it is done:
<input type="text" ng-model="filterValue">
<li ng-repeat="i in data | filter:{age:filterValue}:true"> {{i | json }}</li>
will filter only age
in data
array and true
is for exact match.
For deep filtering,
<li ng-repeat="i in data | filter:{$:filterValue}:true"> {{i}}</li>
The $
is a special property for deep filter and the true
is for exact match like above.
Most of the time, you will use them like this:
For example:
In both cases, the request body contains the data for the resource to be created or updated. It should be obvious from the route names that POST is not idempotent (if you call it 3 times it will create 3 objects), but PUT is idempotent (if you call it 3 times the result is the same). PUT is often used for "upsert" operation (create or update), but you can always return a 404 error if you only want to use it to modify.
Note that POST "creates" a new element in the collection, and PUT "replaces" an element at a given URL, but it is a very common practice to use PUT for partial modifications, that is, use it only to update existing resources and only modify the included fields in the body (ignoring the other fields). This is technically incorrect, if you want to be REST-purist, PUT should replace the whole resource and you should use PATCH for the partial update. I personally don't care much as far as the behavior is clear and consistent across all your API endpoints.
Remember, REST is a set of conventions and guidelines to keep your API simple. If you end up with a complicated work-around just to check the "RESTfull" box then you are defeating the purpose ;)
$xml = '<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<PaymentNotification xmlns="http://apilistener.envoyservices.com">
<payment>
<uniqueReference>ESDEUR11039872</uniqueReference>
<epacsReference>74348dc0-cbf0-df11-b725-001ec9e61285</epacsReference>
<postingDate>2010-11-15T15:19:45</postingDate>
<bankCurrency>EUR</bankCurrency>
<bankAmount>1.00</bankAmount>
<appliedCurrency>EUR</appliedCurrency>
<appliedAmount>1.00</appliedAmount>
<countryCode>ES</countryCode>
<bankInformation>Sean Wood</bankInformation>
<merchantReference>ESDEUR11039872</merchantReference>
</payment>
</PaymentNotification>
</soap:Body>
</soap:Envelope>';
$doc = new DOMDocument();
$doc->loadXML($xml);
echo $doc->getElementsByTagName('postingDate')->item(0)->nodeValue;
die;
Result is:
2010-11-15T15:19:45
None of these worked for me. I'm using Mac OS 10.10.5 and Workbench 6.3. What worked for me is Database->Migration Wizard... Flow the steps very carefully
Using Accept header is really easy to get the format json or xml from the REST service.
This is my Controller, take a look produces section.
@RequestMapping(value = "properties", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}, method = RequestMethod.GET)
public UIProperty getProperties() {
return uiProperty;
}
In order to consume the REST service we can use the code below where header can be MediaType.APPLICATION_JSON_VALUE or MediaType.APPLICATION_XML_VALUE
HttpHeaders headers = new HttpHeaders();
headers.add("Accept", header);
HttpEntity entity = new HttpEntity(headers);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.exchange("http://localhost:8080/properties", HttpMethod.GET, entity,String.class);
return response.getBody();
Edit 01:
In order to work with application/xml
, add this dependency
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
Also this is a cause too: If you built a jQuery collection (via .map() or something similar) then you shouldn't use this collection in .ajax()'s data. Because it's still a jQuery object, not plain JavaScript Array. You should use .get() at the and to get plain js array and should use it on the data setting on .ajax().
This is a solution in shell script:
apk="$apk_path"
adb install "$apk"
sleep 1
pkg_info=`aapt dump badging "$apk" | head -1 | awk -F " " '{print $2}'`
eval $pkg_info > /dev/null
pkg_name=$name
adb shell monkey -p "${pkg_name}" -c android.intent.category.LAUNCHER 1
A very simple solution can be:
try {
requestEntity = RequestEntity
.get(new URI("user String"));
return restTemplate.exchange(requestEntity, String.class);
} catch (RestClientResponseException e) {
return ResponseEntity.status(e.getRawStatusCode()).body(e.getResponseBodyAsString());
}
Edit: this is an answer to the OP's original question about the minimal key, not the minimal answer.
You can get the keys of the dict using the keys
function, and you're right about using min
to find the minimum of that list.
Use CSS styles with CSS Classes instead
CSS
.error {
border:2px solid red;
}
Now in Javascript
document.getElementById("fName").className = document.getElementById("fName").className + " error"; // this adds the error class
document.getElementById("fName").className = document.getElementById("fName").className.replace(" error", ""); // this removes the error class
The main reason I mention this is suppose you want to change the color of the errored element's border. If you choose your way you will may need to modify many places in code. If you choose my way you can simply edit the style sheet.
You need a loop over the lines of a file, you need to learn about string methods
with open(filename,'r') as f:
for line in f.readlines():
# python can do regexes, but this is for s fixed string only
if "something" in line:
idx1 = line.find('"')
idx2 = line.find('"', idx1+1)
field = line[idx1+1:idx2-1]
print(field)
and you need a method to pass the filename to your python program and while you are at it, maybe also the string to search for...
For the future, try to ask more focused questions if you can,
$('.launchConfirm').on('click', function (e) {
$('#confirm')
.modal({ backdrop: 'static', keyboard: false })
.one('click', '#delete', function (e) {
//delete function
});
});
For your button:
<button class='btn btn-danger btn-xs launchConfirm' type="button" name="remove_levels"><span class="fa fa-times"></span> delete</button></td>
You can use defaultdict:
>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> a = ['1', '2']
>>> for i in a:
... for j in range(int(i), int(i) + 2):
... d[j].append(i)
...
>>> d
defaultdict(<type 'list'>, {1: ['1'], 2: ['1', '2'], 3: ['2']})
>>> d.items()
[(1, ['1']), (2, ['1', '2']), (3, ['2'])]
Yes. unless, there is an ambiguity.
This works for me,
List<string> lstRemoveColumns = new List<string>() { "ColValue1", "ColVal2", "ColValue3", "ColValue4" };
List<DataRow> rowsToDelete = new List<DataRow>();
foreach (DataRow row in dt.Rows) {
if (lstRemoveColumns.Contains(row["ColumnName"].ToString())) {
rowsToDelete.Add(row);
}
}
foreach (DataRow row in rowsToDelete) {
dt.Rows.Remove(row);
}
dt.AcceptChanges();
Use this:
SELECT s.name AS Student, c.name AS Course
FROM student s
LEFT JOIN (bridge b CROSS JOIN course c)
ON (s.id = b.sid AND b.cid = c.id);
When you want to remove one xxx.java file from SVN:
You could also create the input button in this way:
var button = '<input type="button" id="questionButton" value='+variable+'> <br />';
It might be the syntax of the Button creation that is off somehow.
We use phabricator and don't push using git. I had to create bash alias which works on Linux/mac
vim ~/.bash_aliases
new_branch() {
git checkout -b "$1"
git branch --set-upstream-to=origin/master "$1"
}
save
source ~/.bash_aliases
new_branch test #instead of git checkout -b test
git pull
I had this problem today. I was using STS 3.4 with its bundled Roo 1.2.4. Later I tried with Eclipse Kepler and Roo 1.2.5, same error.
I've changed my pom.xml adding pluginTemplates tag after build and before plugins declaration but didn't work.
What made the magic for me:
Configured JDK, Roo and Maven bin directories on my PATH:
export PATH=/opt/jdk1.7.0_51/bin:$PATH export PATH=/opt/spring-roo-1.2.5.RELEASE/bin:$PATH export PATH=/opt/apache-maven-3.2.1/bin:$PATH
Made my configuration as following: (http://docs.spring.io/spring-roo/reference/html/beginning.html)
$ mkdir hello
$ cd hello
$ roo.sh
roo> project --topLevelPackage com.foo
roo> jpa setup --provider HIBERNATE --database HYPERSONIC_PERSISTENT
roo> web mvc setup
roo> perform eclipse
Open with Eclipse (nothing of STS, but I guess it works): Import -> Existing Projects into Workspace
In PL/SQL code, you can use: DBMS_OUTPUT.NEW_LINE;
An example, just to make this a 15 seconds answer -
Say you have "styles.xaml" in a WPF library named "common" and you want to use it from your main application project:
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/Common;component/styles.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
For the sake of performances, we can now safely use requestAnimationFrame for fast looping, instead of setInterval/setTimeout.
When using setInterval/setTimeout, if a loop task is taking more time than the interval, the browser will simply extend the interval loop, to continue the full rendering. This is creating issues. After minutes of setInterval/setTimeout overload, this can freeze the tab, the browser or the whole computer.
Internet devices have a wide range of performances, so it's quite impossible to hardcode a fixed interval time in milliseconds!
Using the Date object, to compare the start Date Epoch and the current. This is way faster than everything else, the browser will take care of everything, at a steady 60FPS (1000 / 60 = 16.66ms by frame) -a quarter of an eye blink- and if the task in the loop is requiring more than that, the browser will drop some repaints.
This allow a margin before our eyes are noticing (Human = 24FPS => 1000 / 24 = 41.66ms by frame = fluid animation!)
https://caniuse.com/#search=requestAnimationFrame
/* Seconds to (STRING)HH:MM:SS.MS ------------------------*/_x000D_
/* This time format is compatible with FFMPEG ------------*/_x000D_
function secToTimer(sec){_x000D_
const o = new Date(0), p = new Date(sec * 1000)_x000D_
return new Date(p.getTime()-o.getTime()).toString().split(" ")[4] + "." + p.getMilliseconds()_x000D_
}_x000D_
_x000D_
/* Countdown loop ----------------------------------------*/_x000D_
let job, origin = new Date().getTime()_x000D_
const timer = () => {_x000D_
job = requestAnimationFrame(timer)_x000D_
OUT.textContent = secToTimer((new Date().getTime() - origin) / 1000)_x000D_
}_x000D_
_x000D_
/* Start looping -----------------------------------------*/_x000D_
requestAnimationFrame(timer)_x000D_
_x000D_
/* Stop looping ------------------------------------------*/_x000D_
// cancelAnimationFrame(job)_x000D_
_x000D_
/* Reset the start date ----------------------------------*/_x000D_
// origin = new Date().getTime()
_x000D_
span {font-size:4rem}
_x000D_
<span id="OUT"></span>_x000D_
<br>_x000D_
<button onclick="origin = new Date().getTime()">RESET</button>_x000D_
<button onclick="requestAnimationFrame(timer)">RESTART</button>_x000D_
<button onclick="cancelAnimationFrame(job)">STOP</button>
_x000D_
In my case, I was using an TOMCAT 8 and updating to TOMCAT 9 fixed it:
<modelVersion>4.0.0</modelVersion>
<groupId>spring-boot-app</groupId>
<artifactId>spring-boot-app</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>com.example.Application</mainClass>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<tomcat.version>9.0.37</tomcat.version>
</properties>
Related issues:
Python code:
import sys
# main
param_1= sys.argv[1]
param_2= sys.argv[2]
param_3= sys.argv[3]
print 'Params=', param_1, param_2, param_3
Invocation:
$python myfile.py var1 var2 var3
Output:
Params= var1 var2 var3
I had the same problem. I resolved, uninstalling all de the versions in my pc and then reinstall dotnet.
As JERC said, make sure you have an updated version of git. If you are only using the default settings, when you try to install git you will get version 1.7.1. Other than manually downloading and installing the latest version of get, you can also accomplish this by adding a new repository to yum.
From tecadmin.net:
Download and install the rpmforge repository:
# use this for 64-bit
rpm -i 'http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.3-1.el6.rf.x86_64.rpm'
# use this for 32-bit
rpm -i 'http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.3-1.el6.rf.i686.rpm'
# then run this in either case
rpm --import http://apt.sw.be/RPM-GPG-KEY.dag.txt
Then you need to enable the rpmforge-extras. Edit /etc/yum.repos.d/rpmforge.repo
and change enabled = 0
to enabled = 1
under [rpmforge-extras]
. The file looks like this:
### Name: RPMforge RPM Repository for RHEL 6 - dag
### URL: http://rpmforge.net/
[rpmforge]
name = RHEL $releasever - RPMforge.net - dag
baseurl = http://apt.sw.be/redhat/el6/en/$basearch/rpmforge
mirrorlist = http://mirrorlist.repoforge.org/el6/mirrors-rpmforge
#mirrorlist = file:///etc/yum.repos.d/mirrors-rpmforge
enabled = 1
protect = 0
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-rpmforge-dag
gpgcheck = 1
[rpmforge-extras]
name = RHEL $releasever - RPMforge.net - extras
baseurl = http://apt.sw.be/redhat/el6/en/$basearch/extras
mirrorlist = http://mirrorlist.repoforge.org/el6/mirrors-rpmforge-extras
#mirrorlist = file:///etc/yum.repos.d/mirrors-rpmforge-extras
enabled = 0 ####### CHANGE THIS LINE TO "enabled = 1" #############
protect = 0
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-rpmforge-dag
gpgcheck = 1
[rpmforge-testing]
name = RHEL $releasever - RPMforge.net - testing
baseurl = http://apt.sw.be/redhat/el6/en/$basearch/testing
mirrorlist = http://mirrorlist.repoforge.org/el6/mirrors-rpmforge-testing
#mirrorlist = file:///etc/yum.repos.d/mirrors-rpmforge-testing
enabled = 0
protect = 0
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-rpmforge-dag
gpgcheck = 1
Once you've done this, then you can update git with
yum update git
I'm not sure why, but they then suggest disabling rpmforge-extras (change back to enabled = 0
) and then running yum clean all
.
Most likely you'll need to use sudo
for these commands.
For iOS 10.x and Swift 3.x [below versions are also supported] just add the following lines in 'info.plist'
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
Check the mozilla documentation on window.open. The window features ("directory=...,...,height=350") etc. arguments should be a string:
window.open('/pageaddress.html','winname',"directories=0,titlebar=0,toolbar=0,location=0,status=0,menubar=0,scrollbars=no,resizable=no,width=400,height=350");
Try if that works in your browsers. Note that some of the features might be overridden by user preferences, such as "location" (see doc.)
The increasingly popular D3 library handles the oddities of appending/manipulating svg very nicely. You may want to consider using it as opposed to the jQuery hacks mentioned here.
HTML
<svg xmlns="http://www.w3.org/2000/svg"></svg>
Javascript
var circle = d3.select("svg").append("circle")
.attr("r", "10")
.attr("style", "fill:white;stroke:black;stroke-width:5");
I am assuming that test.html is a static file.To render static files use the static middleware like so.
app.use(express.static(path.join(__dirname, 'public')));
This tells express to look for static files in the public directory of the application.
Once you have specified this simply point your browser to the location of the file and it should display.
If however you want to render the views then you have to use the appropriate renderer for it.The list of renderes is defined in consolidate.Once you have decided which library to use just install it.I use mustache so here is a snippet of my config file
var engines = require('consolidate');
app.set('views', __dirname + '/views');
app.engine('html', engines.mustache);
app.set('view engine', 'html');
What this does is tell express to
look for files to render in views directory
Render the files using mustache
The extension of the file is .html(you can use .mustache too)
I found the highest voted answer (hometoast's answer) doesn't work perfectly for me. Two problems:
The following is a modified version:
^((http[s]?|ftp):\/)?\/?([^:\/\s]+)(:([^\/]*))?((\/\w+)*\/)([\w\-\.]+[^#?\s]+)(\?([^#]*))?(#(.*))?$
Position of parts are as follows:
int SCHEMA = 2, DOMAIN = 3, PORT = 5, PATH = 6, FILE = 8, QUERYSTRING = 9, HASH = 12
Edit posted by anon user:
function getFileName(path) {
return path.match(/^((http[s]?|ftp):\/)?\/?([^:\/\s]+)(:([^\/]*))?((\/[\w\/-]+)*\/)([\w\-\.]+[^#?\s]+)(\?([^#]*))?(#(.*))?$/i)[8];
}
You can use html and be a boss with simple things :
<embed src="music.mp3" width="3000" height="200" controls>
for windows 10 press windows key type cred and you should see "Credential Manager" in Control Panel click to open and then remove the related cached credentials then try again, it will ask user id password key in the correct password and you'll be good.
Happened with me when I changed my network password
There's a simple one-liner for this:
String target = myData.replaceAll("[^']*(?:'(.*?)')?.*", "$1");
By making the matching group optional, this also caters for quotes not being found by returning a blank in that case.
See live demo.
When an unauthorized request comes in, the entire request is URL encoded, and added as a query string to the request to the authorization form, so I can see where this may result in a problem given your situation.
According to MSDN, the correct element to modify to reset maxQueryStringLength in web.config is the <httpRuntime>
element inside the <system.web>
element, see httpRuntime Element (ASP.NET Settings Schema). Try modifying that element.
When getting "File not found", my problem was that there was no symlink in the folder where was pointing this line in ngix config:
root /var/www/claims/web;
To achieve this just use an Intent using the constant ACTION_SETTINGS, specifically defined to show the System Settings:
startActivity(new Intent(Settings.ACTION_SETTINGS));
startActivityForResult() is optional, only if you want to return some data when the settings activity is closed.
startActivityForResult(new Intent(Settings.ACTION_SETTINGS), 0);
here you can find a list of contants to show specific settings or details of an aplication.
Try type-safe-enum pattern.
public sealed class AuthenticationMethod {
private readonly String name;
private readonly int value;
public static readonly AuthenticationMethod FORMS = new AuthenticationMethod (1, "FORMS");
public static readonly AuthenticationMethod WINDOWSAUTHENTICATION = new AuthenticationMethod (2, "WINDOWS");
public static readonly AuthenticationMethod SINGLESIGNON = new AuthenticationMethod (3, "SSN");
private AuthenticationMethod(int value, String name){
this.name = name;
this.value = value;
}
public override String ToString(){
return name;
}
}
Update Explicit (or implicit) type conversion can be done by
adding static field with mapping
private static readonly Dictionary<string, AuthenticationMethod> instance = new Dictionary<string,AuthenticationMethod>();
filling this mapping in instance constructor
instance[name] = this;
and adding user-defined type conversion operator
public static explicit operator AuthenticationMethod(string str)
{
AuthenticationMethod result;
if (instance.TryGetValue(str, out result))
return result;
else
throw new InvalidCastException();
}
Here is email code I used in one of my databases. I just made variables for the person I wanted to send it to, CC, subject, and the body. Then you just use the DoCmd.SendObject command. I also set it to "True" after the body so you can edit the message before it automatically sends.
Public Function SendEmail2()
Dim varName As Variant
Dim varCC As Variant
Dim varSubject As Variant
Dim varBody As Variant
varName = "[email protected]"
varCC = "[email protected], [email protected]"
'separate each email by a ','
varSubject = "Hello"
'Email subject
varBody = "Let's get ice cream this week"
'Body of the email
DoCmd.SendObject , , , varName, varCC, , varSubject, varBody, True, False
'Send email command. The True after "varBody" allows user to edit email before sending.
'The False at the end will not send it as a Template File
End Function
What you are talking about is the way a parameterized query is written. '@' just signifies that it is a parameter. You can add the value for that parameter during execution process
eg:
sqlcommand cmd = new sqlcommand(query,connection);
cmd.parameters.add("@custid","1");
sqldatareader dr = cmd.executequery();
You should check for Dictionary.ContainsKey(int key) before trying to pull out the value.
Dictionary<int, int> myDictionary = new Dictionary<int, int>();
myDictionary.Add(2,4);
myDictionary.Add(3,5);
int keyToFind = 7;
if(myDictionary.ContainsKey(keyToFind))
{
myValueLookup = myDictionay[keyToFind];
// do work...
}
else
{
// the key doesn't exist.
}
Using reduce, you can do this in one Array.prototype function. This will fetch all even numbers from an array.
var arr = [1,2,3,4,5,6,7,8];_x000D_
_x000D_
var brr = arr.reduce((c, n) => {_x000D_
if (n % 2 !== 0) {_x000D_
return c;_x000D_
}_x000D_
c.push(n);_x000D_
return c;_x000D_
}, []);_x000D_
_x000D_
document.getElementById('mypre').innerHTML = brr.toString();
_x000D_
<h1>Get all even numbers</h1>_x000D_
<pre id="mypre"> </pre>
_x000D_
You can use the same method and generalize it for your objects, like this.
var arr = options.reduce(function(c,n){
if(somecondition) {return c;}
c.push(n);
return c;
}, []);
arr
will now contain the filtered objects.
webRequest.ContentType = "application/x-www-form-urlencoded";
Where does application/x-www-form-urlencoded's name come from?
If you send HTTP GET request, you can use query parameters as follows:
http://example.com/path/to/page
?name=ferret&color=purple
The content of the fields is encoded as a query string. The application/x-www-form-
urlencoded
's name come from the previous url query parameter but the query parameters is
in where the body of request instead of url.
The whole form data is sent as a long query string.The query string contains name- value pairs separated by & character
e.g. field1=value1&field2=value2
It can be simple request called simple - don't trigger a preflight check
Simple request must have some properties. You can look here for more info. One of them is that there are only three values allowed for Content-Type header for simple requests
3.For mostly flat param trees, application/x-www-form-urlencoded is tried and tested.
request.ContentType = "application/json; charset=utf-8";
axios and superagent, two of the more popular npm HTTP libraries, work with JSON bodies by default.
{ "id": 1, "name": "Foo", "price": 123, "tags": [ "Bar", "Eek" ], "stock": { "warehouse": 300, "retail": 20 } }
Now, if the request isn't simple request, the browser automatically sends a HTTP request before the original one by OPTIONS method to check whether it is safe to send the original request. If itis ok, Then send actual request. You can look here for more info.
You use the id
property to the get the id, then the substr
method to remove the first part of it, then optionally parseInt
to turn it into a number:
var id = theElement.id.substr(5);
or:
var id = parseInt(theElement.id.substr(5));
For Android Studio 3.5, fount it using instructions here: https://developer.android.com/studio/debug/device-file-explorer (View -> Tool Windows -> Device File Explorer -> -> databases
At the top first set up database connection as follow:
<?php
$mysqli = new mysqli("localhost", "username", "password", "database") or die($this->mysqli->error);
$query= $mysqli->query("SELECT PcID from PC");
?>
Then include the following code in HTML inside form
<select name="selected_pcid" id='selected_pcid'>
<?php
while ($rows = $query->fetch_array(MYSQLI_ASSOC)) {
$value= $rows['id'];
?>
<option value="<?= $value?>"><?= $value?></option>
<?php } ?>
</select>
However, if you are using materialize css or any other out of the box css, make sure that select field is not hidden or disabled.
The way I would do it is to create paragraph tags where you want your error messages with the same class and show them when the data is invalid. Here is my fiddle
if ($('#email').val() == '' || !$('#password').val() == '') {
$('.loginError').show();
return false;
}
I also added the paragraph tags below the email and password inputs
<p class="loginError" style="display:none;">please enter your email address or password.</p>
To initialize long you need to append "L" to the end.
It can be either uppercase or lowercase.
All the numeric values are by default int
. Even when you do any operation of byte
with any integer, byte
is first promoted to int
and then any operations are performed.
Try this
byte a = 1; // declare a byte
a = a*2; // you will get error here
You get error because 2
is by default int
.
Hence you are trying to multiply byte
with int
.
Hence result gets typecasted to int
which can't be assigned back to byte
.
A linked table row is possible, but not with the standard <table>
elements. You can do it using the display: table
style properties. Here and here are some fiddles to demonstrate.
This code should do the trick:
.table {_x000D_
display: table;_x000D_
}_x000D_
_x000D_
.row {_x000D_
display: table-row;_x000D_
}_x000D_
_x000D_
.cell {_x000D_
display: table-cell;_x000D_
padding: 10px;_x000D_
}_x000D_
_x000D_
.row:hover {_x000D_
background-color: #cccccc;_x000D_
}_x000D_
_x000D_
.cell:hover {_x000D_
background-color: #e5e5e5;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" type="text/css" />_x000D_
_x000D_
<div role="grid" class="table">_x000D_
<div role="row" class="row">_x000D_
<div role="gridcell" class="cell">_x000D_
1.1_x000D_
</div>_x000D_
<div role="gridcell" class="cell">_x000D_
1.2_x000D_
</div>_x000D_
<div role="gridcell" class="cell">_x000D_
1.3_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<a role="row" class="row" href="#">_x000D_
<div role="gridcell" class="cell">_x000D_
2.1_x000D_
</div>_x000D_
<div role="gridcell" class="cell">_x000D_
2.2_x000D_
</div>_x000D_
<div role="gridcell" class="cell">_x000D_
2.3_x000D_
</div>_x000D_
</a>_x000D_
</div>
_x000D_
Note that ARIA roles are needed to ensure proper accessibility since the standard <table>
elements are not used. You may need to add additional roles like role="columnheader"
if applicable. Find out more at the guide here.
One liner: $page_path = end(explode('/', trim($_SERVER['REQUEST_URI'], '/')));
Get URI, trim slashes, convert to array, grab last part
I had to change the js file, so to include "function()" at the beginning of it, and also "()" at the end line. That solved the problem
Today. I have same problem... my solution:
1) check inode: df -i
I saw:
root@vm22433:/etc/mysql# df -i
Filesystem Inodes IUsed IFree IUse% Mounted on
udev 124696 304 124392 1% /dev
tmpfs 127514 452 127062 1% /run
/dev/vda1 1969920 1969920 0 100% /
tmpfs 127514 1 127513 1% /dev/shm
tmpfs 127514 3 127511 1% /run/lock
tmpfs 127514 15 127499 1% /sys/fs/cgroup
tmpfs 127514 12 127502 1% /run/user/1002
2) I began to look what folders use the maximum number of inods:
for i in /*; do echo $i; find $i |wc -l; done
soon I found in /home/tomnolane/tmp folder, which contained a huge number of files.
3) I removed /home/tomnolane/tmp folder PROFIT.
4) checked:
Filesystem Inodes IUsed IFree IUse% Mounted on
udev 124696 304 124392 1% /dev
tmpfs 127514 454 127060 1% /run
/dev/vda1 1969920 450857 1519063 23% /
tmpfs 127514 1 127513 1% /dev/shm
tmpfs 127514 3 127511 1% /run/lock
tmpfs 127514 15 127499 1% /sys/fs/cgroup
tmpfs 127514 12 127502 1% /run/user/1002
it's ok.
5) restart mysql service
- it's ok!!!!
Another approach is to append the submit input button to the form only when it is supposed to be submited and replace it by a simple div during the form filling
Seems like you are looking for the Mode value (Statistical Mode) , have a look at Apache's Docs for Statistical functions.
It's quite easy and efficient to use Excel as a reporting tool for Access data.
A quick "non programming" approach is to set a List or a Pivot Table, linked to your External Data source. But that's out of scope for Stackoverflow.
A programmatic approach can be very simple:
strProv = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & SourceFile & ";"
Set cnn = New ADODB.Connection
cnn.Open strProv
Set rst = New ADODB.Recordset
rst.Open strSql, cnn
myDestRange.CopyFromRecordset rst
That's it !
I followed the top answer and started looking at yahoo finance. Their API can be accessed a number of different ways, but I found a nice reference for getting stock info as a CSV here: http://www.jarloo.com/
Using that I wrote this script. I'm not really a ruby guy but this might help you hack something together. I haven't come up with variable names for all the fields yahoo offers yet, so you can fill those in if you need them.
Here's the usage
TICKERS_SP500 = "GICS,CIK,MMM,ABT,ABBV,ACN,ACE,ACT,ADBE,ADT,AES,AET,AFL,AMG,A,GAS,APD,ARG,AKAM,AA,ALXN,ATI,ALLE,ADS,ALL,ALTR,MO,AMZN,AEE,AAL,AEP,AXP,AIG,AMT,AMP,ABC,AME,AMGN,APH,APC,ADI,AON,APA,AIV,AAPL,AMAT,ADM,AIZ,T,ADSK,ADP,AN,AZO,AVGO,AVB,AVY,BHI,BLL,BAC,BK,BCR,BAX,BBT,BDX,BBBY,BBY,BIIB,BLK,HRB,BA,BWA,BXP,BSX,BMY,BRCM,BFB,CHRW,CA,CVC,COG,CAM,CPB,COF,CAH,HSIC,KMX,CCL,CAT,CBG,CBS,CELG,CNP,CTL,CERN,CF,SCHW,CHK,CVX,CMG,CB,CI,XEC,CINF,CTAS,CSCO,C,CTXS,CLX,CME,CMS,COH,KO,CCE,CTSH,CL,CMA,CSC,CAG,COP,CNX,ED,STZ,GLW,COST,CCI,CSX,CMI,CVS,DHI,DHR,DRI,DVA,DE,DLPH,DAL,XRAY,DVN,DO,DTV,DFS,DG,DLTR,D,DOV,DOW,DPS,DTE,DD,DUK,DNB,ETFC,EMN,ETN,EBAY,ECL,EIX,EW,EA,EMC,EMR,ENDP,ESV,ETR,EOG,EQT,EFX,EQIX,EQR,ESS,EL,ES,EXC,EXPE,EXPD,ESRX,XOM,FFIV,FB,FDO,FAST,FDX,FIS,FITB,FSLR,FE,FISV,FLIR,FLS,FLR,FMC,FTI,F,FOSL,BEN,FCX,FTR,GME,GCI,GPS,GRMN,GD,GE,GGP,GIS,GM,GPC,GNW,GILD,GS,GT,GOOG,GWW,HAL,HBI,HOG,HAR,HRS,HIG,HAS,HCA,HCP,HCN,HP,HES,HPQ,HD,HON,HRL,HSP,HST,HCBK,HUM,HBAN,ITW,IR,TEG,INTC,ICE,IBM,IP,IPG,IFF,INTU,ISRG,IVZ,IRM,JEC,JNJ,JCI,JOY,JPM,JNPR,KSU,K,KEY,GMCR,KMB,KIM,KMI,KLAC,KSS,KRFT,KR,LB,LLL,LH,LRCX,LM,LEG,LEN,LVLT,LUK,LLY,LNC,LLTC,LMT,L,LO,LOW,LYB,MTB,MAC,M,MNK,MRO,MPC,MAR,MMC,MLM,MAS,MA,MAT,MKC,MCD,MHFI,MCK,MJN,MWV,MDT,MRK,MET,KORS,MCHP,MU,MSFT,MHK,TAP,MDLZ,MON,MNST,MCO,MS,MOS,MSI,MUR,MYL,NDAQ,NOV,NAVI,NTAP,NFLX,NWL,NFX,NEM,NWSA,NEE,NLSN,NKE,NI,NE,NBL,JWN,NSC,NTRS,NOC,NRG,NUE,NVDA,ORLY,OXY,OMC,OKE,ORCL,OI,PCAR,PLL,PH,PDCO,PAYX,PNR,PBCT,POM,PEP,PKI,PRGO,PFE,PCG,PM,PSX,PNW,PXD,PBI,PCL,PNC,RL,PPG,PPL,PX,PCP,PCLN,PFG,PG,PGR,PLD,PRU,PEG,PSA,PHM,PVH,QEP,PWR,QCOM,DGX,RRC,RTN,RHT,REGN,RF,RSG,RAI,RHI,ROK,COL,ROP,ROST,RCL,R,CRM,SNDK,SCG,SLB,SNI,STX,SEE,SRE,SHW,SIAL,SPG,SWKS,SLG,SJM,SNA,SO,LUV,SWN,SE,STJ,SWK,SPLS,SBUX,HOT,STT,SRCL,SYK,STI,SYMC,SYY,TROW,TGT,TEL,TE,THC,TDC,TSO,TXN,TXT,HSY,TRV,TMO,TIF,TWX,TWC,TJX,TMK,TSS,TSCO,RIG,TRIP,FOXA,TSN,TYC,USB,UA,UNP,UNH,UPS,URI,UTX,UHS,UNM,URBN,VFC,VLO,VAR,VTR,VRSN,VZ,VRTX,VIAB,V,VNO,VMC,WMT,WBA,DIS,WM,WAT,ANTM,WFC,WDC,WU,WY,WHR,WFM,WMB,WIN,WEC,WYN,WYNN,XEL,XRX,XLNX,XL,XYL,YHOO,YUM,ZMH,ZION,ZTS,SAIC,AP"
AllData = loadStockInfo(TICKERS_SP500, allParameters())
SpecificData = loadStockInfo("GOOG,CIK", "ask,dps")
loadStockInfo returns a hash, such that SpecificData["GOOG"]["name"] is "Google Inc."
Finally, the actual code to run that...
require 'net/http'
# Jack Franzen & Garin Bedian
# Based on http://www.jarloo.com/yahoo_finance/
$parametersData = Hash[[
["symbol", ["s", "Symbol"]],
["ask", ["a", "Ask"]],
["divYield", ["y", "Dividend Yield"]],
["bid", ["b", "Bid"]],
["dps", ["d", "Dividend per Share"]],
#["noname", ["b2", "Ask (Realtime)"]],
#["noname", ["r1", "Dividend Pay Date"]],
#["noname", ["b3", "Bid (Realtime)"]],
#["noname", ["q", "Ex-Dividend Date"]],
#["noname", ["p", "Previous Close"]],
#["noname", ["o", "Open"]],
#["noname", ["c1", "Change"]],
#["noname", ["d1", "Last Trade Date"]],
#["noname", ["c", "Change & Percent Change"]],
#["noname", ["d2", "Trade Date"]],
#["noname", ["c6", "Change (Realtime)"]],
#["noname", ["t1", "Last Trade Time"]],
#["noname", ["k2", "Change Percent (Realtime)"]],
#["noname", ["p2", "Change in Percent"]],
#["noname", ["c8", "After Hours Change (Realtime)"]],
#["noname", ["m5", "Change From 200 Day Moving Average"]],
#["noname", ["c3", "Commission"]],
#["noname", ["m6", "Percent Change From 200 Day Moving Average"]],
#["noname", ["g", "Day’s Low"]],
#["noname", ["m7", "Change From 50 Day Moving Average"]],
#["noname", ["h", "Day’s High"]],
#["noname", ["m8", "Percent Change From 50 Day Moving Average"]],
#["noname", ["k1", "Last Trade (Realtime) With Time"]],
#["noname", ["m3", "50 Day Moving Average"]],
#["noname", ["l", "Last Trade (With Time)"]],
#["noname", ["m4", "200 Day Moving Average"]],
#["noname", ["l1", "Last Trade (Price Only)"]],
#["noname", ["t8", "1 yr Target Price"]],
#["noname", ["w1", "Day’s Value Change"]],
#["noname", ["g1", "Holdings Gain Percent"]],
#["noname", ["w4", "Day’s Value Change (Realtime)"]],
#["noname", ["g3", "Annualized Gain"]],
#["noname", ["p1", "Price Paid"]],
#["noname", ["g4", "Holdings Gain"]],
#["noname", ["m", "Day’s Range"]],
#["noname", ["g5", "Holdings Gain Percent (Realtime)"]],
#["noname", ["m2", "Day’s Range (Realtime)"]],
#["noname", ["g6", "Holdings Gain (Realtime)"]],
#["noname", ["k", "52 Week High"]],
#["noname", ["v", "More Info"]],
#["noname", ["j", "52 week Low"]],
#["noname", ["j1", "Market Capitalization"]],
#["noname", ["j5", "Change From 52 Week Low"]],
#["noname", ["j3", "Market Cap (Realtime)"]],
#["noname", ["k4", "Change From 52 week High"]],
#["noname", ["f6", "Float Shares"]],
#["noname", ["j6", "Percent Change From 52 week Low"]],
["name", ["n", "Company Name"]],
#["noname", ["k5", "Percent Change From 52 week High"]],
#["noname", ["n4", "Notes"]],
#["noname", ["w", "52 week Range"]],
#["noname", ["s1", "Shares Owned"]],
#["noname", ["x", "Stock Exchange"]],
#["noname", ["j2", "Shares Outstanding"]],
#["noname", ["v", "Volume"]],
#["noname", ["a5", "Ask Size"]],
#["noname", ["b6", "Bid Size"]],
#["noname", ["k3", "Last Trade Size"]],
#["noname", ["t7", "Ticker Trend"]],
#["noname", ["a2", "Average Daily Volume"]],
#["noname", ["t6", "Trade Links"]],
#["noname", ["i5", "Order Book (Realtime)"]],
#["noname", ["l2", "High Limit"]],
#["noname", ["e", "Earnings per Share"]],
#["noname", ["l3", "Low Limit"]],
#["noname", ["e7", "EPS Estimate Current Year"]],
#["noname", ["v1", "Holdings Value"]],
#["noname", ["e8", "EPS Estimate Next Year"]],
#["noname", ["v7", "Holdings Value (Realtime)"]],
#["noname", ["e9", "EPS Estimate Next Quarter"]],
#["noname", ["s6", "evenue"]],
#["noname", ["b4", "Book Value"]],
#["noname", ["j4", "EBITDA"]],
#["noname", ["p5", "Price / Sales"]],
#["noname", ["p6", "Price / Book"]],
#["noname", ["r", "P/E Ratio"]],
#["noname", ["r2", "P/E Ratio (Realtime)"]],
#["noname", ["r5", "PEG Ratio"]],
#["noname", ["r6", "Price / EPS Estimate Current Year"]],
#["noname", ["r7", "Price / EPS Estimate Next Year"]],
#["noname", ["s7", "Short Ratio"]
]]
def replaceCommas(data)
s = ""
inQuote = false
data.split("").each do |a|
if a=='"'
inQuote = !inQuote
s += '"'
elsif !inQuote && a == ","
s += "#"
else
s += a
end
end
return s
end
def allParameters()
s = ""
$parametersData.keys.each do |i|
s = s + i + ","
end
return s
end
def prepareParameters(parametersText)
pt = parametersText.split(",")
if !pt.include? 'symbol'; pt.push("symbol"); end;
if !pt.include? 'name'; pt.push("name"); end;
p = []
pt.each do |i|
p.push([i, $parametersData[i][0]])
end
return p
end
def prepareURL(tickers, parameters)
urlParameters = ""
parameters.each do |i|
urlParameters += i[1]
end
s = "http://download.finance.yahoo.com/d/quotes.csv?"
s = s + "s=" + tickers + "&"
s = s + "f=" + urlParameters
return URI(s)
end
def loadStockInfo(tickers, parametersRaw)
parameters = prepareParameters(parametersRaw)
url = prepareURL(tickers, parameters)
data = Net::HTTP.get(url)
data = replaceCommas(data)
h = CSVtoObject(data, parameters)
logStockObjects(h, true)
end
#parse csv
def printCodes(substring, length)
a = data.index(substring)
b = data.byteslice(a, 10)
puts "printing codes of string: "
puts b
puts b.split('').map(&:ord).to_s
end
def CSVtoObject(data, parameters)
rawData = []
lineBreaks = data.split(10.chr)
lineBreaks.each_index do |i|
rawData.push(lineBreaks[i].split("#"))
end
#puts "Found " + rawData.length.to_s + " Stocks"
#puts " w/ " + rawData[0].length.to_s + " Fields"
h = Hash.new("MainHash")
rawData.each_index do |i|
o = Hash.new("StockObject"+i.to_s)
#puts "parsing object" + rawData[i][0]
rawData[i].each_index do |n|
#puts "parsing parameter" + n.to_s + " " +parameters[n][0]
o[ parameters[n][0] ] = rawData[i][n].gsub!(/^\"|\"?$/, '')
end
h[o["symbol"]] = o;
end
return h
end
def logStockObjects(h, concise)
h.keys.each do |i|
if concise
puts "(" + h[i]["symbol"] + ")\t\t" + h[i]["name"]
else
puts ""
puts h[i]["name"]
h[i].keys.each do |p|
puts " " + $parametersData[p][1] + " : " + h[i][p].to_s
end
end
end
end
This is due to IFS (Internal Field Separator) variable which contains newline.
$ cat xx1
1
2
$ A=`cat xx1`
$ echo $A
1 2
$ echo "|$IFS|"
|
|
A workaround is to reset IFS to not contain the newline, temporarily:
$ IFSBAK=$IFS
$ IFS=" "
$ A=`cat xx1` # Can use $() as well
$ echo $A
1
2
$ IFS=$IFSBAK
To REVERT this horrible change for IFS:
IFS=$IFSBAK
Less no longer evaluates expression inside calc
by default since v3.00
.
Original answer (Less v1.x...2.x
):
Do this:
body { width: calc(~"100% - 250px - 1.5em"); }
In Less 1.4.0 we will have a strictMaths
option which requires all Less calculations to be within brackets, so the calc
will work "out-of-the-box". This is an option since it is a major breaking change. Early betas of 1.4.0 had this option on by default. The release version has it off by default.
git-pull - Fetch from and integrate with another repository or a local branch
git pull [options] [<repository> [<refspec>...]]
You can refer official git doc https://git-scm.com/docs/git-pull
Ex :
git pull origin dev
In your code you don't get the HttpResponse, so you won't see what the server side sends you back.
you need to get the Response similar to the way you get (make) the Request. So
public static bool SendAnSMSMessage(string message)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://api.pennysms.com/jsonrpc");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{ \"method\": \"send\", " +
" \"params\": [ " +
" \"IPutAGuidHere\", " +
" \"[email protected]\", " +
" \"MyTenDigitNumberWasHere\", " +
" \"" + message + "\" " +
" ] " +
"}";
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
//Now you have your response.
//or false depending on information in the response
return true;
}
}
I also notice in the pennysms documentation that they expect a content type of "text/json" and not "application/json". That may not make a difference, but it's worth trying in case it doesn't work.
Had the same problem. Seems like there is something wrong with the set up instructions or the initial tables that are being created. This is how I got mysqld running on my machine.
If the mysqld server is already running on your Mac, stop it first with:
launchctl unload -w ~/Library/LaunchAgents/com.mysql.mysqld.plist
Start the mysqld server with the following command which lets anyone log in with full permissions.
mysqld_safe --skip-grant-tables
Then run mysql -u root
which should now let you log in successfully without a password. The following command should reset all the root passwords.
UPDATE mysql.user SET Password=PASSWORD('NewPassword') WHERE User='root'; FLUSH PRIVILEGES;
Now if you kill the running copy of mysqld_safe and start it up again without the skip-grant-tables option, you should be able to log in with mysql -u root -p
and the new password you just set.
Open a command prompt as an Administrator.
Enter slmgr /upk
and wait for this to complete. This will uninstall the current product key from Windows and put it into an unlicensed state.
Enter slmgr /cpky
and wait for this to complete. This will remove the product key from the registry if it's still there.
Enter slmgr /rearm
and wait for this to complete. This is to reset the Windows activation timers so the new users will be prompted to activate Windows when they put in the key.
This should put the system back to a pre-key state.
Hope this helps you out!
I need to give my user a web interface to change the session timeout interval. So, different installations of the web application would be able to have different timeouts for their sessions, but their web.xml cannot be different.
your question is simple, you need session timeout interval should be configurable at run time and configuration should be done through web interface and there shouldn't be overhead of restarting the server.
I am extending Michaels answer to address your question.
Logic: You need to store configured value in either .properties file or to database. On server start read that stored value and copy to a variable use that variable until server is UP. As config is updated update variable also. Thats it.
In MyHttpSessionListener class 1. create a static variable with name globalSessionTimeoutInterval.
create a static block(executed for only for first time of class is being accessed) and read timeout value from config.properties file and set value to globalSessionTimeoutInterval variable.
Now use that value to set maxInactiveInterval
Now Web part i.e, Admin configuration page
a. Copy configured value to static variable globalSessionTimeoutInterval.
b. Write same value to config.properties file. (consider server is restarted then globalSessionTimeoutInterval will be loaded with value present in config.properties file)
Alternative .properties file OR storing it into database. Choice is yours.
Logical code for achieving the same
public class MyHttpSessionListener implements HttpSessionListener
{
public static Integer globalSessionTimeoutInterval = null;
static
{
globalSessionTimeoutInterval = Read value from .properties file or database;
}
public void sessionCreated(HttpSessionEvent event)
{
event.getSession().setMaxInactiveInterval(globalSessionTimeoutInterval);
}
public void sessionDestroyed(HttpSessionEvent event) {}
}
And in your Configuration Controller or Configuration servlet
String valueReceived = request.getParameter(timeoutValue);
if(valueReceived != null)
{
MyHttpSessionListener.globalSessionTimeoutInterval = Integer.parseInt(timeoutValue);
//Store valueReceived to config.properties file or database
}
Here is a working version of the "build defs". This is similar to my previous answer but I figured out the build month. (You just can't compute build month in a #if
statement, but you can use a ternary expression that will be compiled down to a constant.)
Also, according to the documentation, if the compiler cannot get the time of day it will give you question marks for these strings. So I added tests for this case, and made the various macros return an obviously wrong value (99) if this happens.
#ifndef BUILD_DEFS_H
#define BUILD_DEFS_H
// Example of __DATE__ string: "Jul 27 2012"
// Example of __TIME__ string: "21:06:19"
#define COMPUTE_BUILD_YEAR \
( \
(__DATE__[ 7] - '0') * 1000 + \
(__DATE__[ 8] - '0') * 100 + \
(__DATE__[ 9] - '0') * 10 + \
(__DATE__[10] - '0') \
)
#define COMPUTE_BUILD_DAY \
( \
((__DATE__[4] >= '0') ? (__DATE__[4] - '0') * 10 : 0) + \
(__DATE__[5] - '0') \
)
#define BUILD_MONTH_IS_JAN (__DATE__[0] == 'J' && __DATE__[1] == 'a' && __DATE__[2] == 'n')
#define BUILD_MONTH_IS_FEB (__DATE__[0] == 'F')
#define BUILD_MONTH_IS_MAR (__DATE__[0] == 'M' && __DATE__[1] == 'a' && __DATE__[2] == 'r')
#define BUILD_MONTH_IS_APR (__DATE__[0] == 'A' && __DATE__[1] == 'p')
#define BUILD_MONTH_IS_MAY (__DATE__[0] == 'M' && __DATE__[1] == 'a' && __DATE__[2] == 'y')
#define BUILD_MONTH_IS_JUN (__DATE__[0] == 'J' && __DATE__[1] == 'u' && __DATE__[2] == 'n')
#define BUILD_MONTH_IS_JUL (__DATE__[0] == 'J' && __DATE__[1] == 'u' && __DATE__[2] == 'l')
#define BUILD_MONTH_IS_AUG (__DATE__[0] == 'A' && __DATE__[1] == 'u')
#define BUILD_MONTH_IS_SEP (__DATE__[0] == 'S')
#define BUILD_MONTH_IS_OCT (__DATE__[0] == 'O')
#define BUILD_MONTH_IS_NOV (__DATE__[0] == 'N')
#define BUILD_MONTH_IS_DEC (__DATE__[0] == 'D')
#define COMPUTE_BUILD_MONTH \
( \
(BUILD_MONTH_IS_JAN) ? 1 : \
(BUILD_MONTH_IS_FEB) ? 2 : \
(BUILD_MONTH_IS_MAR) ? 3 : \
(BUILD_MONTH_IS_APR) ? 4 : \
(BUILD_MONTH_IS_MAY) ? 5 : \
(BUILD_MONTH_IS_JUN) ? 6 : \
(BUILD_MONTH_IS_JUL) ? 7 : \
(BUILD_MONTH_IS_AUG) ? 8 : \
(BUILD_MONTH_IS_SEP) ? 9 : \
(BUILD_MONTH_IS_OCT) ? 10 : \
(BUILD_MONTH_IS_NOV) ? 11 : \
(BUILD_MONTH_IS_DEC) ? 12 : \
/* error default */ 99 \
)
#define COMPUTE_BUILD_HOUR ((__TIME__[0] - '0') * 10 + __TIME__[1] - '0')
#define COMPUTE_BUILD_MIN ((__TIME__[3] - '0') * 10 + __TIME__[4] - '0')
#define COMPUTE_BUILD_SEC ((__TIME__[6] - '0') * 10 + __TIME__[7] - '0')
#define BUILD_DATE_IS_BAD (__DATE__[0] == '?')
#define BUILD_YEAR ((BUILD_DATE_IS_BAD) ? 99 : COMPUTE_BUILD_YEAR)
#define BUILD_MONTH ((BUILD_DATE_IS_BAD) ? 99 : COMPUTE_BUILD_MONTH)
#define BUILD_DAY ((BUILD_DATE_IS_BAD) ? 99 : COMPUTE_BUILD_DAY)
#define BUILD_TIME_IS_BAD (__TIME__[0] == '?')
#define BUILD_HOUR ((BUILD_TIME_IS_BAD) ? 99 : COMPUTE_BUILD_HOUR)
#define BUILD_MIN ((BUILD_TIME_IS_BAD) ? 99 : COMPUTE_BUILD_MIN)
#define BUILD_SEC ((BUILD_TIME_IS_BAD) ? 99 : COMPUTE_BUILD_SEC)
#endif // BUILD_DEFS_H
With the following test code, the above works great:
printf("%04d-%02d-%02dT%02d:%02d:%02d\n", BUILD_YEAR, BUILD_MONTH, BUILD_DAY, BUILD_HOUR, BUILD_MIN, BUILD_SEC);
However, when I try to use those macros with your stringizing macro, it stringizes the literal expression! I don't know of any way to get the compiler to reduce the expression to a literal integer value and then stringize.
Also, if you try to statically initialize an array of values using these macros, the compiler complains with an error: initializer element is not constant
message. So you cannot do what you want with these macros.
At this point I'm thinking that your best bet is the Python script that just generates a new include file for you. You can pre-compute anything you want in any format you want. If you don't want Python we can write an AWK script or even a C program.
Create a temporary element (e. g. DIV
), assign your HTML code to its innerHTML
property, and then append its child nodes to the HEAD
element one by one. For example, like this:
var temp = document.createElement('div');
temp.innerHTML = '<link rel="stylesheet" href="example.css" />'
+ '<script src="foobar.js"><\/script> ';
var head = document.head;
while (temp.firstChild) {
head.appendChild(temp.firstChild);
}
Compared with rewriting entire HEAD
contents via its innerHTML
, this wouldn’t affect existing child elements of the HEAD
element in any way.
Note that scripts inserted this way are apparently not executed automatically, while styles are applied successfully. So if you need scripts to be executed, you should load JS files using Ajax and then execute their contents using eval()
.
try this
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = service.getBestProvider(criteria, false);
Location location = service.getLastKnownLocation(provider);
LatLng userLocation = new LatLng(location.getLatitude(),location.getLongitude());
I found some way to perform in on dictionary contain my custom class methods
foreach (var item in this.Values.Where(p => p.IsActive == false))
item.Refresh();
Where 'this' derived from : Dictionary<string, MyCustomClass>
class MyCustomClass
{
public void Refresh(){}
}
if you build an MVC project, its included by default. otherwise, what Nick said.
You can, of course, show it before making the request, and hide it after it completes:
$('#loading-image').show();
$.ajax({
url: uri,
cache: false,
success: function(html){
$('.info').append(html);
},
complete: function(){
$('#loading-image').hide();
}
});
I usually prefer the more general solution of binding it to the global ajaxStart and ajaxStop events, that way it shows up for all ajax events:
$('#loading-image').bind('ajaxStart', function(){
$(this).show();
}).bind('ajaxStop', function(){
$(this).hide();
});
You can use apache Range API. https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/Range.html
I used a relative path in the xsi:noNamespaceSchemaLocation to provide the local xsd file (because I could not use a namespace in the instance xml).
<?xml version="1.0" encoding="UTF-8"?>
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../project/schema.xsd">
</root>
Validation works and the warning is fixed (not ignored).
I noticed this question a couple of days late, but I feel that I can add some insight. I hope this can be helpful towards your RESTful venture.
Point 1: Am I understanding it right?
You understood right. That is a correct representation of a RESTful architecture. You may find the following matrix from Wikipedia very helpful in defining your nouns and verbs:
When dealing with a Collection URI like: http://example.com/resources/
GET: List the members of the collection, complete with their member URIs for further navigation. For example, list all the cars for sale.
PUT: Meaning defined as "replace the entire collection with another collection".
POST: Create a new entry in the collection where the ID is assigned automatically by the collection. The ID created is usually included as part of the data returned by this operation.
DELETE: Meaning defined as "delete the entire collection".
When dealing with a Member URI like: http://example.com/resources/7HOU57Y
GET: Retrieve a representation of the addressed member of the collection expressed in an appropriate MIME type.
PUT: Update the addressed member of the collection or create it with the specified ID.
POST: Treats the addressed member as a collection in its own right and creates a new subordinate of it.
DELETE: Delete the addressed member of the collection.
Point 2: I need more verbs
In general, when you think you need more verbs, it may actually mean that your resources need to be re-identified. Remember that in REST you are always acting on a resource, or on a collection of resources. What you choose as the resource is quite important for your API definition.
Activate/Deactivate Login: If you are creating a new session, then you may want to consider "the session" as the resource. To create a new session, use POST to http://example.com/sessions/
with the credentials in the body. To expire it use PUT or a DELETE (maybe depending on whether you intend to keep a session history) to http://example.com/sessions/SESSION_ID
.
Change Password: This time the resource is "the user". You would need a PUT to http://example.com/users/USER_ID
with the old and new passwords in the body. You are acting on "the user" resource, and a change password is simply an update request. It's quite similar to the UPDATE statement in a relational database.
My instinct would be to do a GET call to a URL like
/api/users/1/activate_login
This goes against a very core REST principle: The correct usage of HTTP verbs. Any GET request should never leave any side effect.
For example, a GET request should never create a session on the database, return a cookie with a new Session ID, or leave any residue on the server. The GET verb is like the SELECT statement in a database engine. Remember that the response to any request with the GET verb should be cache-able when requested with the same parameters, just like when you request a static web page.
Point 3: How to return error messages and codes
Consider the 4xx or 5xx HTTP status codes as error categories. You can elaborate the error in the body.
Failed to Connect to Database: / Incorrect Database Login: In general you should use a 500 error for these types of errors. This is a server-side error. The client did nothing wrong. 500 errors are normally considered "retryable". i.e. the client can retry the same exact request, and expect it to succeed once the server's troubles are resolved. Specify the details in the body, so that the client will be able to provide some context to us humans.
The other category of errors would be the 4xx family, which in general indicate that the client did something wrong. In particular, this category of errors normally indicate to the client that there is no need to retry the request as it is, because it will continue to fail permanently. i.e. the client needs to change something before retrying this request. For example, "Resource not found" (HTTP 404) or "Malformed Request" (HTTP 400) errors would fall in this category.
Point 4: How to do authentication
As pointed out in point 1, instead of authenticating a user, you may want to think about creating a session. You will be returned a new "Session ID", along with the appropriate HTTP status code (200: Access Granted or 403: Access Denied).
You will then be asking your RESTful server: "Can you GET me the resource for this Session ID?".
There is no authenticated mode - REST is stateless: You create a session, you ask the server to give you resources using this Session ID as a parameter, and on logout you drop or expire the session.
For me these steps worked
stop-all.sh
hadoop namenode -format
start-all.sh
Yes we can check the length of queue object created from collections.
from collections import deque
class Queue():
def __init__(self,batchSize=32):
#self.batchSie = batchSize
self._queue = deque(maxlen=batchSize)
def enqueue(self, items):
''' Appending the items to the queue'''
self._queue.append(items)
def dequeue(self):
'''remoe the items from the top if the queue becomes full '''
return self._queue.popleft()
Creating an object of class
q = Queue(batchSize=64)
q.enqueue([1,2])
q.enqueue([2,3])
q.enqueue([1,4])
q.enqueue([1,22])
Now retrieving the length of the queue
#check the len of queue
print(len(q._queue))
#you can print the content of the queue
print(q._queue)
#Can check the content of the queue
print(q.dequeue())
#Check the length of retrieved item
print(len(q.dequeue()))
check the results in attached screen shot
Hope this helps...
Here's an approach using generators:
function* square(n) {
for (var i = 0; i < n; i++ ) yield i*i;
}
Then you can write
console.log(...square(7));
Another idea is:
[...Array(5)].map((_, i) => i*i)
Array(5)
creates an unfilled five-element array. That's how Array
works when given a single argument. We use the spread operator to create an array with five undefined elements. That we can then map. See http://ariya.ofilabs.com/2013/07/sequences-using-javascript-array.html.
Alternatively, we could write
Array.from(Array(5)).map((_, i) => i*i)
or, we could take advantage of the second argument to Array#from
to skip the map
and write
Array.from(Array(5), (_, i) => i*i)
A horrible hack which I saw recently, which I do not recommend you use, is
[...1e4+''].map((_, i) => i*i)
You can do it very easily actually. Use the following code.
enum GroupTypes
{
OEM,
CMB
};
Then when you want to get the string value of each enum element just use the following line of code.
String oemString = Enum.GetName(typeof(GroupTypes), GroupTypes.OEM);
I've used this method successfully in the past, and I've also used a constants class to hold string constants, both work out pretty well, but I tend to prefer this.
du -h --max-depth=0 * | sort -hr
3,5M asdf.6000.gz
3,4M asdf.4000.gz
3,2M asdf.2000.gz
2,5M xyz.PT.gz
136K xyz.6000.gz
116K xyz.6000p.gz
88K test.4000.gz
76K test.4000p.gz
44K test.2000.gz
8,0K desc.common.tcl
8,0K wer.2000p.gz
8,0K wer.2000.gz
4,0K ttree.3
du
displays "disk usage"h
is for "human readable" (both, in sort and in du)max-depth=0
means du
will not show sizes of subfolders (remove that if you want to show all sizes of every file in every sub-, subsub-, ..., folder)r
is for "reverse" (biggest file first)When I came to this question, I wanted to clean up my file system. The command line tool ncdu
is way better suited to this task.
Installation on Ubuntu:
$ sudo apt-get install ncdu
Usage:
Just type ncdu [path]
in the command line. After a few seconds for analyzing the path, you will see something like this:
$ ncdu 1.11 ~ Use the arrow keys to navigate, press ? for help
--- / ---------------------------------------------------------
. 96,1 GiB [##########] /home
. 17,7 GiB [# ] /usr
. 4,5 GiB [ ] /var
1,1 GiB [ ] /lib
732,1 MiB [ ] /opt
. 275,6 MiB [ ] /boot
198,0 MiB [ ] /storage
. 153,5 MiB [ ] /run
. 16,6 MiB [ ] /etc
13,5 MiB [ ] /bin
11,3 MiB [ ] /sbin
. 8,8 MiB [ ] /tmp
. 2,2 MiB [ ] /dev
! 16,0 KiB [ ] /lost+found
8,0 KiB [ ] /media
8,0 KiB [ ] /snap
4,0 KiB [ ] /lib64
e 4,0 KiB [ ] /srv
! 4,0 KiB [ ] /root
e 4,0 KiB [ ] /mnt
e 4,0 KiB [ ] /cdrom
. 0,0 B [ ] /proc
. 0,0 B [ ] /sys
@ 0,0 B [ ] initrd.img.old
@ 0,0 B [ ] initrd.img
@ 0,0 B [ ] vmlinuz.old
@ 0,0 B [ ] vmlinuz
Delete the currently highlighted element with d, exit with CTRL + c
TL;DR: add the parameter cursorclass=MySQLdb.cursors.DictCursor
at the end of your MySQLdb.connect
.
I had a working code and the DB moved, I had to change the host/user/pass. After this change, my code stopped working and I started getting this error. Upon closer inspection, I copy-pasted the connection string on a place that had an extra directive. The old code read like:
conn = MySQLdb.connect(host="oldhost",
user="olduser",
passwd="oldpass",
db="olddb",
cursorclass=MySQLdb.cursors.DictCursor)
Which was replaced by:
conn = MySQLdb.connect(host="newhost",
user="newuser",
passwd="newpass",
db="newdb")
The parameter cursorclass=MySQLdb.cursors.DictCursor
at the end was making python allow me to access the rows using the column names as index. But the poor copy-paste eliminated that, yielding the error.
So, as an alternative to the solutions already presented, you can also add this parameter and access the rows in the way you originally wanted. ^_^ I hope this helps others.
If you want to run the script directly, you can:
PYTHONPATH
).sys.path
in the your script.Then:
import module_you_wanted
This worked perfectly
public class BackButton extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_box);
Toolbar chatbox_toolbar=(Toolbar)findViewById(R.id.chat_box_toolbar);
chatbox_toolbar.setTitle("Demo Back Button");
chatbox_toolbar.setTitleTextColor(getResources().getColor(R.color.white));
setSupportActionBar(chatbox_toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
chatbox_toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Define Back Button Function
}
});
}
}
As stated here: Why use Fragment#setRetainInstance(boolean)?
you can also use fragments method setRetainInstance(true)
like this:
public class MyFragment extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// keep the fragment and all its data across screen rotation
setRetainInstance(true);
}
}
Yes, that is possible. The challenge, however, is to do their layout properly. The easiest way to do it would be to have an AbsoluteLayout and then put the two images where you want them to be. You don't need to do anything special for the transparent png except having it added later to the layout.
You could use Timestamp.valueOf(String)
. The documentation states that it understands timestamps in the format yyyy-mm-dd hh:mm:ss[.f...]
, so you might need to change the field separators in your incoming string.
Then again, if you're going to do that then you could just parse it yourself and use the setNanos
method to store the microseconds.
I'm having a problem with your script in Firefox. When I scroll down, the script continues to add a margin to the page and I never reach the bottom of the page. This occurs because the ActionBox is still part of the page elements. I posted a demo here.
position: fixed
to the CSS definition, but I see this won't work for youtop
.UPDATED:
CSS
#ActionBox {
position: relative;
float: right;
}
Script
var alert_top = 0;
var alert_margin_top = 0;
$(function() {
alert_top = $("#ActionBox").offset().top;
alert_margin_top = parseInt($("#ActionBox").css("margin-top"),10);
$(window).scroll(function () {
var scroll_top = $(window).scrollTop();
if (scroll_top > alert_top) {
$("#ActionBox").css("margin-top", ((scroll_top-alert_top)+(alert_margin_top*2)) + "px");
console.log("Setting margin-top to " + $("#ActionBox").css("margin-top"));
} else {
$("#ActionBox").css("margin-top", alert_margin_top+"px");
};
});
});
Also it is important to add a base (10 in this case) to your parseInt()
, e.g.
parseInt($("#ActionBox").css("top"),10);
I had to do a lot of settings edits like the previous answers, so I don't know which made it work after a lot of modifications.
Nothing worked until I closed and openen my IDE, but the last three things I did was disable the lonefy.vscode-js-css-html-formatter
, "html.format.enable": true,
and restart Visual Studio.
{
"editor.suggestSelection": "first",
"vsintellicode.modify.editor.suggestSelection": "automaticallyOverrodeDefaultValue",
"workbench.colorTheme": "Default Light+",
"[html]": {
"editor.defaultFormatter": "vscode.html-language-features",
"editor.tabSize": 2,
"editor.detectIndentation": false,
"editor.insertSpaces": true
},
"typescript.format.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces": true,
"editor.tabSize": 2,
"typescript.format.insertSpaceAfterConstructor": true,
"files.autoSave": "afterDelay",
"html.format.indentHandlebars": true,
"html.format.indentInnerHtml": true,
"html.format.enable": true,
"editor.detectIndentation": false,
"editor.insertSpaces": true,
}
Multiple commands' output can be redirected. This works for either the command line or most usefully in a bash script. The -s
directs the password prompt to the screen.
Hereblock cmds stdout/stderr are sent to seperate files and nothing to display.
sudo -s -u username <<'EOF' 2>err 1>out
ls; pwd;
EOF
Hereblock cmds stdout/stderr are sent to a single file and display.
sudo -s -u username <<'EOF' 2>&1 | tee out
ls; pwd;
EOF
Hereblock cmds stdout/stderr are sent to separate files and stdout to display.
sudo -s -u username <<'EOF' 2>err | tee out
ls; pwd;
EOF
Depending on who you are(whoami) and username a password may or may not be required.
I prefer to use git-bash.exe instead of sh.exe.
start "" "%ProgramFiles%\Git\git-bash.exe" -c "tail -f /c/Windows/win.ini"
You can stop closing the window when call /usr/bin/bash --login -i
in the end;
start "" "%ProgramFiles%\Git\git-bash.exe" -c "echo 1 && echo 2 && /usr/bin/bash --login -i"
Note: I'm not sure this is a good way :)
try setting this
CATALINA_OPTS="-Djava.awt.headless=true -Dfile.encoding=UTF-8
-server -Xms1536m -Xmx1536m
-XX:NewSize=256m -XX:MaxNewSize=256m -XX:PermSize=256m
-XX:MaxPermSize=256m -XX:+DisableExplicitGC"
in {$tomcat-folder}\bin\setenv.sh
(create it if necessary).
See http://www.mkyong.com/tomcat/tomcat-javalangoutofmemoryerror-permgen-space/ for more details.
Regarding your question (b), be aware that the Websocket specification hasn't been finalised. According to the W3C:
Implementors should be aware that this specification is not stable.
Personally I regard Websockets to be waaay too bleeding edge to use at present. Though I'll probably find them useful in a year or so.
You should learn about EAFP vs LBYL.
from sys import stdin, stdout
def main(infile=stdin, outfile=stdout):
if isinstance(infile, basestring):
infile=open(infile,'r')
if isinstance(outfile, basestring):
outfile=open(outfile,'w')
for lineno, line in enumerate(infile, 1):
line = line.strip()
try:
print >>outfile, int(line,16)
except ValueError:
return "Bad value at line %i: %r" % (lineno, line)
if __name__ == "__main__":
from sys import argv, exit
exit(main(*argv[1:]))
Try this code.
<!DOCTYPE HTML>
<html>
<head>
<title>PhoneGap</title>
<script type="text/javascript" charset="utf-8" src="cordova-1.5.0.js"></script>
<script type="text/javascript" charset="utf-8">
function onLoad()
{
document.addEventListener("deviceready", onDeviceReady, true);
}
function exitFromApp()
{
navigator.app.exitApp();
}
</script>
</head>
<body onload="onLoad();">
<button name="buttonClick" onclick="exitFromApp()">Click Me!</button>
</body>
</html>
Replace src="cordova-1.5.0.js" with your phonegap js .
This is, IMHO, the most generic and robust solution (if your actions are user-triggered, eg 'user clicks on a button'):
As an example, note this elegant solution to adding "Are you sure?" popup to any button just by decorating a button with an attribute. We will conditionally continue default behavior if the user doesn't opt out.
1. Let's add to every button that we want an "are you sure" popup a warning text:
<button class="btn btn-success-outline float-right" type="submit" ays_text="You will lose any unsaved changes... Do you want to continue?" >Do something dangerous</button>
2. Attach handlers to ALL such buttons:
$('button[ays_text]').click(function (e, from) {
if (from == null) { // user clicked it!
var btn = $(this);
e.preventDefault();
if (confirm() == true) {
btn.trigger('click', ['your-app-name-here-or-anything-that-is-not-null']);
}
}
// otherwise - do nothing, ie continue default
});
That's it.
Here is a code sample which should pretty much sum this up for you... In addition to the below, showing how you can't access a default in another package there is one more thing.
Default is not accessible in a subclass if the class that subclasses it is in another package, but it is accessible if the subclass is in the same package.
package main;
public class ClassA {
private int privateVar;
public int publicVar;
int defaultVar;
}
package main;
public class ClassB {
public static void main(String[] args) {
ClassA a = new ClassA();
int v1 = a.publicVar; // Works
int v2 = a.defaultVar; // Works
int v3 = a.privateVar; // Doesn't work
}
}
package other;
public class ClassC {
public static void main(String[] args) {
ClassA a = new ClassA();
int v1 = a.publicVar; // Works
int v2 = a.defaultVar; // Doesn't work
int v3 = a.privateVar; // Doesn't work
}
}
Unfortunately node does not support for each ... in
, even though it is specified in JavaScript 1.6. Chrome uses the same JavaScript engine and is reported as having a similar shortcoming.
You'll have to settle for array.forEach(function(item) { /* etc etc */ })
.
EDIT: From Google's official V8 website:
V8 implements ECMAScript as specified in ECMA-262.
On the same MDN website where it says that for each ...in
is in JavaScript 1.6, it says that it is not in any ECMA version - hence, presumably, its absence from Node.
I found another set of examples for customizing an AlertDialog from a guy named Mossila. I think they're better than Google's examples. To quickly see Google's API demos, you must import their demo jar(s) into your project, which you probably don't want.
But Mossila's example code is fully self-contained. It can be directly cut-and-pasted into your project. It just works! Then you only need to tweak it to your needs. See here
When you write to the file via file output stream, the file will be created automatically. but make sure all necessary directories ( folders) are created.
String absolutePath = ...
try{
File file = new File(absolutePath);
file.mkdirs() ;
//all parent folders are created
//now the file will be created when you start writing to it via FileOutputStream.
}catch (Exception e){
System.out.println("Error : "+ e.getmessage());
}
Windows -> Preferences -> Java Compiler
HashMaps don't allow access by position, it only knows about the hash code and and it can retrieve the value if it can calculate the hash code of the key. TreeMaps have a notion of ordering. Linkedhas maps preserve the order in which they entered the map.
If you get this message after doing a git pull remote branch
, try following it up with a git fetch
. (Optionally, run git fetch -p
to prune deleted branches from the repo)
Fetch seems to update the local representation of the remote branch, which doesn't necessarily happen when you do a git pull remote branch
.
When asking a user for a response to put into a cell using the InputBox method, there are usually three things that can happen¹.
If you are putting the return value into a cell, your own logic stream will dictate what you want to do about the latter two scenarios. You may want to clear the cell or you may want to leave the cell contents alone. Here is how to handle the various outcomes with a variant type variable and a Select Case statement.
Dim returnVal As Variant
returnVal = InputBox(Prompt:="Type a value:", Title:="Test Data")
'if the user clicked Cancel, Close or Esc the False
'is translated to the variant as a vbNullString
Select Case True
Case Len(returnVal) = 0
'no value but user clicked OK - clear the target cell
Range("A2").ClearContents
Case Else
'returned a value with OK, save it
Range("A2") = returnVal
End Select
¹ There is a fourth scenario when a specific type of InputBox method is used. An InputBox can return a formula, cell range error or array. Those are special cases and requires using very specific syntax options. See the supplied link for more.
Regarding which python version to use, Mac OS usually ships an old version of python. It's a good idea to upgrade to a newer version. You can download a .dmg from http://www.python.org/download/ . If you do that, remember to update the path. You can find the exact commands here http://farmdev.com/thoughts/66/python-3-0-on-mac-os-x-alongside-2-6-2-5-etc-/
You can use the shorthand flex property and set it to
flex: 0 0 100%;
That's flex-grow
, flex-shrink
, and flex-basis
in one line. Flex shrink was described above, flex grow is the opposite, and flex basis is the size of the container.
Hi the problem is in FileDownloader class
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
You need to remove the above two lines and everything will work fine. Please mark the question as answered if it is working as expected.
Latest solution for the same problem is updated Android PDF Write / Read using Android 9 (API level 28)
Attaching the working code with screenshots.
MainActivity.java
package com.example.downloadread;
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void download(View v)
{
new DownloadFile().execute("http://maven.apache.org/maven-1.x/maven.pdf", "maven.pdf");
}
public void view(View v)
{
File pdfFile = new File(Environment.getExternalStorageDirectory() + "/testthreepdf/" + "maven.pdf"); // -> filename = maven.pdf
Uri path = Uri.fromFile(pdfFile);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try{
startActivity(pdfIntent);
}catch(ActivityNotFoundException e){
Toast.makeText(MainActivity.this, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
}
}
private class DownloadFile extends AsyncTask<String, Void, Void>{
@Override
protected Void doInBackground(String... strings) {
String fileUrl = strings[0]; // -> http://maven.apache.org/maven-1.x/maven.pdf
String fileName = strings[1]; // -> maven.pdf
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "testthreepdf");
folder.mkdir();
File pdfFile = new File(folder, fileName);
try{
pdfFile.createNewFile();
}catch (IOException e){
e.printStackTrace();
}
FileDownloader.downloadFile(fileUrl, pdfFile);
return null;
}
}
}
FileDownloader.java
package com.example.downloadread;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class FileDownloader {
private static final int MEGABYTE = 1024 * 1024;
public static void downloadFile(String fileUrl, File directory){
try {
URL url = new URL(fileUrl);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
//urlConnection.setRequestMethod("GET");
//urlConnection.setDoOutput(true);
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(directory);
int totalSize = urlConnection.getContentLength();
byte[] buffer = new byte[MEGABYTE];
int bufferLength = 0;
while((bufferLength = inputStream.read(buffer))>0 ){
fileOutputStream.write(buffer, 0, bufferLength);
}
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.downloadread"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.downloadread.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="15dp"
android:text="download"
android:onClick="download" />
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/button1"
android:layout_marginTop="38dp"
android:text="view"
android:onClick="view" />
</RelativeLayout>
I'm fairly certain the answer is: No. You can select options with JavaScript but not open the select. You'd have to use a custom solution.
Note: All of the following instructions apply universally (aka to all OSes) unless otherwise specified.
You will need:
Change the file extension of the .apk
file by either adding a .zip
extension to the filename, or to change .apk
to .zip
.
For example, com.example.apk
becomes com.example.zip
, or com.example.apk.zip
. Note that on Windows and macOS, it may prompt you whether you are sure you want to change the file extension. Click OK or Add if you're using macOS:
Extract the renamed APK file in a specific folder. For example, let that folder be demofolder
.
If it didn't work, try opening the file in another application such as WinZip or 7-Zip.
For macOS, you can try running unzip
in Terminal (available at /Applications/Terminal.app
), where it takes one or more arguments: the file to unzip + optional arguments. See man unzip
for documentation and arguments.
Download dex2jar
(see all releases on GitHub) and extract that zip file in the same folder as stated in the previous point.
Open command prompt (or a terminal) and change your current directory to the folder created in the previous point and type the command d2j-dex2jar.bat classes.dex
and press enter. This will generate classes-dex2jar.jar
file in the same folder.
d2j-dex2jar.bat
with d2j-dex2jar.sh
. In other words, run d2j-jar2dex.sh classes.dex
in the terminal and press enter.Download Java Decompiler (see all releases on Github) and extract it and start (aka double click) the executable/application.
From the JD-GUI window, either drag and drop the generated classes-dex2jar.jar
file into it, or go to File > Open File...
and browse for the jar.
Next, in the menu, go to File > Save All Sources
(Windows: Ctrl+Alt+S, macOS: ?+?+S). This should open a dialog asking you where to save a zip file named `classes-dex2jar.jar.src.zip" consisting of all packages and java files. (You can rename the zip file to be saved)
Extract that zip file (classes-dex2jar.jar.src.zip
) and you should get all java files of the application.
xml
files from APKapktool
website for installation instructions and moreWindows:
myxmlfolder
).myxmlfolder
folder and rename the apktool jar file to apktool.jar
..apk
file in the same folder (i.e myxmlfolder
).Open the command prompt (or terminal) and change your current directory to the folder where apktool
is stored (in this case, myxmlfolder
). Next, type the command apktool if framework-res.apk
.
What we're doing here is that we are installing a framework. For more info, see the docs.
In the command prompt, type the command apktool d filename.apk
(where filename
is the name of apk file). This should decode the file. For more info, see the docs.
This should result in a folder filename.out
being outputted, where filename
is the original name of the apk file without the .apk
file extension. In this folder are all the XML files such as layout, drawables etc.
Source: How to get source code from APK file - Comptech Blogspot
div {_x000D_
white-space: nowrap;_x000D_
overflow: hidden;_x000D_
}
_x000D_
<div>test that doesn't wrap</div>
_x000D_
Note: this only works on block elements. If you need to do this to table cells (for example) you need to put a div inside the table cell as table cells have display table-cell not block.
As of CSS3, this is supported for table cells as well.
I had a similar issue, no videos would play in Chrome. Tried installing beta 64bit, going back to Chrome 32bit release.
The only thing that worked for me was updating my video drivers.
I have the NVIDIA GTS 240. Downloaded, installed the drivers and restarted and Chrome 38.0.2125.77 beta-m (64-bit) starting playing HTML5 videos again on youtube, vimeo and others. Hope this helps anyone else.
NOTICE that append generates a new slice if cap is not sufficient. @kostix's answer is correct, or you can pass slice argument by pointer!
If you do not care about tick shifting (depending on how long did it took previously on each execution) and you do not want to use channels, it's possible to use native range function.
i.e.
package main
import "fmt"
import "time"
func main() {
go heartBeat()
time.Sleep(time.Second * 5)
}
func heartBeat() {
for range time.Tick(time.Second * 1) {
fmt.Println("Foo")
}
}
You can also invert the position when you request an object:
Object obj = list.get(list.size() - 1 - position);
Hemnath
If your variable is the percentage:
var myWidth = 70;
$('div#somediv').width(myWidth + '%');
If your variable is in pixels, and you want the percentage it take up of the parent:
var myWidth = 140;
var myPercentage = (myWidth / $('div#somediv').parent().width()) * 100;
$('div#somediv').width(myPercentage + '%');
It depends on the context, but here's an example of "-and" in action:
get-childitem | where-object { $_.Name.StartsWith("f") -and $_.Length -gt 10kb }
So that's getting all the files bigger than 10kb in a directory whose filename starts with "f".
I have put together a collection of categories for NSData and NSString which uses solutions found on Jeff LaMarche's blog and some hints by Quinn Taylor here on Stack Overflow.
It uses categories to extend NSData to provide AES256 encryption and also offers an extension of NSString to BASE64-encode encrypted data safely to strings.
Here's an example to show the usage for encrypting strings:
NSString *plainString = @"This string will be encrypted";
NSString *key = @"YourEncryptionKey"; // should be provided by a user
NSLog( @"Original String: %@", plainString );
NSString *encryptedString = [plainString AES256EncryptWithKey:key];
NSLog( @"Encrypted String: %@", encryptedString );
NSLog( @"Decrypted String: %@", [encryptedString AES256DecryptWithKey:key] );
Get the full source code here:
Thanks for all the helpful hints!
-- Michael
From Oracle 18c
you could use Inline External Tables:
Inline external tables enable the runtime definition of an external table as part of a SQL statement, without creating the external table as persistent object in the data dictionary.
With inline external tables, the same syntax that is used to create an external table with a CREATE TABLE statement can be used in a SELECT statement at runtime. Specify inline external tables in the FROM clause of a query block. Queries that include inline external tables can also include regular tables for joins, aggregation, and so on.
INSERT INTO target_table(time_id, prod_id, quantity_sold, amount_sold)
SELECT time_id, prod_id, quantity_sold, amount_sold
FROM EXTERNAL (
(time_id DATE NOT NULL,
prod_id INTEGER NOT NULL,
quantity_sold NUMBER(10,2),
amount_sold NUMBER(10,2))
TYPE ORACLE_LOADER
DEFAULT DIRECTORY data_dir1
ACCESS PARAMETERS (
RECORDS DELIMITED BY NEWLINE
FIELDS TERMINATED BY '|')
LOCATION ('sales_9.csv') REJECT LIMIT UNLIMITED) sales_external;
I use GET/204 with a RESTful collection that is a positional array of known fixed length but with holes.
GET /items
200: ["a", "b", null]
GET /items/0
200: "a"
GET /items/1
200: "b"
GET /items/2
204:
GET /items/3
404: Not Found
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {_x000D_
var target = $(e.target).attr("href") // activated tab_x000D_
alert(target);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<ul id="myTab" class="nav nav-tabs">_x000D_
<li class="active"><a href="#home" data-toggle="tab">Home</a></li>_x000D_
<li class=""><a href="#profile" data-toggle="tab">Profile</a></li>_x000D_
</ul>_x000D_
<div id="myTabContent" class="tab-content">_x000D_
<div class="tab-pane fade active in" id="home">_x000D_
home tab!_x000D_
</div>_x000D_
<div class="tab-pane fade" id="profile">_x000D_
profile tab!_x000D_
</div>_x000D_
</div>
_x000D_
While the accepted answer solved the OP's original problem, most people finding this question through a Google search are likely having an entirely different problem which just happens to throw the same no suitable HttpMessageConverter found exception.
What happens under the covers is that MappingJackson2HttpMessageConverter
swallows any exceptions that occur in its canRead()
method, which is supposed to auto-detect whether the payload is suitable for json decoding. The exception is replaced by a simple boolean return that basically communicates sorry, I don't know how to decode this message to the higher level APIs (RestClient
). Only after all other converters' canRead() methods return false, the no suitable HttpMessageConverter found exception is thrown by the higher-level API, totally obscuring the true problem.
For people who have not found the root cause (like you and me, but not the OP), the way to troubleshoot this problem is to place a debugger breakpoint on onMappingJackson2HttpMessageConverter.canRead()
, then enable a general breakpoint on any exception, and hit Continue. The next exception is the true root cause.
My specific error happened to be that one of the beans referenced an interface that was missing the proper deserialization annotations.
UPDATE FROM THE FUTURE
This has proven to be such a recurring issue across so many of my projects, that I've developed a more proactive solution. Whenever I have a need to process JSON exclusively (no XML or other formats), I now replace my RestTemplate
bean with an instance of the following:
public class JsonRestTemplate extends RestTemplate {
public JsonRestTemplate(
ClientHttpRequestFactory clientHttpRequestFactory) {
super(clientHttpRequestFactory);
// Force a sensible JSON mapper.
// Customize as needed for your project's definition of "sensible":
ObjectMapper objectMapper = new ObjectMapper()
.registerModule(new Jdk8Module())
.registerModule(new JavaTimeModule())
.configure(
SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
MappingJackson2HttpMessageConverter jsonMessageConverter = new MappingJackson2HttpMessageConverter() {
public boolean canRead(java.lang.Class<?> clazz,
org.springframework.http.MediaType mediaType) {
return true;
}
public boolean canRead(java.lang.reflect.Type type,
java.lang.Class<?> contextClass,
org.springframework.http.MediaType mediaType) {
return true;
}
protected boolean canRead(
org.springframework.http.MediaType mediaType) {
return true;
}
};
jsonMessageConverter.setObjectMapper(objectMapper);
messageConverters.add(jsonMessageConverter);
super.setMessageConverters(messageConverters);
}
}
This customization makes the RestClient
incapable of understanding anything other than JSON. The upside is that any error messages that may occur will be much more explicit about what's wrong.
If somehow balancePanel won't work, you could use this:
this.Location = new Point(127, 283);
or
anotherObject.Location = new Point(127, 283);
String is immutable and it goes to the string pool. Once written, it cannot be overwritten.
char[]
is an array which you should overwrite once you used the password and this is how it should be done:
char[] passw = request.getPassword().toCharArray()
if (comparePasswords(dbPassword, passw) {
allowUser = true;
cleanPassword(passw);
cleanPassword(dbPassword);
passw=null;
}
private static void cleanPassword (char[] pass) {
Arrays.fill(pass, '0');
}
One scenario where the attacker could use it is a crashdump - when the JVM crashes and generates a memory dump - you will be able to see the password.
That is not necessarily a malicious external attacker. This could be a support user that has access to the server for monitoring purposes. He could peek into a crashdump and find the passwords.
find ./ -cTime -1 -type f
OR
find ./ -cmin -60 -type f
Just create a new theme in res/values/styles.xml where you change the "colorPrimaryDark" which is the color of the status bar:
<style name="AppTheme.GrayStatusBar" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorPrimaryDark">@color/colorGray</item>
</style>
And modify the activity theme in AndroidManifest.xml to the one you want, on the next activity you can change the color back to the original one by selecting the original theme:
<activity
android:name=".LoginActivity"
android:theme="@style/AppTheme.GrayStatusBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
This is how your res/values/colors.xml should look like:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#c6d6f0</color>
<color name="colorGray">#757575</color>
</resources>
Label without an onclick will behave as you would expect. It changes the input. What you relly want is to execute selectAll()
when you click on a label, right?
Then only add select all to the label onclick. Or wrap the input into the the label and assign onclick only for the label
<label for="check_all_1" onclick="selectAll(document.wizard_form, this);">
<input type="checkbox" id="check_all_1" name="check_all_1" title="Select All">
Select All
</label>
or
if (StringA.Equals(StringB, StringComparison.CurrentCultureIgnoreCase)) {
but you need to be sure that StringA is not null. So probably better tu use:
string.Equals(StringA , StringB, StringComparison.CurrentCultureIgnoreCase);
as John suggested
EDIT: corrected the bug
after that all html we want to write these lines of code
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/themes/base/jquery-ui.css" type="text/css" media="all">
<script>
$('#date').datepicker({
changeMonth: true,
changeYear: true,
showButtonPanel: true,
yearRange: "-100:+0",
dateFormat: 'dd/mm/yy'
});
</script>
I always use pseudo elements :before
and :after
for changing the appearance of checkboxes and radio buttons. it's works like a charm.
Refer this link for more info
Steps
visibility:hidden
or opacity:0
or position:absolute;left:-9999px
etc.:before
element and pass either an empty or a non-breaking space '\00a0'
;:checked
state, pass the unicode content: "\2713"
, which is a checkmark;:focus
style to make the checkbox accessible.Here is how I did it.
.box {_x000D_
background: #666666;_x000D_
color: #ffffff;_x000D_
width: 250px;_x000D_
padding: 10px;_x000D_
margin: 1em auto;_x000D_
}_x000D_
p {_x000D_
margin: 1.5em 0;_x000D_
padding: 0;_x000D_
}_x000D_
input[type="checkbox"] {_x000D_
visibility: hidden;_x000D_
}_x000D_
label {_x000D_
cursor: pointer;_x000D_
}_x000D_
input[type="checkbox"] + label:before {_x000D_
border: 1px solid #333;_x000D_
content: "\00a0";_x000D_
display: inline-block;_x000D_
font: 16px/1em sans-serif;_x000D_
height: 16px;_x000D_
margin: 0 .25em 0 0;_x000D_
padding: 0;_x000D_
vertical-align: top;_x000D_
width: 16px;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:before {_x000D_
background: #fff;_x000D_
color: #333;_x000D_
content: "\2713";_x000D_
text-align: center;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:after {_x000D_
font-weight: bold;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:focus + label::before {_x000D_
outline: rgb(59, 153, 252) auto 5px;_x000D_
}
_x000D_
<div class="content">_x000D_
<div class="box">_x000D_
<p>_x000D_
<input type="checkbox" id="c1" name="cb">_x000D_
<label for="c1">Option 01</label>_x000D_
</p>_x000D_
<p>_x000D_
<input type="checkbox" id="c2" name="cb">_x000D_
<label for="c2">Option 02</label>_x000D_
</p>_x000D_
<p>_x000D_
<input type="checkbox" id="c3" name="cb">_x000D_
<label for="c3">Option 03</label>_x000D_
</p>_x000D_
</div>_x000D_
</div>
_x000D_
Much more stylish using :before
and :after
body{_x000D_
font-family: sans-serif; _x000D_
}_x000D_
_x000D_
.container {_x000D_
margin-top: 50px;_x000D_
margin-left: 20px;_x000D_
margin-right: 20px;_x000D_
}_x000D_
.checkbox {_x000D_
width: 100%;_x000D_
margin: 15px auto;_x000D_
position: relative;_x000D_
display: block;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"] {_x000D_
width: auto;_x000D_
opacity: 0.00000001;_x000D_
position: absolute;_x000D_
left: 0;_x000D_
margin-left: -20px;_x000D_
}_x000D_
.checkbox label {_x000D_
position: relative;_x000D_
}_x000D_
.checkbox label:before {_x000D_
content: '';_x000D_
position: absolute;_x000D_
left: 0;_x000D_
top: 0;_x000D_
margin: 4px;_x000D_
width: 22px;_x000D_
height: 22px;_x000D_
transition: transform 0.28s ease;_x000D_
border-radius: 3px;_x000D_
border: 2px solid #7bbe72;_x000D_
}_x000D_
.checkbox label:after {_x000D_
content: '';_x000D_
display: block;_x000D_
width: 10px;_x000D_
height: 5px;_x000D_
border-bottom: 2px solid #7bbe72;_x000D_
border-left: 2px solid #7bbe72;_x000D_
-webkit-transform: rotate(-45deg) scale(0);_x000D_
transform: rotate(-45deg) scale(0);_x000D_
transition: transform ease 0.25s;_x000D_
will-change: transform;_x000D_
position: absolute;_x000D_
top: 12px;_x000D_
left: 10px;_x000D_
}_x000D_
.checkbox input[type="checkbox"]:checked ~ label::before {_x000D_
color: #7bbe72;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"]:checked ~ label::after {_x000D_
-webkit-transform: rotate(-45deg) scale(1);_x000D_
transform: rotate(-45deg) scale(1);_x000D_
}_x000D_
_x000D_
.checkbox label {_x000D_
min-height: 34px;_x000D_
display: block;_x000D_
padding-left: 40px;_x000D_
margin-bottom: 0;_x000D_
font-weight: normal;_x000D_
cursor: pointer;_x000D_
vertical-align: sub;_x000D_
}_x000D_
.checkbox label span {_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
-webkit-transform: translateY(-50%);_x000D_
transform: translateY(-50%);_x000D_
}_x000D_
.checkbox input[type="checkbox"]:focus + label::before {_x000D_
outline: 0;_x000D_
}
_x000D_
<div class="container"> _x000D_
<div class="checkbox">_x000D_
<input type="checkbox" id="checkbox" name="" value="">_x000D_
<label for="checkbox"><span>Checkbox</span></label>_x000D_
</div>_x000D_
_x000D_
<div class="checkbox">_x000D_
<input type="checkbox" id="checkbox2" name="" value="">_x000D_
<label for="checkbox2"><span>Checkbox</span></label>_x000D_
</div>_x000D_
</div>
_x000D_
Consider using the Comparator
interface described here which uses generics so you can avoid casting Object
to Student
.
As Eugene Retunsky said, your first part is the correct way to compare String
s. Also if the lastName
s are equal I think you meant to compare firstName
s, in which case just use compareTo
in the same way.
If you're trying to do this from the command line, you may be encountering an issue where a machine-wide environment variable 'Platform' is being set for you and working against you. I can reproduce this if I use the VS2012 Command window instead of a regular windows Command window.
At the command prompt type:
set platform
In a VS2012 Command window, I have a value of 'X64' preset. That seems to interfere with whatever is in my solution file.
In a regular Command window, the 'set' command results in a "variable not defined" message...which is good.
If the result of your 'set' command above returns no environment variable value, you should be good to go.
I think most of the people replying here didn't quite understand the question, or else I might be mistaken.
The question is "how to check whether or not a selector exists in jQuery."
Most people have taken this for "how to check whether an element exists in the DOM using jQuery." Hardly interchangeable.
jQuery allows you to create custom selectors, but see here what happens when you try to use on e before initializing it;
$(':YEAH');
"Syntax error, unrecognized expression: YEAH"
After running into this, I realized it was simply a matter of checking
if ($.expr[':']['YEAH']) {
// Query for your :YEAH selector with ease of mind.
}
Cheers.
$("#example").dataTable(
{
"aoColumnDefs": [{
"bSortable": false,
"aTargets": [0, 1, 2, 3, 4, 5]
}]
}
);
If you just setting up development env, then use pip freeze file, caz that makes the git repo clean.
Then if doing production deployment, then checkin the whole venv folder. That will make your deployment more reproducible, not need those libxxx-dev packages, and avoid the internet issues.
So there are two repos. One for your main source code, which includes a requirements.txt. And a env repo, which contains the whole venv folder.
Use ls()
function to see what R objects are occupying space. use rm("objectName") to clear the objects from R memory that is no longer required. See this too.
There are 2 major differences.
Technical, there are 3 major differences:
First and foremost, Community doesn't have TFS support.
You'll just have to use git (arguable whether this constitutes a disadvantage or whether this actually is a good thing).
Note: This is what MS wrote. Actually, you can check-in&out with TFS as normal, if you have a TFS server in the network. You just cannot use Visual Studio as TFS SERVER.
Second, VS Community is severely limited in its testing capability.
Only unit tests. No Performance tests, no load tests, no performance profiling.
Third, VS Community's ability to create Virtual Environments has been severely cut.
On the other hand, syntax highlighting, IntelliSense, Step-Through debugging, GoTo-Definition, Git-Integration and Build/Publish are really all the features I need, and I guess that applies to a lot of developers.
For all other things, there are tools that do the same job faster, better and cheaper.
If you, like me, anyway use git, do unit testing with NUnit, and use Java-Tools to do Load-Testing on Linux plus TeamCity for CI, VS Community is more than sufficient, technically speaking.
Licensing:
A) If you're an individual developer (no enterprise, no organization), no difference (AFAIK), you can use CommunityEdition like you'd use the paid edition (as long as you don't do subcontracting)
B) You can use CommunityEdition freely for OpenSource (OSI) projects
C) If you're an educational insitution, you can use CommunityEdition freely (for education/classroom use)
D) If you're an enterprise with 250 PCs or users or more than one million US dollars in revenue (including subsidiaries), you are NOT ALLOWED to use CommunityEdition.
E) If you're not an enterprise as defined above, and don't do OSI or education, but are an "enterprise"/organization, with 5 or less concurrent (VS) developers, you can use VS Community freely (but only if you're the owner of the software and sell it, not if you're a subcontractor creating software for a larger enterprise, software which in the end the enterprise will own), otherwise you need a paid edition.
The above does not consitute legal advise.
See also:
https://softwareengineering.stackexchange.com/questions/262916/understanding-visual-studio-community-edition-license
Not sure in which Swift version this feature was added, but right now (Swift 2.1) you only need this code:
enum Audience : String {
case public
case friends
case private
}
let audience = Audience.public.rawValue // "public"
When strings are used for raw values, the implicit value for each case is the text of that case’s name.
[...]
enum CompassPoint : String { case north, south, east, west }
In the example above, CompassPoint.south has an implicit raw value of "south", and so on.
You access the raw value of an enumeration case with its rawValue property:
let sunsetDirection = CompassPoint.west.rawValue // sunsetDirection is "west"
git show somebranch:path/to/your/file
you can also do multiple files and have them concatenated:
git show branchA~10:fileA branchB^^:fileB
You do not have to provide the full path to the file, relative paths are acceptable e.g.:
git show branchA~10:../src/hello.c
If you want to get the file in the local directory (revert just one file) you can checkout:
git checkout somebranch^^^ -- path/to/file
If you want that image to be zoomed on mouse hover :
$(document).ready( function() {
$('#div img').hover(
function() {
$(this).animate({ 'zoom': 1.2 }, 400);
},
function() {
$(this).animate({ 'zoom': 1 }, 400);
});
});
?or you may do like this if zoom in and out buttons are used :
$("#ZoomIn").click(ZoomIn());
$("#ZoomOut").click(ZoomOut());
function ZoomIn (event) {
$("#div img").width(
$("#div img").width() * 1.2
);
$("#div img").height(
$("#div img").height() * 1.2
);
},
function ZoomOut (event) {
$("#div img").width(
$("#imgDtls").width() * 0.5
);
$("#div img").height(
$("#div img").height() * 0.5
);
}
I would recommend 422. It's not part of the main HTTP spec, but it is defined by a public standard (WebDAV) and it should be treated by browsers the same as any other 4xx status code.
From RFC 4918:
The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.
This is the first post on google so I thought I'd post different ways that are available and how they compare. Unfortunately I can't figure out how to create a table here, so it's an image. The code for each is below the image using fully qualified names.
My.Application.Info.DirectoryPath
Environment.CurrentDirectory
System.Windows.Forms.Application.StartupPath
AppDomain.CurrentDomain.BaseDirectory
System.Reflection.Assembly.GetExecutingAssembly.Location
System.Reflection.Assembly.GetExecutingAssembly.CodeBase
New System.UriBuilder(System.Reflection.Assembly.GetExecutingAssembly.CodeBase)
Path.GetDirectoryName(Uri.UnescapeDataString((New System.UriBuilder(System.Reflection.Assembly.GetExecutingAssembly.CodeBase).Path)))
Uri.UnescapeDataString((New System.UriBuilder(System.Reflection.Assembly.GetExecutingAssembly.CodeBase).Path))
case when field1>0 then field2/field1 else 0 end as field3
I have this similar problem where I'm able to start the tomcat server but however application not initialized or started, so I have Right clicked on my project --> Deployment Assembly --> Click 'Add' in the right side panel, select 'Java Build path entries' and click 'Next', Now select 'Maven dependencies' and click 'Finish'. Now I run the server and it started the application successfully.
Comparing recursion to iteration is like comparing a phillips head screwdriver to a flat head screwdriver. For the most part you could remove any phillips head screw with a flat head, but it would just be easier if you used the screwdriver designed for that screw right?
Some algorithms just lend themselves to recursion because of the way they are designed (Fibonacci sequences, traversing a tree like structure, etc.). Recursion makes the algorithm more succinct and easier to understand (therefore shareable and reusable).
Also, some recursive algorithms use "Lazy Evaluation" which makes them more efficient than their iterative brothers. This means that they only do the expensive calculations at the time they are needed rather than each time the loop runs.
That should be enough to get you started. I'll dig up some articles and examples for you too.
Link 1: Haskel vs PHP (Recursion vs Iteration)
Here is an example where the programmer had to process a large data set using PHP. He shows how easy it would have been to deal with in Haskel using recursion, but since PHP had no easy way to accomplish the same method, he was forced to use iteration to get the result.
http://blog.webspecies.co.uk/2011-05-31/lazy-evaluation-with-php.html
Link 2: Mastering Recursion
Most of recursion's bad reputation comes from the high costs and inefficiency in imperative languages. The author of this article talks about how to optimize recursive algorithms to make them faster and more efficient. He also goes over how to convert a traditional loop into a recursive function and the benefits of using tail-end recursion. His closing words really summed up some of my key points I think:
"recursive programming gives the programmer a better way of organizing code in a way that is both maintainable and logically consistent."
Link 3: Is recursion ever faster than looping? (Answer)
Here is a link to an answer for a stackoverflow question that is similar to yours. The author points out that a lot of the benchmarks associated with either recursing or looping are very language specific. Imperative languages are typically faster using a loop and slower with recursion and vice-versa for functional languages. I guess the main point to take from this link is that it is very difficult to answer the question in a language agnostic / situation blind sense.
I combined 2 answers here. (@simo and @bresleveloper)
https://stackblitz.com/edit/angular-double-scroll?file=src%2Fapp%2Fapp.component.html
@Component({
selector: 'app-double-scroll',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<div class="wrapper1" #wrapper1>
<div class="div1" #div1></div>
</div>
<div class="wrapper2" #wrapper2>
<div class="div2" #div2>
<ng-content></ng-content>
</div>
</div>
`,
styles: [
`
.wrapper1, .wrapper2 { width: 100%; overflow-x: auto; overflow-y: hidden; }
`,
`
.div1 { overflow: hidden; height: 0.5px;}
`,
`
.div2 { overflow: hidden; min-width: min-content}
`
]
})
export class DoubleScrollComponent implements AfterViewInit {
@ViewChild('wrapper1') wrapper1: ElementRef<any>;
@ViewChild('wrapper2') wrapper2: ElementRef<any>;
@ViewChild('div1') div1: ElementRef<any>;
@ViewChild('div2') div2: ElementRef<any>;
constructor(private _r: Renderer2, private _cd: ChangeDetectorRef) {
}
ngAfterViewInit() {
this._cd.detach();
this._r.setStyle(this.div1.nativeElement, 'width', this.div2.nativeElement.clientWidth + 'px' );
this.wrapper1.nativeElement.onscroll = e => this.wrapper2.nativeElement.scroll((e.target as HTMLElement).scrollLeft, 0)
this.wrapper2.nativeElement.onscroll = e => this.wrapper1.nativeElement.scroll((e.target as HTMLElement).scrollLeft, 0)
}
}
<div style="width: 200px; border: 1px black dashed">
<app-double-scroll>
<div style="min-width: 400px; background-color: red; word-break: keep-all; white-space: nowrap;">
long ass text long ass text long ass text long ass text long ass text long ass text long ass text long ass text long ass text
</div>
</app-double-scroll>
<br>
<hr>
<br>
<app-double-scroll>
<div style="display: inline-block; background-color: green; word-break: keep-all; white-space: nowrap;">
short ass text
</div>
</app-double-scroll>
<br>
<hr>
<br>
<app-double-scroll>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
<td>table cell</td>
</tr>
</tbody>
</table>
</app-double-scroll>
</div>
First, you don't declare the type in Ruby, so you don't need the first string
.
To replace a word in string, you do: sentence.gsub(/match/, "replacement")
.
The R Language Definition is handy for answering these types of questions:
R has three basic indexing operators, with syntax displayed by the following examples
x[i] x[i, j] x[[i]] x[[i, j]] x$a x$"a"For vectors and matrices the
[[
forms are rarely used, although they have some slight semantic differences from the[
form (e.g. it drops any names or dimnames attribute, and that partial matching is used for character indices). When indexing multi-dimensional structures with a single index,x[[i]]
orx[i]
will return thei
th sequential element ofx
.For lists, one generally uses
[[
to select any single element, whereas[
returns a list of the selected elements.The
[[
form allows only a single element to be selected using integer or character indices, whereas[
allows indexing by vectors. Note though that for a list, the index can be a vector and each element of the vector is applied in turn to the list, the selected component, the selected component of that component, and so on. The result is still a single element.
In my case, I was missing the .modal-dialog div
Doesn't fire event: shown.bs.modal
<div id="loadingModal" class="modal fade">
<p>Loading...</p>
</div>
Does fire event: shown.bs.modal
<div id="loadingModal" class="modal fade">
<div class="modal-dialog">
<p>Loading...</p>
</div>
</div>
Here is my function, uses binary search to find item and then inserts appropriately:
function binaryInsert(val, arr){_x000D_
let mid, _x000D_
len=arr.length,_x000D_
start=0,_x000D_
end=len-1;_x000D_
while(start <= end){_x000D_
mid = Math.floor((end + start)/2);_x000D_
if(val <= arr[mid]){_x000D_
if(val >= arr[mid-1]){_x000D_
arr.splice(mid,0,val);_x000D_
break;_x000D_
}_x000D_
end = mid-1;_x000D_
}else{_x000D_
if(val <= arr[mid+1]){_x000D_
arr.splice(mid+1,0,val);_x000D_
break;_x000D_
}_x000D_
start = mid+1;_x000D_
}_x000D_
}_x000D_
return arr;_x000D_
}_x000D_
_x000D_
console.log(binaryInsert(16, [_x000D_
5, 6, 14, 19, 23, 44,_x000D_
35, 51, 86, 68, 63, 71,_x000D_
87, 117_x000D_
]));
_x000D_
Try to reinstall cygwin with selected package:gcc-g++ : gnu compiler collection c++ (from devel category), openssh server and client program (net), make: the gnu version (devel), ncurses terminal (utils), enhanced vim editors (editors), an ANSI common lisp implementation (math) and libncurses-devel (lib).
This library files should be under cygwin\usr\include
Regards.
I'm Using Xampp and Laravel 5.8 in Windows 10, and i've been like this before. When i got this problem, My XAMPP is no have Password
Then I tried to delete some codes in
config>database.php
'password' => env('DB_PASSWORD', ''),
And in .env
DB_PASSWORD=SECRET
the Problem is solved
in python 3.6 and newer, you can format it just like this:
new_string = f'{s} {i}'
print(new_string)
or just:
print(f'{s} {i}')
My issue is :
return __import__('MySQLdb')
ImportError: No module named MySQLdb
and my resolution :
pip install MySQL-python
yum install mysql-devel.x86_64
at the very beginning, i just installed MySQL-python, but the issue still existed. So i think if this issue happened, you should also take mysql-devel into consideration. Hope this helps.
A pull request is just that: a request to merge one branch into another.
Your pull request doesn't "contain" anything, it's just a marker saying "please merge this branch into that one".
The set of changes the PR shows in the web UI is just the changes between the target branch and your feature branch. To modify your pull request, you must modify your feature branch, probably with a force push to the feature branch.
In your case, you'll probably want to amend your commit. Not sure about your exact situation, but some combination of interactive rebase and add -p
should sort you out.
Most answers based on (a1 - a2) or (a1 & a2) would not work if there are duplicate elements in either array. I arrived here looking for a way to see if all letters of a word (split to an array) were part of a set of letters (for scrabble for example). None of these answers worked, but this one does:
def contains_all?(a1, a2)
try = a1.chars.all? do |letter|
a1.count(letter) <= a2.count(letter)
end
return try
end
OpenJDK is a reference model and open source, while Oracle JDK is an implementation of the OpenJDK and is not open source. Oracle JDK is more stable than OpenJDK.
OpenJDK is released under GPL v2 license whereas Oracle JDK is licensed under Oracle Binary Code License Agreement.
OpenJDK and Oracle JDK have almost the same code, but Oracle JDK has more classes and some bugs fixed.
So if you want to develop enterprise/commercial software I would suggest to go for Oracle JDK, as it is thoroughly tested and stable.
I have faced lot of problems with application crashes using OpenJDK, which are fixed just by switching to Oracle JDK
undefined index means that somewhere in the $_POST array, there isn't an index (key) for the key username.
You should be setting your posted values into variables for a more clean solution, and it's a good habit to get into.
If I was having a similar error, I'd do something like this:
$username = $_POST['username']; // you should really do some more logic to see if it's set first
echo $username;
If username didn't turn up, that'd mean I was screwing up somewhere. You can also,
var_dump($_POST);
To see what you're posting. var_dump is really useful as far as debugging. Check it out: var_dump
it takes this command about 2 mins to return the data as there is a lot of data
Probably, Bad Design. Consider using paging here.
default connection time is 30 secs, how do I increase this
As you are facing a timeout on your command, therefore you need to increase the timeout of your sql command. You can specify it in your command like this
// Setting command timeout to 2 minutes
scGetruntotals.CommandTimeout = 120;
I had to insert picture filepath into database using similar method. The query below worked fine:
DECLARE @num INT = 8270058
WHILE(@num<8270284)
begin
INSERT INTO [dbo].[Galleries]
(ImagePath)
VALUES
('~/Content/Galeria/P'+CONVERT(varchar(10), @num)+'.JPG')
SET @num = @num + 1
end
The code for you would be:
DECLARE @num INT = 1000
WHILE(@num<1051)
begin
SELECT @num
SET @num = @num + 1
end
If you need only reading csv files then I recommend this library: A Fast CSV Reader
If you also need to generate csv files then use this one: FileHelpers
Both of them are free and opensource.
This is also found in the UINavigationController class documentation:
navigationItem.hidesBackButton = true
I know this is an old question, but I had this problem recently and none of the answers helped me. However, Corral's comment on Ryan Atkinson's answer did tip me off to the problem.
I had all my compiled class files in target/classes
, which are not packages in my case. I was trying to package it with jar cvfe App.jar target/classes App
, from the root directory of my project, as my App class was in the default unnamed package.
This doesn't work, as the newly created App.jar
will have the class App.class
in the directory target/classes
. If you try to run this jar with java -jar App.jar
, it will complain that it cannot find the App
class. This is because the packages inside App.jar
don't match the actual packages in the project.
This could be solved by creating the jar directly from the target/classes
directory, using jar cvfe App.jar . App
. This is rather cumbersome in my opinion.
The simple solution is to list the folders you want to add with the -C
option instead of using the default way of listing folders. So, in my case, the correct command is java cvfe App.jar App -C target/classes .
. This will directly add all files in the target/classes
directory to the root of App.jar
, thus solving the problem.
date()
itself is only for formatting, but it accepts a second parameter.
date("F j, Y", time() - 60 * 60 * 24);
To keep it simple I just subtract 24 hours from the unix timestamp.
A modern oop-approach is using DateTime
$date = new DateTime();
$date->sub(new DateInterval('P1D'));
echo $date->format('F j, Y') . "\n";
Or in your case (more readable/obvious)
$date = new DateTime();
$date->add(DateInterval::createFromDateString('yesterday'));
echo $date->format('F j, Y') . "\n";
(Because DateInterval
is negative here, we must add()
it here)
See also: DateTime::sub()
and DateInterval
You can use the following
import { find } from 'lodash'
Then to return the entire object (not only its key or value) from the list with the following:
let match = find(savedViews, { 'ID': 'id to match'});
If we declare a variable as static, there will be only one copy of the variable. So, whenever different threads access that variable, there will be only one final value for the variable(since there is only one memory location allocated for the variable).
If a variable is declared as volatile, all threads will have their own copy of the variable but the value is taken from the main memory.So, the value of the variable in all the threads will be the same.
So, in both cases, the main point is that the value of the variable is same across all threads.
You can installing the provider dynamically:
1) Download these jars:
bcprov-jdk15on-152.jar
bcprov-ext-jdk15on-152.jar
2) Copy jars to WEB-INF/lib
(or your classpath)
3) Add provider dynamically:
import org.bouncycastle.jce.provider.BouncyCastleProvider;
...
Security.addProvider(new BouncyCastleProvider());
Or add "sort name" to list alphabetically
Get-ADPrincipalGroupMembership username | select name | sort name
Notwithstanding what Pavel Shved said - that it is probably more advisable to get used to Escaping Insert mode - here is an example set of mappings for quick navigation within Insert mode:
" provide hjkl movements in Insert mode via the <Alt> modifier key
inoremap <A-h> <C-o>h
inoremap <A-j> <C-o>j
inoremap <A-k> <C-o>k
inoremap <A-l> <C-o>l
This will make Alt+h in Insert mode go one character left, Alt+j down and so on, analogously to hjkl in Normal mode.
You have to copy that code into your vimrc file to have it loaded every time you start vim (you can open that by typing :new $myvimrc
starting in Normal mode).
Since the Alt modifier key is not mapped (to something important) by default, you can in the same fashion pull other (or all) functionality from Normal mode to Insert mode. E.g.:
Moving to the beginning of the current word with Alt+b:
inoremap <A-b> <C-o>b
inoremap <A-w> <C-o>w
It is worth mentioning that there may be better uses for the Alt key than replicating Normal mode behaviour: e.g. here are mappings for copying from an adjacent line the portion from the current column till the end of the line:
" Insert the rest of the line below the cursor.
" Mnemonic: Elevate characters from below line
inoremap <A-e>
\<Esc>
\jl
\y$
\hk
\p
\a
" Insert the rest of the line above the cursor.
" Mnemonic: Y depicts a funnel, through which the above line's characters pour onto the current line.
inoremap <A-y>
\<Esc>
\kl
\y$
\hj
\p
\a
(I used \
line continuation and indentation to increase clarity. The commands are interpreted as if written on a single line.)
CTRL-H delete the character in front of the cursor (same as <Backspace>)
CTRL-W delete the word in front of the cursor
CTRL-U delete all characters in front of the cursor (influenced by the 'backspace' option)
(There are no notable built-in hotkeys for movement in Insert mode.)
Reference: :help insert-index
This set of mappings makes the upper Alt+hjkl movements available in the Command-line:
" provide hjkl movements in Command-line mode via the <Alt> modifier key
cnoremap <A-h> <Left>
cnoremap <A-j> <Down>
cnoremap <A-k> <Up>
cnoremap <A-l> <Right>
Alternatively, these mappings add the movements both to Insert mode and Command-line mode in one go:
" provide hjkl movements in Insert mode and Command-line mode via the <Alt> modifier key
noremap! <A-h> <Left>
noremap! <A-j> <Down>
noremap! <A-k> <Up>
noremap! <A-l> <Right>
The mapping commands for pulling Normal mode commands to Command-line mode look a bit different from the Insert mode mapping commands (because Command-line mode lacks Insert mode's Ctrl+O):
" Normal mode command(s) go… --v <-- here
cnoremap <expr> <A-h> &cedit. 'h' .'<C-c>'
cnoremap <expr> <A-j> &cedit. 'j' .'<C-c>'
cnoremap <expr> <A-k> &cedit. 'k' .'<C-c>'
cnoremap <expr> <A-l> &cedit. 'l' .'<C-c>'
cnoremap <expr> <A-b> &cedit. 'b' .'<C-c>'
cnoremap <expr> <A-w> &cedit. 'w' .'<C-c>'
CTRL-B cursor to beginning of command-line
CTRL-E cursor to end of command-line
CTRL-F opens the command-line window (unless a different key is specified in 'cedit')
CTRL-H delete the character in front of the cursor (same as <Backspace>)
CTRL-W delete the word in front of the cursor
CTRL-U delete all characters in front of the cursor
CTRL-P recall previous command-line from history (that matches pattern in front of the cursor)
CTRL-N recall next command-line from history (that matches pattern in front of the cursor)
<Up> recall previous command-line from history (that matches pattern in front of the cursor)
<Down> recall next command-line from history (that matches pattern in front of the cursor)
<S-Up> recall previous command-line from history
<S-Down> recall next command-line from history
<PageUp> recall previous command-line from history
<PageDown> recall next command-line from history
<S-Left> cursor one word left
<C-Left> cursor one word left
<S-Right> cursor one word right
<C-Right> cursor one word right
<LeftMouse> cursor at mouse click
Reference: :help ex-edit-index
Instead of having your Test2 class contain a JPanel, you should have it subclass JPanel:
public class Test2 extends JPanel {
Test2(){
...
}
More details:
JPanel is a subclass of Component, so any method that takes a Component as an argument can also take a JPanel as an argument.
Older versions didn't let you add directly to a JFrame; you had to use JFrame.getContentPane().add(Component). If you're using an older version, this might also be an issue. Newer versions of Java do let you call JFrame.add(Component) directly.
ebdiv is set style="display:none;"
it is works show & hide
$(document).ready(function(){
$("#eb").click(function(){
$("#ebdiv").toggle();
});
});
A JAR file extension is .jar and is created with jar command from command prompt (like javac command is executed). Generally, a JAR file contains Java related resources like libraries, classes etc.JAR file is like winzip file except that Jar files are platform independent.
A WAR file is simply a JAR file but contains only Web related Java files like Servlets, JSP, HTML.
To execute a WAR file, a Web server or Web container is required, for example, Tomcat or Weblogic or Websphere. To execute a JAR file, simple JDK is enough.
As required in Question::
var string1= "foo/bar/test.html";
if(string1.contains("/"))
{
var string_parts = string1.split("/");
var result = string_parts[string_parts.length - 1];
console.log(result);
}
and for question asked on url (asked for one occurence of '=' )::
[http://stackoverflow.com/questions/24156535/how-to-split-a-string-after-a-particular-character-in-jquery][1]
var string1= "Hello how are =you";
if(string1.contains("="))
{
var string_parts = string1.split("=");
var result = string_parts[string_parts.length - 1];
console.log(result);
}
If your main element has some child elements or text, you could make use of it.
Position your main element relative (or absolute/fixed) and use both :before and :after positioned absolute (in my situation it had to be absolute, don't know about your's).
Now if you want one more pseudo-element, attach an absolute :before to one of the main element's children (if you have only text, put it in a span, now you have an element), which is not relative/absolute/fixed.
This element will start acting like his owner is your main element.
HTML
<div class="circle">
<span>Some text</span>
</div>
CSS
.circle {
position: relative; /* or absolute/fixed */
}
.circle:before {
position: absolute;
content: "";
/* more styles: width, height, etc */
}
.circle:after {
position: absolute;
content: "";
/* more styles: width, height, etc */
}
.circle span {
/* not relative/absolute/fixed */
}
.circle span:before {
position: absolute;
content: "";
/* more styles: width, height, etc */
}
In reference to your comment after Ian Henry's answer, I'm not quite 100% sure I understand what you are asking.
If it is about getting double quote marks added into a string, you can concatenate the double quotes into your string, for example:
String theFirst = "Java Programming";
String ROM = "\"" + theFirst + "\"";
Or, if you want to do it with one String variable, it would be:
String ROM = "Java Programming";
ROM = "\"" + ROM + "\"";
Of course, this actually replaces the original ROM, since Java Strings are immutable.
If you are wanting to do something like turn the variable name into a String, you can't do that in Java, AFAIK.
Copy the Lombok jar into your eclipse based IDE (Eclipse/STS etc-) install folder
.ini
file for your IDEm2
repositorycp ~/.m2/repository/projectlombork/lombork-1.x.jar /path/to/IDE/lombok.jar
Edit the .ini
file in the install folder of your IDE and add the following lines below -vmargs
.
-javaagent:lombok.jar
-Xbootclasspath/a:lombok.jar
.ini
file and the name of the jar lombok.jar
Restart your IDE and rebuild/maven-update your project
Add @Repository in your dao class
@Repository
public interface UserDao extends CrudRepository<User, Long> {
User findByUsername(String username);
User findByEmail(String email);
}
Depending on what listeners you attach, trace output can go to the debug window, the console, a file, database, or all at once. The possibilities are literally endless, as implementing your own TraceListener is extremely simple.
I believe that although javascript is an option here, you have a smoother animation through forcing hardware accelerate with CSS3. You can achieve this by setting the following CSS3 properties on the moving div:
div.hardware-accelarate {
-webkit-transform: translate3d(0,0,0);
-moz-transform: translate3d(0,0,0);
-ms-transform: translate3d(0,0,0);
-o-transform: translate3d(0,0,0);
transform: translate3d(0,0,0);
}
I've made a plunkr setup for ya'll to test and tweak...
Imagine that we have 3 buttons for example
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Capture our button from layout
Button button = (Button)findViewById(R.id.corky);
Button button2 = (Button)findViewById(R.id.corky2);
Button button3 = (Button)findViewById(R.id.corky3);
// Register the onClick listener with the implementation above
button.setOnClickListener(mCorkyListener);
button2.setOnClickListener(mCorkyListener);
button3.setOnClickListener(mCorkyListener);
}
// Create an anonymous implementation of OnClickListener
private View.OnClickListener mCorkyListener = new View.OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
// Yes we will handle click here but which button clicked??? We don't know
}
};
}
So what we will do?
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Capture our button from layout
Button button = (Button)findViewById(R.id.corky);
Button button2 = (Button)findViewById(R.id.corky2);
Button button3 = (Button)findViewById(R.id.corky3);
// Register the onClick listener with the implementation above
button.setOnClickListener(mCorkyListener);
button2.setOnClickListener(mCorkyListener);
button3.setOnClickListener(mCorkyListener);
}
// Create an anonymous implementation of OnClickListener
private View.OnClickListener mCorkyListener = new View.OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
// Yes we will handle click here but which button clicked??? We don't know
// So we will make
switch (v.getId() /*to get clicked view id**/) {
case R.id.corky:
// do something when the corky is clicked
break;
case R.id.corky2:
// do something when the corky2 is clicked
break;
case R.id.corky3:
// do something when the corky3 is clicked
break;
default:
break;
}
}
};
}
Or we can do this:
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Capture our button from layout
Button button = (Button)findViewById(R.id.corky);
Button button2 = (Button)findViewById(R.id.corky2);
Button button3 = (Button)findViewById(R.id.corky3);
// Register the onClick listener with the implementation above
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// do something when the corky is clicked
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// do something when the corky2 is clicked
}
});
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// do something when the corky3 is clicked
}
});
}
}
Or we can implement View.OnClickListener and i think it's the best way:
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Capture our button from layout
Button button = (Button)findViewById(R.id.corky);
Button button2 = (Button)findViewById(R.id.corky2);
Button button3 = (Button)findViewById(R.id.corky3);
// Register the onClick listener with the implementation above
button.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// do something when the button is clicked
// Yes we will handle click here but which button clicked??? We don't know
// So we will make
switch (v.getId() /*to get clicked view id**/) {
case R.id.corky:
// do something when the corky is clicked
break;
case R.id.corky2:
// do something when the corky2 is clicked
break;
case R.id.corky3:
// do something when the corky3 is clicked
break;
default:
break;
}
}
}
Finally there is no real differences here Just "Way better than the other"
When I need to call another constructor from inside the code (not on the first line), I usually use a helper method like this:
class MyClass {
int field;
MyClass() {
init(0);
}
MyClass(int value) {
if (value<0) {
init(0);
}
else {
init(value);
}
}
void init(int x) {
field = x;
}
}
But most often I try to do it the other way around by calling the more complex constructors from the simpler ones on the first line, to the extent possible. For the above example
class MyClass {
int field;
MyClass(int value) {
if (value<0)
field = 0;
else
field = value;
}
MyClass() {
this(0);
}
}
You hide Bootstrap modals with:
$('#modal').modal('hide');
Saying $().hide()
makes the matched element invisible, but as far as the modal-related code is concerned, it's still there. See the Methods section in the Modals documentation.